-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUdsClientImpl.cs
More file actions
1651 lines (1490 loc) · 80.4 KB
/
Copy pathUdsClientImpl.cs
File metadata and controls
1651 lines (1490 loc) · 80.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CanKit.Pro.Actor;
using CanKit.Pro.IsoTp;
namespace CanKit.Pro.Uds;
/// <summary>
/// Default <see cref="IUdsClient"/> implementation. Owns a single request lock so at most one
/// UDS request is on the wire at any time (ISO 14229-1 §7.3), plus the P2/P2* wait loop that
/// implements NRC 0x78 handling.
/// </summary>
/// <remarks>
/// <para>
/// The client makes no assumptions about how the underlying <see cref="IIsoTpChannel"/> handles
/// concurrency — every write is a single <see cref="IIsoTpChannel.SendAsync"/> and every read
/// is a single <see cref="IIsoTpChannel.ReceiveAsync"/>. Because we hold the request lock
/// across the send + wait, we know the next reassembled PDU on the channel belongs to the
/// current request (the ECU only speaks in response to a request, ISO 14229-1 §7.3).
/// Multi-step services such as SecurityAccess and DownloadAsync keep that same lock across
/// every on-the-wire exchange so keep-alive traffic cannot interleave.
/// </para>
/// <para>
/// Before each send (and on abort paths) the client calls
/// <see cref="IIsoTpChannel.DiscardPendingPdus(long)"/> so a late ECU reply from a cancelled or
/// timed-out wait cannot be consumed as the answer to a later request. SID correlation during
/// the wait loop remains as a second line of defense for stray frames that arrive while a
/// request is still outstanding.
/// </para>
/// </remarks>
internal sealed class UdsClientImpl : IUdsClient
{
private const byte NegativeResponseSid = 0x7F;
private const byte PositiveResponseOffset = 0x40;
private const byte NrcResponsePending = 0x78;
private const byte SuppressPositiveResponseBit = 0x80;
private const byte NrcBusyRepeatRequest = 0x21;
/// <summary>How long Dispose waits for a request in flight to release the lock.</summary>
internal TimeSpan DisposeLockTimeout { get; set; } = TimeSpan.FromSeconds(5);
// A suppressed send draws no positive response but may still draw a negative one, up to P2
// after it went out. A following request for the same service would take that negative
// response as its own; it waits until the window is over instead (Codex on #150).
private readonly SuppressedResponseWindows _suppressedWindows = new();
private readonly IIsoTpChannel _channel;
private readonly bool _ownsChannel;
private readonly UdsClientOptions _options;
private readonly SemaphoreSlim _requestLock = new(1, 1);
private readonly CancellationTokenSource _lifetimeCts = new();
// Null in production: P2/P2*, the suppressed-response windows and the busy-repeat delay are
// measured on Stopwatch.GetTimestamp() and waited out on real timers. A test injects the
// actor whose clock the channel it opened shares; then every timestamp this class compares
// against a deadline *and* every wait for one is on that clock, so a test advances it
// instead of sleeping, and "did the answer come before the window closed" is decided by
// the test's order of events rather than by the host's scheduling (#171). Not disposed here.
private readonly ProtocolActor? _clock;
private readonly ITimeSource _time;
// Test hook: fires whenever a caller finds _requestLock already held and starts waiting on
// it -- the observable a queued call is waiting on, standing in for a wall-clock sleep
// timed to land while an earlier call holds the lock (#171). No-op in production; a test
// subscribes to learn the wait has begun rather than guessing how long the holder needs.
internal event Action? RequestLockContended;
// Test hook: fires once _requestLock has actually been taken -- contended or not -- so a
// test driving a holder that then blocks on something else (a gated channel double) knows
// the lock is held without guessing how long the acquisition itself takes (#171).
internal event Action? RequestLockAcquired;
/// <summary>
/// Acquires <see cref="_requestLock"/>, raising <see cref="RequestLockContended"/> first if
/// it is already held. The non-blocking probe
/// (<see cref="SemaphoreSlim.Wait(int, CancellationToken)"/> with a zero timeout) keeps the
/// common uncontended path free of the event's cost and, more to the point, is what makes
/// the signal mean "a holder is in the way" rather than "a wait was requested" -- the latter
/// would fire on every call, contended or not (#171). The probe takes the token too, so a
/// call cancelled before it starts throws rather than taking a free lock, as the plain
/// <see cref="SemaphoreSlim.WaitAsync(CancellationToken)"/> it replaced did.
/// </summary>
private async Task AcquireRequestLockAsync(CancellationToken cancellationToken)
{
if (!_requestLock.Wait(0, cancellationToken))
{
RequestLockContended?.Invoke();
await _requestLock.WaitAsync(cancellationToken).ConfigureAwait(false);
}
RequestLockAcquired?.Invoke();
}
private byte _currentSession = (byte)UdsSessionType.Default;
private TesterPresentKeepAlive? _keepAlive;
private int _disposed;
public UdsClientImpl(IIsoTpChannel channel, UdsClientOptions options, bool ownsChannel)
: this(channel, options, ownsChannel, clock: null)
{
}
/// <summary>
/// As the public constructor, measuring and waiting out P2, P2*, the suppressed-response
/// windows and the busy-repeat delay on <paramref name="clock"/>; null (the public
/// constructor's choice) is the wall clock. The
/// channel underneath must have been opened on that same actor, and its demux must stamp
/// frames with its time source, or a deadline and an arrival are not comparable (#171). The
/// actor is not disposed with this client.
/// </summary>
internal UdsClientImpl(IIsoTpChannel channel, UdsClientOptions options, bool ownsChannel,
ProtocolActor? clock)
{
_channel = channel;
_options = options;
_ownsChannel = ownsChannel;
_clock = clock;
_time = clock?.TimeSource ?? MonotonicTimeSource.Instance;
// Every duration here runs a timer, and a timer measures about 49 days at most: one
// beyond that would throw when it is armed, after the request went out (Codex on #150).
if (options.P2ClientMax <= TimeSpan.Zero || options.P2ClientMax > MaxTimerSpan)
throw new ArgumentException("P2ClientMax must be positive and within a timer's reach (about 49 days).", nameof(options));
if (options.P2StarClientMax <= TimeSpan.Zero || options.P2StarClientMax > MaxTimerSpan)
throw new ArgumentException("P2StarClientMax must be positive and within a timer's reach (about 49 days).", nameof(options));
if (options.MaxBusyRepeatRequests < 0)
throw new ArgumentOutOfRangeException(nameof(options),
"MaxBusyRepeatRequests must be >= 0 (0 disables the repeat).");
if (options.BusyRepeatRequestDelay < TimeSpan.Zero || options.BusyRepeatRequestDelay > MaxTimerSpan)
throw new ArgumentOutOfRangeException(nameof(options),
"BusyRepeatRequestDelay must not be negative, and must be within a timer's reach (about 49 days).");
if (options.MaxResponsePendingCount < 0)
throw new ArgumentException("MaxResponsePendingCount must be non-negative.", nameof(options));
if (options.TesterPresentPeriod <= TimeSpan.Zero || options.TesterPresentPeriod > MaxTimerSpan)
throw new ArgumentException("TesterPresentPeriod must be positive and within a timer's reach (about 49 days).", nameof(options));
}
// The longest span Task.Delay and CancellationTokenSource.CancelAfter accept.
private static readonly TimeSpan MaxTimerSpan = TimeSpan.FromMilliseconds(uint.MaxValue - 1);
public IIsoTpChannel Channel => _channel;
public UdsClientOptions Options => _options;
public byte CurrentSession => Volatile.Read(ref _currentSession);
// ---------------------------------------------------------------------------------------
// Public service methods (see IUdsClient for XML docs).
// ---------------------------------------------------------------------------------------
public async Task<byte[]> DiagnosticSessionControlAsync(UdsSessionType session,
CancellationToken cancellationToken = default)
=> await DiagnosticSessionControlAsync((byte)session, cancellationToken).ConfigureAwait(false);
public async Task<byte[]> DiagnosticSessionControlAsync(byte sessionType,
CancellationToken cancellationToken = default)
{
// The sub-function byte's bit 7 is suppressPosRspMsgIndication, not part of the session
// type; a caller passing 0x83 meant something this method does not do (it waits for
// the response), and masking it to 0x03 hid that (#57). 0x00 is ISOSAEReserved.
if (sessionType == 0 || (sessionType & SuppressPositiveResponseBit) != 0)
throw new ArgumentOutOfRangeException(nameof(sessionType), sessionType,
"Session type must be 0x01..0x7F; bit 7 is suppressPosRspMsgIndication and is not accepted here.");
byte sub = sessionType;
var request = new byte[] { (byte)UdsServiceId.DiagnosticSessionControl, sub };
var response = await ExecuteAsync(UdsServiceId.DiagnosticSessionControl, request,
cancellationToken).ConfigureAwait(false);
// Positive response layout (ISO 14229-1 §9.2.2.4):
// [0]=0x50 [1]=sessionType [2..5]=sessionParameterRecord (P2_server/P2*_server timing)
// Some ECUs omit the parameter record on legacy sessions; we accept >= 2 bytes.
if (response.Length < 2 || response[1] != sub)
throw new UdsProtocolException(
$"DiagnosticSessionControl response sub-function mismatch (expected 0x{sub:X2}, got payload length {response.Length}).");
Volatile.Write(ref _currentSession, sub);
int recordLength = response.Length - 2;
var record = new byte[recordLength];
if (recordLength > 0) Buffer.BlockCopy(response, 2, record, 0, recordLength);
return record;
}
public async Task<byte[]> EcuResetAsync(UdsEcuResetType resetType,
CancellationToken cancellationToken = default)
{
var request = new byte[] { (byte)UdsServiceId.EcuReset, (byte)resetType };
var response = await ExecuteAsync(UdsServiceId.EcuReset, request,
cancellationToken).ConfigureAwait(false);
// Positive response layout: [0]=0x51 [1]=resetType [2]?=powerDownTime.
if (response.Length < 2 || response[1] != (byte)resetType)
throw new UdsProtocolException(
$"ECUReset response reset-type mismatch (expected 0x{(byte)resetType:X2}, got payload length {response.Length}).");
// ISO 14229-1: after a successful ECUReset the server returns to the default session.
// Mirror that in CurrentSession so later calls do not assume a stale negotiated session.
Volatile.Write(ref _currentSession, (byte)UdsSessionType.Default);
int tail = response.Length - 2;
var record = new byte[tail];
if (tail > 0) Buffer.BlockCopy(response, 2, record, 0, tail);
return record;
}
public async Task<byte[]> ReadDataByIdentifierAsync(ushort dataIdentifier,
CancellationToken cancellationToken = default)
{
var request = new byte[]
{
(byte)UdsServiceId.ReadDataByIdentifier,
(byte)(dataIdentifier >> 8),
(byte)(dataIdentifier & 0xFF),
};
var response = await ExecuteAsync(UdsServiceId.ReadDataByIdentifier, request,
cancellationToken).ConfigureAwait(false);
// Positive response: [0]=0x62 [1..2]=DID [3..]=dataRecord.
if (response.Length < 3)
throw new UdsProtocolException(
$"ReadDataByIdentifier response too short ({response.Length} bytes).");
ushort echoed = (ushort)((response[1] << 8) | response[2]);
if (echoed != dataIdentifier)
throw new UdsProtocolException(
$"ReadDataByIdentifier response DID mismatch (requested 0x{dataIdentifier:X4}, got 0x{echoed:X4}).");
int len = response.Length - 3;
var data = new byte[len];
if (len > 0) Buffer.BlockCopy(response, 3, data, 0, len);
return data;
}
public async Task<IReadOnlyDictionary<ushort, byte[]>> ReadDataByIdentifierAsync(
IReadOnlyList<ushort> dataIdentifiers,
IReadOnlyDictionary<ushort, int> dataRecordLengths,
CancellationToken cancellationToken = default)
{
if (dataIdentifiers is null) throw new ArgumentNullException(nameof(dataIdentifiers));
if (dataRecordLengths is null) throw new ArgumentNullException(nameof(dataRecordLengths));
if (dataIdentifiers.Count == 0)
throw new ArgumentException("At least one DID is required.", nameof(dataIdentifiers));
var requested = new HashSet<ushort>();
foreach (var did in dataIdentifiers)
{
if (!requested.Add(did))
throw new ArgumentException(
$"Duplicate DID 0x{did:X4} in multi-DID request.", nameof(dataIdentifiers));
if (!dataRecordLengths.TryGetValue(did, out int len))
throw new ArgumentException(
$"Missing dataRecord length for DID 0x{did:X4}.", nameof(dataRecordLengths));
if (len < 0)
throw new ArgumentException(
$"dataRecord length for DID 0x{did:X4} must be non-negative.",
nameof(dataRecordLengths));
}
var request = new byte[1 + dataIdentifiers.Count * 2];
request[0] = (byte)UdsServiceId.ReadDataByIdentifier;
for (int i = 0; i < dataIdentifiers.Count; i++)
{
request[1 + i * 2] = (byte)(dataIdentifiers[i] >> 8);
request[2 + i * 2] = (byte)(dataIdentifiers[i] & 0xFF);
}
var response = await ExecuteAsync(UdsServiceId.ReadDataByIdentifier, request,
cancellationToken).ConfigureAwait(false);
// Multi-DID positive response (ISO 14229-1 §9.3.4.4): [0]=0x62 then
// (DID[2 bytes] + dataRecord[len bytes])* for every returned DID. Lengths are not on
// the wire — parse strictly from the caller-supplied DID definition so payload bytes
// that happen to match another DID are never treated as record boundaries.
var result = new Dictionary<ushort, byte[]>(dataIdentifiers.Count);
int cursor = 1;
while (cursor < response.Length)
{
if (cursor + 2 > response.Length)
throw new UdsProtocolException(
$"Multi-DID ReadDataByIdentifier response truncated while reading DID at offset {cursor}.");
ushort did = (ushort)((response[cursor] << 8) | response[cursor + 1]);
if (!requested.Contains(did))
throw new UdsProtocolException(
$"Multi-DID ReadDataByIdentifier response contains unexpected DID 0x{did:X4}.");
if (result.ContainsKey(did))
throw new UdsProtocolException(
$"Multi-DID ReadDataByIdentifier response contains duplicate DID 0x{did:X4}.");
int recLen = dataRecordLengths[did];
int dataStart = cursor + 2;
if (dataStart + recLen > response.Length)
throw new UdsProtocolException(
$"Multi-DID ReadDataByIdentifier response truncated for DID 0x{did:X4} " +
$"(expected {recLen} data bytes, {response.Length - dataStart} remain).");
var rec = new byte[recLen];
if (recLen > 0) Buffer.BlockCopy(response, dataStart, rec, 0, recLen);
result[did] = rec;
cursor = dataStart + recLen;
}
if (result.Count != dataIdentifiers.Count)
{
var missing = new List<string>();
foreach (var did in dataIdentifiers.Where(did => !result.ContainsKey(did)))
missing.Add($"0x{did:X4}");
throw new UdsProtocolException(
$"Multi-DID ReadDataByIdentifier response missing DIDs: {string.Join(", ", missing)}.");
}
return result;
}
public async Task WriteDataByIdentifierAsync(ushort dataIdentifier, ReadOnlyMemory<byte> data,
CancellationToken cancellationToken = default)
{
var request = new byte[3 + data.Length];
request[0] = (byte)UdsServiceId.WriteDataByIdentifier;
request[1] = (byte)(dataIdentifier >> 8);
request[2] = (byte)(dataIdentifier & 0xFF);
if (data.Length > 0) data.Span.CopyTo(request.AsSpan(3));
var response = await ExecuteAsync(UdsServiceId.WriteDataByIdentifier, request,
cancellationToken).ConfigureAwait(false);
// Positive response: [0]=0x6E [1..2]=DID.
if (response.Length < 3)
throw new UdsProtocolException(
$"WriteDataByIdentifier response too short ({response.Length} bytes).");
ushort echoed = (ushort)((response[1] << 8) | response[2]);
if (echoed != dataIdentifier)
throw new UdsProtocolException(
$"WriteDataByIdentifier response DID mismatch (wrote 0x{dataIdentifier:X4}, got 0x{echoed:X4}).");
}
public async Task<byte[]> RoutineControlAsync(UdsRoutineControlType routineType,
ushort routineIdentifier, ReadOnlyMemory<byte> routineControlOptionRecord = default,
CancellationToken cancellationToken = default)
{
var request = new byte[4 + routineControlOptionRecord.Length];
request[0] = (byte)UdsServiceId.RoutineControl;
request[1] = (byte)routineType;
request[2] = (byte)(routineIdentifier >> 8);
request[3] = (byte)(routineIdentifier & 0xFF);
if (routineControlOptionRecord.Length > 0)
routineControlOptionRecord.Span.CopyTo(request.AsSpan(4));
var response = await ExecuteAsync(UdsServiceId.RoutineControl, request,
cancellationToken).ConfigureAwait(false);
// Positive response: [0]=0x71 [1]=sub [2..3]=routineId [4..]=routineInfo+statusRecord.
if (response.Length < 4 || response[1] != (byte)routineType)
throw new UdsProtocolException(
$"RoutineControl response sub-function mismatch (expected 0x{(byte)routineType:X2}).");
ushort echoed = (ushort)((response[2] << 8) | response[3]);
if (echoed != routineIdentifier)
throw new UdsProtocolException(
$"RoutineControl response routineId mismatch (requested 0x{routineIdentifier:X4}, got 0x{echoed:X4}).");
int tail = response.Length - 4;
var info = new byte[tail];
if (tail > 0) Buffer.BlockCopy(response, 4, info, 0, tail);
return info;
}
public async Task SecurityAccessAsync(byte requestSeedLevel, Func<byte[], byte[]> computeKey,
CancellationToken cancellationToken = default)
{
if (computeKey is null) throw new ArgumentNullException(nameof(computeKey));
if (requestSeedLevel == 0 || requestSeedLevel >= 0x7F || (requestSeedLevel & 0x01) == 0)
throw new ArgumentOutOfRangeException(nameof(requestSeedLevel),
"SecurityAccess requestSeedLevel must be an odd byte in 0x01..0x7F.");
byte sendKeyLevel = (byte)(requestSeedLevel + 1);
ThrowIfDisposed();
using var linked = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken, _lifetimeCts.Token);
var linkedToken = linked.Token;
// Hold the request lock across seed + sendKey so TesterPresent keep-alive (or another
// UDS call) cannot interleave and break the ISO 14229-1 security-access sequence
// (NRC requestSequenceError on real ECUs).
await AcquireRequestLockAsync(linkedToken).ConfigureAwait(false);
try
{
var seedRequest = new byte[] { (byte)UdsServiceId.SecurityAccess, requestSeedLevel };
var seedResponse = await ExecuteCoreAsync(UdsServiceId.SecurityAccess, seedRequest,
linkedToken).ConfigureAwait(false);
// Positive response: [0]=0x67 [1]=requestSeedLevel [2..]=seed. A seed of all zeroes
// means "already unlocked" per ISO 14229-1 §9.4.5.3 -- the length is the server's
// usual seed length, the bytes are 0x00 -- and the client MUST NOT send the key
// (#29): a key computed for that seed gets NRC 0x24 back. A zero-length seed is kept
// as the defensive reading of the same answer.
if (seedResponse.Length < 2 || seedResponse[1] != requestSeedLevel)
throw new UdsProtocolException(
$"SecurityAccess seed response sub-function mismatch (expected 0x{requestSeedLevel:X2}).");
int seedLen = seedResponse.Length - 2;
if (seedLen == 0) return;
if (IsAllZero(seedResponse, 2, seedLen)) return;
var seed = new byte[seedLen];
Buffer.BlockCopy(seedResponse, 2, seed, 0, seedLen);
byte[] key = computeKey(seed)
?? throw new UdsProtocolException("SecurityAccess computeKey callback returned null.");
if (key.Length == 0)
throw new UdsProtocolException("SecurityAccess computeKey callback returned an empty key.");
var keyRequest = new byte[2 + key.Length];
keyRequest[0] = (byte)UdsServiceId.SecurityAccess;
keyRequest[1] = sendKeyLevel;
Buffer.BlockCopy(key, 0, keyRequest, 2, key.Length);
var keyResponse = await ExecuteCoreAsync(UdsServiceId.SecurityAccess, keyRequest,
linkedToken).ConfigureAwait(false);
if (keyResponse.Length < 2 || keyResponse[1] != sendKeyLevel)
throw new UdsProtocolException(
$"SecurityAccess sendKey response sub-function mismatch (expected 0x{sendKeyLevel:X2}).");
}
finally
{
_requestLock.Release();
}
}
public async Task TesterPresentAsync(bool suppressPositiveResponse = true,
CancellationToken cancellationToken = default)
{
byte sub = suppressPositiveResponse ? SuppressPositiveResponseBit : (byte)0x00;
var request = new byte[] { (byte)UdsServiceId.TesterPresent, sub };
if (suppressPositiveResponse)
{
await SendWithoutResponseAsync(request, cancellationToken).ConfigureAwait(false);
return;
}
var response = await ExecuteAsync(UdsServiceId.TesterPresent, request,
cancellationToken).ConfigureAwait(false);
if (response.Length < 2 || response[1] != 0x00)
throw new UdsProtocolException(
$"TesterPresent response sub-function mismatch (expected 0x00, got payload length {response.Length}).");
}
public IDisposable StartTesterPresentKeepAlive(TimeSpan? period = null)
{
ThrowIfDisposed();
var interval = period ?? _options.TesterPresentPeriod;
if (interval <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(period), "TesterPresent period must be positive.");
var candidate = new TesterPresentKeepAlive(this, interval,
_options.KeepAliveSuppressPositiveResponse);
if (Interlocked.CompareExchange(ref _keepAlive, candidate, null) is not null)
{
candidate.Dispose();
throw new InvalidOperationException(
"A TesterPresent keep-alive is already running; dispose it before starting another.");
}
candidate.Start();
return candidate;
}
public async Task<byte[]> SendRawAsync(ReadOnlyMemory<byte> request,
CancellationToken cancellationToken = default)
{
if (request.Length == 0)
throw new ArgumentException("Request must contain at least a SID byte.", nameof(request));
var sid = (UdsServiceId)request.Span[0];
var copy = new byte[request.Length];
request.Span.CopyTo(copy);
// A request with suppressPosRspMsgIndication set gets no positive response; waiting P2
// for one ended in a timeout every time (#57). Sent the way a suppressed TesterPresent
// is, and an empty response returned. A negative response the server may still send is
// not waited for either -- the next request's discard drops it.
if (copy.Length >= 2 && HasSubFunction(sid) && (copy[1] & SuppressPositiveResponseBit) != 0)
{
await SendWithoutResponseAsync(copy, cancellationToken).ConfigureAwait(false);
return Array.Empty<byte>();
}
return await ExecuteAsync(sid, copy, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Fire-and-forget under the request lock: the frame goes out without interleaving a real
/// request, and no response is waited for. The lifetime token is linked so Dispose()
/// cancels a wait or send still in progress, as ExecuteAsync does.
/// </summary>
private async Task SendWithoutResponseAsync(byte[] request, CancellationToken cancellationToken)
{
ThrowIfDisposed();
using var linked = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken, _lifetimeCts.Token);
var linkedToken = linked.Token;
await AcquireRequestLockAsync(linkedToken).ConfigureAwait(false);
try
{
// The stale-reply discard the answered path runs before its send, here too: a late
// 0x78 to an earlier request for this service, queued since that request's abort,
// would otherwise be read by the next call's wait-out as inside this send's window
// -- it predates the send, which the window's end alone does not say -- and move
// the window out by P2* for nothing (Codex on #150). A 0x78 for a service with a
// window still open is routed to it by the discard, as always.
await DiscardStalePdusAsync().ConfigureAwait(false);
// Noted before the send as well: cancelled between the driver's acceptance and the
// confirmation, the frame is on the bus and may still be answered (Codex on #150).
// Moved out to the transmit stamp afterwards.
bool hadWindow = _suppressedWindows.TryGetDeadline(request[0], out var previousUntil);
_suppressedWindows.Note(request[0], Now(), _options.P2ClientMax, _time.Frequency);
IsoTpTransmitStamps stamps;
try
{
stamps = await _channel.SendWithTransmitStampAsync(request, linkedToken).ConfigureAwait(false);
}
catch (Exception ex) when (RefusedBeforeTransmission(ex))
{
// Nothing reached the bus: the window noted for it is put back (Codex on #150).
_suppressedWindows.Restore(request[0], hadWindow, previousUntil);
throw;
}
catch
{
// A send that leaves by exception -- cancelled, or a transport fault -- may
// have put the frame on the bus after the provisional window ran out; its P2
// from the transmission is at most P2 from now (Codex on #150).
_suppressedWindows.Note(request[0], Now(), _options.P2ClientMax, _time.Frequency);
throw;
}
var sent = stamps.LastFrameTransmitTimestamp > 0 ? stamps.LastFrameTransmitTimestamp : Now();
_suppressedWindows.Note(request[0], sent, _options.P2ClientMax, _time.Frequency);
}
finally
{
_requestLock.Release();
}
}
// The channel refuses a request before transmitting it with an argument error -- an
// empty or oversized PDU -- or because it is disposed; a cancellation or a transport fault
// comes after the frame may be out.
private static bool RefusedBeforeTransmission(Exception ex)
=> ex is ArgumentException or InvalidOperationException or ObjectDisposedException;
// Under the request lock. A request for a service with a suppressed send still open waits
// out that send's P2, reading what arrives: it is the suppressed send's and is dropped --
// except NRC 0x78, which says the peer's final answer is still coming and moves the window
// out by P2* (Codex on #150). So a late negative response to the suppressed send cannot
// be taken for this request's.
private async Task WaitOutSuppressedResponseWindowAsync(UdsServiceId serviceId, CancellationToken linkedToken)
{
byte sid = (byte)serviceId;
if (!_suppressedWindows.TryGetDeadline(sid, out var until)) return;
bool waitedOut = false;
try
{
while (true)
{
var remaining = SuppressedResponseWindows.Remaining(until, Now(), _time.Frequency);
if (remaining <= TimeSpan.Zero)
{
// The window is over as measured now -- but a 0x78 may be queued already,
// and it moves the window out (Bugbot on #150). Only an empty inbox ends
// it, and only once the channel has settled: a 0x78 stamped inside the
// window may still be on its way through its actor (Codex on #150).
await SettleAsync().ConfigureAwait(false);
if (DrainExtends(sid, ref until)) continue;
break;
}
using var slice = CancelAt(until);
using var combined = CancellationTokenSource.CreateLinkedTokenSource(linkedToken, slice.Token);
IsoTpReceivedPdu pdu;
try
{
pdu = await _channel.ReceiveWithArrivalAsync(combined.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (slice.IsCancellationRequested && !linkedToken.IsCancellationRequested)
{
await SettleAsync().ConfigureAwait(false);
if (DrainExtends(sid, ref until)) continue;
break;
}
catch (IsoTpException)
{
// A queued transport fault -- an aborted reassembly from before -- is stale
// here, as it is in the discard that follows (Bugbot on #150).
continue;
}
ExtendOnPending(sid, pdu, ref until);
}
waitedOut = true;
}
finally
{
// A cancelled wait keeps what remains of the window, extensions included, for the
// next request (Bugbot on #150).
if (waitedOut) _suppressedWindows.Forget(sid);
else _suppressedWindows.Extend(sid, until);
}
}
// Reads whatever is queued; true when a 0x78 among it moved this service's window out.
private bool DrainExtends(byte sid, ref long until)
{
bool extended = false;
while (true)
{
IsoTpReceivedPdu queued;
try
{
if (!_channel.TryReceiveWithArrival(out queued)) break;
}
catch (IsoTpException)
{
continue; // a stale transport fault, dropped as the discard would (Bugbot on #150)
}
extended |= ExtendOnPending(sid, queued, ref until);
}
return extended;
}
// A 0x78 heard while waiting out one service's window may be for another service whose
// window is open too; it moves that service's window out in the table, and this
// service's locally (Codex on #150). True when this service's moved.
private bool ExtendOnPending(byte sid, in IsoTpReceivedPdu pdu, ref long until)
{
var data = pdu.Pdu;
if (data.Length < 3 || data[0] != NegativeResponseSid || data[2] != NrcResponsePending)
return false;
var extendedUntil = pdu.FirstFrameArrivalTimestamp + Ticks(_options.P2StarClientMax);
if (data[1] != sid)
{
// Another service's: only a window still open when the 0x78 arrived (Codex on #150).
_suppressedWindows.ExtendIfOpenAt(data[1], pdu.FirstFrameArrivalTimestamp, extendedUntil);
return false;
}
// This service's: likewise only if the window was still open when it arrived -- a
// 0x78 queued after P2 ran out answers nothing the window covers (Codex on #150).
if (pdu.FirstFrameArrivalTimestamp > until || extendedUntil <= until) return false;
until = extendedUntil;
return true;
}
// The services whose second byte is a sub-function parameter, and so carry the
// suppressPosRspMsgIndication bit (ISO 14229-1 table 2, "sub-function" column). Not 0x2A:
// its transmissionMode is a plain parameter (Codex on #150).
private static bool HasSubFunction(UdsServiceId sid) => (byte)sid switch
{
0x10 or 0x11 or 0x19 or 0x27 or 0x28 or 0x29 or 0x2C or 0x31 or 0x3E
or 0x83 or 0x85 or 0x86 or 0x87 => true,
_ => false,
};
// ---------------------------------------------------------------------------------------
// Upload / Download (SRS FR-UDS-012, ISO 14229-1 §14).
// ---------------------------------------------------------------------------------------
public async Task<UdsDownloadResponse> RequestDownloadAsync(
byte dataFormatIdentifier,
byte addressAndLengthFormatIdentifier,
ReadOnlyMemory<byte> memoryAddress,
ReadOnlyMemory<byte> memorySize,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
using var linked = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken, _lifetimeCts.Token);
var linkedToken = linked.Token;
await AcquireRequestLockAsync(linkedToken).ConfigureAwait(false);
try
{
return await RequestTransferSetupCoreAsync(
UdsServiceId.RequestDownload,
dataFormatIdentifier,
addressAndLengthFormatIdentifier,
memoryAddress,
memorySize,
(lfid, maxBlock) => new UdsDownloadResponse(lfid, maxBlock),
linkedToken).ConfigureAwait(false);
}
finally
{
_requestLock.Release();
}
}
public async Task<UdsUploadResponse> RequestUploadAsync(
byte dataFormatIdentifier,
byte addressAndLengthFormatIdentifier,
ReadOnlyMemory<byte> memoryAddress,
ReadOnlyMemory<byte> memorySize,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
using var linked = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken, _lifetimeCts.Token);
var linkedToken = linked.Token;
await AcquireRequestLockAsync(linkedToken).ConfigureAwait(false);
try
{
return await RequestTransferSetupCoreAsync(
UdsServiceId.RequestUpload,
dataFormatIdentifier,
addressAndLengthFormatIdentifier,
memoryAddress,
memorySize,
(lfid, maxBlock) => new UdsUploadResponse(lfid, maxBlock),
linkedToken).ConfigureAwait(false);
}
finally
{
_requestLock.Release();
}
}
/// <summary>
/// Assumes <see cref="_requestLock"/> is already held. Builds the 0x34/0x35 request, hands
/// it to <see cref="ExecuteCoreAsync"/>, and parses the maxNumberOfBlockLength.
/// </summary>
private async Task<TResult> RequestTransferSetupCoreAsync<TResult>(
UdsServiceId serviceId,
byte dataFormatIdentifier,
byte addressAndLengthFormatIdentifier,
ReadOnlyMemory<byte> memoryAddress,
ReadOnlyMemory<byte> memorySize,
Func<byte, ulong, TResult> project,
CancellationToken linkedToken)
{
int addressWidth = addressAndLengthFormatIdentifier & 0x0F;
int sizeWidth = (addressAndLengthFormatIdentifier >> 4) & 0x0F;
if (addressWidth == 0)
throw new ArgumentOutOfRangeException(nameof(addressAndLengthFormatIdentifier),
"memoryAddress width nibble (low nibble) must be non-zero.");
if (sizeWidth == 0)
throw new ArgumentOutOfRangeException(nameof(addressAndLengthFormatIdentifier),
"memorySize width nibble (high nibble) must be non-zero.");
if (memoryAddress.Length != addressWidth)
throw new ArgumentOutOfRangeException(nameof(memoryAddress),
$"memoryAddress length ({memoryAddress.Length}) does not match the width nibble ({addressWidth}) in addressAndLengthFormatIdentifier.");
if (memorySize.Length != sizeWidth)
throw new ArgumentOutOfRangeException(nameof(memorySize),
$"memorySize length ({memorySize.Length}) does not match the width nibble ({sizeWidth}) in addressAndLengthFormatIdentifier.");
var request = new byte[3 + addressWidth + sizeWidth];
request[0] = (byte)serviceId;
request[1] = dataFormatIdentifier;
request[2] = addressAndLengthFormatIdentifier;
memoryAddress.Span.CopyTo(request.AsSpan(3));
memorySize.Span.CopyTo(request.AsSpan(3 + addressWidth));
var response = await ExecuteCoreAsync(serviceId, request, linkedToken).ConfigureAwait(false);
// Positive response layout (ISO 14229-1 §14.2.2.4 / §14.1.2.4):
// [0]=respSid [1]=lengthFormatIdentifier [2..]=maxNumberOfBlockLength (big-endian).
if (response.Length < 2)
throw new UdsProtocolException(
$"{serviceId} response too short ({response.Length} bytes).");
byte lengthFormatIdentifier = response[1];
int maxBlockWidth = (lengthFormatIdentifier >> 4) & 0x0F;
if (maxBlockWidth == 0)
throw new UdsProtocolException(
$"{serviceId} response lengthFormatIdentifier 0x{lengthFormatIdentifier:X2} has zero maxNumberOfBlockLength width.");
if (maxBlockWidth > 8)
throw new UdsProtocolException(
$"{serviceId} response lengthFormatIdentifier 0x{lengthFormatIdentifier:X2} claims {maxBlockWidth} bytes of maxNumberOfBlockLength; the client caps this at 8 (ulong).");
if (response.Length < 2 + maxBlockWidth)
throw new UdsProtocolException(
$"{serviceId} response truncated (need {2 + maxBlockWidth} bytes for maxNumberOfBlockLength, got {response.Length}).");
ulong maxNumberOfBlockLength = 0;
for (int i = 0; i < maxBlockWidth; i++)
maxNumberOfBlockLength = (maxNumberOfBlockLength << 8) | response[2 + i];
return project(lengthFormatIdentifier, maxNumberOfBlockLength);
}
public async Task<byte[]> TransferDataAsync(byte blockSequenceCounter,
ReadOnlyMemory<byte> data, CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
using var linked = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken, _lifetimeCts.Token);
var linkedToken = linked.Token;
await AcquireRequestLockAsync(linkedToken).ConfigureAwait(false);
try
{
return await TransferDataCoreAsync(blockSequenceCounter, data, linkedToken)
.ConfigureAwait(false);
}
finally
{
_requestLock.Release();
}
}
/// <summary>
/// Assumes <see cref="_requestLock"/> is already held. Sends one 0x36 request and validates
/// the echoed block-sequence counter.
/// </summary>
private async Task<byte[]> TransferDataCoreAsync(byte blockSequenceCounter,
ReadOnlyMemory<byte> data, CancellationToken linkedToken)
{
var request = new byte[2 + data.Length];
request[0] = (byte)UdsServiceId.TransferData;
request[1] = blockSequenceCounter;
if (data.Length > 0) data.Span.CopyTo(request.AsSpan(2));
var response = await ExecuteCoreAsync(UdsServiceId.TransferData, request,
linkedToken).ConfigureAwait(false);
// Positive response: [0]=0x76 [1]=blockSequenceCounter [2..]=transferResponseParameterRecord.
if (response.Length < 2)
throw new UdsProtocolException(
$"TransferData response too short ({response.Length} bytes).");
if (response[1] != blockSequenceCounter)
throw new UdsProtocolException(
$"TransferData response blockSequenceCounter mismatch (sent 0x{blockSequenceCounter:X2}, got 0x{response[1]:X2}).");
int tail = response.Length - 2;
var record = new byte[tail];
if (tail > 0) Buffer.BlockCopy(response, 2, record, 0, tail);
return record;
}
public async Task RequestTransferExitAsync(
ReadOnlyMemory<byte> transferRequestParameterRecord = default,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
using var linked = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken, _lifetimeCts.Token);
var linkedToken = linked.Token;
await AcquireRequestLockAsync(linkedToken).ConfigureAwait(false);
try
{
await RequestTransferExitCoreAsync(transferRequestParameterRecord, linkedToken)
.ConfigureAwait(false);
}
finally
{
_requestLock.Release();
}
}
/// <summary>
/// Assumes <see cref="_requestLock"/> is already held. Sends one 0x37 request; the
/// vendor-specific transferResponseParameterRecord is discarded (SID correlation is done
/// by <see cref="ExecuteCoreAsync"/>).
/// </summary>
private async Task RequestTransferExitCoreAsync(
ReadOnlyMemory<byte> transferRequestParameterRecord,
CancellationToken linkedToken)
{
var request = new byte[1 + transferRequestParameterRecord.Length];
request[0] = (byte)UdsServiceId.RequestTransferExit;
if (transferRequestParameterRecord.Length > 0)
transferRequestParameterRecord.Span.CopyTo(request.AsSpan(1));
_ = await ExecuteCoreAsync(UdsServiceId.RequestTransferExit, request,
linkedToken).ConfigureAwait(false);
}
public async Task DownloadAsync(
byte dataFormatIdentifier,
byte addressAndLengthFormatIdentifier,
ReadOnlyMemory<byte> memoryAddress,
ReadOnlyMemory<byte> memorySize,
ReadOnlyMemory<byte> data,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
using var linked = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken, _lifetimeCts.Token);
var linkedToken = linked.Token;
// Local hardening for the common uncompressed/unencrypted case (DFI 0x00):
// memorySize is the big-endian count RequestDownload tells the ECU, and it has to
// match the number of bytes the following TransferData blocks will actually carry.
// When DFI selects compression or encryption, memorySize describes the decoded
// target memory range while data holds the encoded bytes this client forwards
// unchanged, so their lengths normally differ — skip decode and equality then.
// RequestTransferSetupCoreAsync still forwards the original ALFI-width bytes.
// This client cites ISO 14229-1 §14.3 for the block-sequence counter only; the
// length check is ours. Reject before RequestDownload so the ECU is never given a
// count we will not send, and refuse sizes that do not fit in ulong so a truncated
// decode cannot let a mismatch through.
if (dataFormatIdentifier == 0x00)
{
ReadOnlySpan<byte> sizeSpan = memorySize.Span;
if (sizeSpan.Length > 8)
{
for (int i = 0; i < sizeSpan.Length - 8; i++)
{
if (sizeSpan[i] != 0)
throw new ArgumentOutOfRangeException(
nameof(memorySize),
"memorySize exceeds what a ulong can represent (nonzero high-order bytes).");
}
sizeSpan = sizeSpan.Slice(sizeSpan.Length - 8);
}
ulong totalBytes = 0;
for (int i = 0; i < sizeSpan.Length; i++)
totalBytes = (totalBytes << 8) | sizeSpan[i];
if (totalBytes != (ulong)data.Length)
throw new ArgumentException(
$"memorySize ({totalBytes}) does not match data.Length ({data.Length}).",
nameof(memorySize));
}
// Hold the request lock across the entire 0x34 → 0x36…0x36 → 0x37 sequence so
// TesterPresent keep-alive (or any other UDS call) cannot interleave mid-download and
// desynchronise the ECU's block-sequence counter (ISO 14229-1 §14.3). Mirror of
// SecurityAccessAsync: acquire the lock once, then call the *Core helpers that assume
// the lock is held. The public RequestDownload/TransferData/RequestTransferExit APIs
// remain unchanged for single-step callers.
await AcquireRequestLockAsync(linkedToken).ConfigureAwait(false);
try
{
var download = await RequestTransferSetupCoreAsync(
UdsServiceId.RequestDownload,
dataFormatIdentifier,
addressAndLengthFormatIdentifier,
memoryAddress,
memorySize,
(lfid, maxBlock) => new UdsDownloadResponse(lfid, maxBlock),
linkedToken).ConfigureAwait(false);
// TransferData request layout: [0]=0x36 [1]=BSC [2..]=payload.
// The ECU-reported maxNumberOfBlockLength is the TOTAL request size in bytes
// (including the SID and the BSC byte), so each chunk carries at most
// maxNumberOfBlockLength - 2 payload bytes.
ulong maxBlock = download.MaxNumberOfBlockLength;
if (maxBlock <= 2)
throw new UdsProtocolException(
$"ECU-reported maxNumberOfBlockLength={maxBlock} leaves no room for TransferData payload " +
"(need at least 3 to carry SID + BSC + one payload byte).");
// Cap the chunk size at int.MaxValue so we can slice ReadOnlyMemory<byte>. Real ECUs
// report block lengths that fit in a few kB; the cap is defensive against absurd LFIs.
int chunkSize = maxBlock - 2 > int.MaxValue ? int.MaxValue : (int)(maxBlock - 2);
int offset = 0;
byte bsc = 0x01; // ISO 14229-1 §14.3.2: first TransferData uses BSC=0x01.
while (offset < data.Length)
{
int remaining = data.Length - offset;
int take = remaining < chunkSize ? remaining : chunkSize;
var chunk = data.Slice(offset, take);
_ = await TransferDataCoreAsync(bsc, chunk, linkedToken).ConfigureAwait(false);
offset += take;
unchecked { bsc++; } // Wraps 0xFF → 0x00 → 0x01 … as required by ISO 14229-1 §14.3.2.
}
await RequestTransferExitCoreAsync(default, linkedToken).ConfigureAwait(false);
}
finally
{
_requestLock.Release();
}
}
public async Task<byte[]> UploadAsync(
byte dataFormatIdentifier,
byte addressAndLengthFormatIdentifier,
ReadOnlyMemory<byte> memoryAddress,
ReadOnlyMemory<byte> memorySize,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
using var linked = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken, _lifetimeCts.Token);
var linkedToken = linked.Token;
// Declared byte count to read: big-endian, same wire layout as in RequestDownload/Upload.
ulong totalBytes = 0;
for (int i = 0; i < memorySize.Length; i++)
totalBytes = (totalBytes << 8) | memorySize.Span[i];
if (totalBytes > int.MaxValue)
throw new UdsProtocolException(
$"Declared memorySize {totalBytes} exceeds what a single upload can buffer.");
// Same lock discipline as DownloadAsync: one continuous 0x35 → 0x36…0x36 → 0x37
// sequence, so keep-alive traffic cannot desynchronise the ECU's block-sequence counter.
await AcquireRequestLockAsync(linkedToken).ConfigureAwait(false);
try
{
_ = await RequestTransferSetupCoreAsync(
UdsServiceId.RequestUpload,
dataFormatIdentifier,
addressAndLengthFormatIdentifier,
memoryAddress,
memorySize,