Repository navigation
Expand file tree
/
Copy pathSRTPClient.cs
More file actions
1006 lines (1003 loc) · 49.3 KB
/
Copy pathSRTPClient.cs
File metadata and controls
1006 lines (1003 loc) · 49.3 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.Buffers.Binary;
using System.Collections.Concurrent;
using System.Diagnostics;
namespace ModemAPI
{
public class SRTPClient
{
/// <summary>
/// The most data one message can carry: 8 bytes of the sequential number and the data have to fit into one tetronet packet.
/// </summary>
public const int MaxMessageLength = 59992;
/// <summary>
/// Metadata of data packets sent by clients that understand batched acknowledgements. Older clients ignore metadata,
/// so they keep receiving data as before and keep acknowledging every packet.
/// </summary>
private const string BatchedAckDataTag = "srtp2";
/// <summary>
/// Every message carries <see cref="BatchedAckDataTag"/>, ":" and the ID of its stream (8 hex digits), and batched
/// acknowledgements carry the ID of the stream they acknowledge. So an acknowledgement of one stream can't acknowledge another
/// one, and <see cref="SRTPServer"/> sees by any message, that a client started a new stream with the same ConnectionID.
/// Receivers, that don't know the ID, take such messages for v1 ones and acknowledge every message.
/// </summary>
private const string StreamDataTagPrefix = BatchedAckDataTag + ":";
// the ID of the stream this client sends
private readonly string StreamId = ((uint)Random.Shared.NextInt64(1, uint.MaxValue)).ToString("x8");
// metadata of every message of this client's stream
private readonly string StreamDataTag;
// the ID of the stream this client receives: the one of the first message that came; null while it's unknown, or the sender has none
private string? PeerStreamId = null;
// the last foreign stream reported through OnError, so every new one is reported once
private string? ReportedForeignStreamId = null;
/// <summary>
/// Whether messages of another stream are reported through <see cref="OnError"/>; off for sessions of <see cref="SRTPServer"/>,
/// which opens a new session for the new stream itself.
/// </summary>
internal bool ReportsForeignStreams = true;
// the moment the last packet of this session arrived (Stopwatch), for the idle timeout of SRTPServer
private long LastPacketTimestamp = Stopwatch.GetTimestamp();
/// <summary>
/// Metadata of a batched acknowledgement: 8 bytes "every packet up to this number is delivered", followed by an
/// optional bitmap of packets received after it (bit i = packet number + 1 + i). It is only sent to peers, whose data carried <see cref="BatchedAckDataTag"/>.
/// </summary>
private const string BatchedAckTag = "srtp2a";
private const string StreamAckTagPrefix = BatchedAckTag + ":";
private const int SelectiveAckBits = 256;
private Address? CommunicatingWith = null;
private uint ConnectionID = 0;
private string QueryType = "";
private IModem Modem;
private long LastReceived = -1; // every packet up to this one is delivered to OnMessageReceived
private long HighestContiguousReceived = -1; // every packet up to this one is received (delivered or waiting in ReorderingBuffer)
private long SequentialPacketNumber = 0;
private long LowestUnacknowledged = 0; // sender side: packets below this one are acknowledged
private volatile bool IsClosed = false;
private int CloseStarted = 0;
private int TicksTimeout;
// retransmission timeout from the measured round trip, as RFC 6298, but never shorter than TicksTimeout; changed under AcknowledgementLock
private long SmoothedRttTicks = -1;
private long RttVarianceTicks = 0;
private long RetransmissionTimeoutTicks;
private static readonly long MaxRetransmissionTimeoutTicks = TimeSpan.FromSeconds(60).Ticks;
// every timeout doubles the wait, up to 2^3 = 8 retransmission timeouts: of the packet itself, and of every packet till
// the next round trip is measured (RFC 6298, 5.5), otherwise with the round trip longer than the timeout every packet
// would be retransmitted before its acknowledgement and none would give a sample
private const int MaxBackoffDoublings = 3;
private int BackoffDoublings = 0;
private long LastBackoffTimestamp = 0;
private ConcurrentDictionary<long, byte[]> ReorderingBuffer = new ConcurrentDictionary<long, byte[]>();
private ConcurrentDictionary<long, ReliablePacketInformation> InternalState = new ConcurrentDictionary<long, ReliablePacketInformation>();
private readonly Lock ReceiveLock = new();
private readonly Lock AcknowledgementLock = new();
private readonly object WindowLock = new();
private bool PeerUsesBatchedAcks = false;
private int UnacknowledgedPackets = 0; // delivered from a batched-ack peer, but not acknowledged yet
private int OutOfOrderSinceAcknowledgement = 0; // received after a gap since the last acknowledgement
private long FirstUnacknowledgedTimestamp = 0;
private long NextSendTimestamp = 0;
private readonly Lock PacingLock = new();
private readonly SemaphoreSlim ReorderSignal = new(0, 1);
// the next sequential number at the last halving of the window: losses of packets sent before it are the same loss event
private long RecoveryPoint = 0;
private bool FailedDueToTooManyRetxAttepms = false;
private double ThrottlingPower = 0.01;
// the window size is changed by the receiving thread and the retransmission thread
private readonly Lock CongestionLock = new();
// Transmit is called by any number of threads: the sequential number is taken and the packet sent under this lock
private readonly Lock TransmitLock = new();
private Action<SRTPClient, byte[]> MessageReceivedHandler = delegate { };
/// <summary>
/// Gets called for each received message by this client, and data of this message is sent to the event handler.
/// A session created by <see cref="SRTPServer"/> starts delivering messages when this is set. The handler runs on the
/// delivery thread of this client: if it throws, the message still counts as delivered, the exception goes to <see cref="OnError"/>
/// (code -2), and the following messages are delivered as usual.
/// </summary>
public Action<SRTPClient, byte[]> OnMessageReceived
{
get { return MessageReceivedHandler; }
set
{
// null means "nobody listens", not a crash on the next message
MessageReceivedHandler = value ?? delegate { };
// the application subscribed, so the messages held for it can go
if (DeliveryHeld)
{
ReleaseDelivery();
}
}
}
/// <summary>
/// Gets called for each error in this client, where the errcode and text description are sent to the event handler.
/// </summary>
public Action<int, string> OnError = delegate { };
/// <summary>
/// Gets called for each retransmit, and Sequential ID is sent to the event handler.
/// </summary>
public Action<long> OnRetransmit = delegate { };
/// <summary>
/// Gets called for each acknowledgement packet, and Sequential ID is sent to the event handler.
/// </summary>
public Action<long> OnAckReceived = delegate { };
/// <summary>
/// Gets called for each acknowledgement packet sending.
/// </summary>
public Action<long> OnAckTransmitted = delegate { };
/// <summary>
/// Gets called for each packet that is out of order, and Sequential ID is sent to the event handler.
/// </summary>
public Action<long> OnOutOfOrderPacketReceived = delegate { };
/// <summary>
/// The largest window: how far past the first unacknowledged packet the sender may go. The sender keeps only about twice
/// what the path holds in flight (its delivery rate times its round trip): more packets wouldn't arrive faster, they would
/// only wait in queues on the way. With <see cref="PacketLossBasedCongestionControl"/> losses shrink the window too.
/// Keep it not bigger than the remote side's <see cref="MaxPacketNoFromFuture"/>.
/// </summary>
public int MaxUnackedPackets = 1024;
/// <summary>
/// How deep into the future packets will be received.
/// </summary>
public int MaxPacketNoFromFuture = 1024;
/// <summary>
/// When the remote side supports batched acknowledgements, one acknowledgement is sent per this many delivered packets.
/// </summary>
public int AckEveryPackets = 16;
/// <summary>
/// When the remote side supports batched acknowledgements, a received packet is acknowledged not later than this (plus the timer resolution).
/// </summary>
public int AckDelayMilliseconds = 2;
/// <summary>
/// A packet is considered lost and retransmitted right away (without waiting for the timeout), once the remote side
/// reports this many packets after it as received. Smaller values react faster, bigger ones tolerate more reordering.
/// </summary>
public int FastRetransmitAfterPackets = 3;
/// <summary>
/// Delay in Ticks (each tick is 100 ns) between Universal Packet Sends.
/// </summary>
public int TicksPacketDelay = 0;
/// <summary>
/// If set to true, this client controls the load using packet loss: the window shrinks on losses and grows on acknowledgements, so the tetronet doesn't get overloaded
/// </summary>
public bool PacketLossBasedCongestionControl = false;
/// <summary>
/// Gets the remote address, which this SRTP client is currently communicating with.
/// </summary>
public Address RemoteServer { get { return Address.Copy(CommunicatingWith); } }
/// <summary>
/// Gets the Connection ID, which this SRTP client is currently using for tetronet communication.
/// </summary>
public uint EndPointConnectionID { get { return ConnectionID; } }
/// <summary>
/// Time out in Ticks, for how long this instance of SRTPClient will wait for a free slot in InternalState.
/// </summary>
public int TransmitTimeOutInTicks = 600000000;
/// <summary>
/// How many retransmissions will any of the packets need to cause the remote side being considered dead and when Transmit(byte[]) method will throw an exception.
/// The wait before every next retransmission of the same packet doubles, up to 8 retransmission timeouts.
/// </summary>
public int RetransmissionsBeforeConsideringRemoteSideDead = 100;
/// <summary>
/// Milliseconds to pause on packet loss if <see cref="PacketLossBasedCongestionControl"/> is set to <see langword="true"/>
/// </summary>
public int ThrottleTime = 2000;
public event Action<SRTPClient> OnClose = delegate { };
public long MissingPacket
{
get
{
return LastReceived + 1;
}
}
public bool IsMissingPacketAvailable
{
get
{
return ReorderingBuffer.ContainsKey(MissingPacket);
}
}
// follows the path: see AdaptiveWindow; changed under AcknowledgementLock
private readonly AdaptiveWindow DelayWindow = new();
// a v1 peer: it acknowledges every packet, without a cumulative number, so a lost acknowledgement holds the window
// until the timeout, and the rounds of the adaptive window don't measure the path; such a peer gets the whole window
private volatile bool PeerAcknowledgesEveryPacket = false;
/// <summary>
/// How far past the first unacknowledged packet the sender may go: the adaptive window (or the whole one for a v1 peer),
/// with <see cref="PacketLossBasedCongestionControl"/> shrunk by losses too. While a hole waits for its retransmission the
/// packets after it count, so a loss slows the sender down instead of letting it refill the queue, that overflowed.
/// </summary>
private int CurrentWindow
{
get
{
int window = PeerAcknowledgesEveryPacket ? MaxUnackedPackets : DelayWindow.Get(MaxUnackedPackets);
return PacketLossBasedCongestionControl ? Math.Min(window, Math.Max(1, (int)(MaxUnackedPackets * ThrottlingPower))) : window;
}
}
public SRTPClient(IModem modem, Address dst, string qt, uint cid, int tickTimeout, bool autoclear = true)
{
StreamDataTag = StreamDataTagPrefix + StreamId;
ConnectionID = cid;
QueryType = qt;
Modem = modem;
CommunicatingWith = dst;
TicksTimeout = tickTimeout;
RetransmissionTimeoutTicks = tickTimeout;
// receiver task
Modem.AttachReceiveEventNoUnfragment(OnPacketReceived);
// error correction task, also cleans the reordering buffer once a second
_ = Task.Run(async delegate ()
{
int round = 0;
while (!IsClosed)
{
try
{
long timeout = Volatile.Read(ref RetransmissionTimeoutTicks);
int backoff = Volatile.Read(ref BackoffDoublings);
foreach (ReliablePacketInformation info in InternalState.Values)
{
if (info.CheckTimeout(timeout << Math.Min(Math.Max(backoff, info.RetransmissionCounter), MaxBackoffDoublings)))
{
// a packet gets exactly RetransmissionsBeforeConsideringRemoteSideDead retransmissions
if (info.RetransmissionCounter >= RetransmissionsBeforeConsideringRemoteSideDead)
{
FailedDueToTooManyRetxAttepms = true;
Close();
break;
}
info.RetransmissionCounter++;
BackOff(timeout << backoff);
// retransmit packets
UnivSend(info.Data, StreamDataTag);
// update timeout
info.UpdateTimeStamp();
// if enabled, pause the transmission
HalveWindowOnLoss(info.Id);
// call the user event
OnRetransmit(info.Id);
}
}
if (autoclear && ++round % 10 == 0)
{
ClearReorderingBuffer();
}
await Task.Delay(100);
}
catch (Exception ex)
{
OnError(1870, "Retransmit Exception: " + ex);
}
}
});
// reorder task, also sends delayed batched acknowledgements
_ = Task.Run(async delegate ()
{
while (!IsClosed)
{
try
{
ForceReadAllAvailablePackets();
SendDelayedAcknowledgement();
}
catch (Exception e)
{
OnError(-1, "Exception: " + e.ToString());
}
// wake up on a new packet instead of polling, the timeout is just a safety net or the acknowledgement delay
await ReorderSignal.WaitAsync(Volatile.Read(ref UnacknowledgedPackets) > 0 ? AckDelayMilliseconds : 100);
}
});
}
// while set, received messages wait in the reordering buffer instead of going to OnMessageReceived
private volatile bool DeliveryHeld = false;
/// <summary>
/// Keeps received messages from being delivered until <see cref="ReleaseDelivery"/> or until <see cref="OnMessageReceived"/> is set,
/// so none of them goes to nobody before the application subscribed.
/// </summary>
internal void HoldDelivery()
{
DeliveryHeld = true;
}
internal void ReleaseDelivery()
{
DeliveryHeld = false;
WakeUpReorderTask();
}
private volatile bool SkipFinalAcknowledgement = false;
/// <summary>
/// Closes a session, whose remote side already started a new stream with the same ConnectionID: an acknowledgement of the
/// old stream must not reach the new one, where it would acknowledge messages, that weren't received.
/// </summary>
internal void CloseWithoutFinalAcknowledgement()
{
SkipFinalAcknowledgement = true;
Close();
}
private static bool IsBatchedAckData(string? metadata)
{
return metadata == BatchedAckDataTag || (metadata != null && metadata.StartsWith(StreamDataTagPrefix, StringComparison.Ordinal));
}
/// <summary>
/// The stream ID of a message, or null, if the sender didn't put one (older senders, or the metadata got lost on the way).
/// </summary>
internal static string? StreamIdOf(Packet packet)
{
return packet.Metadata != null && packet.Metadata.StartsWith(StreamDataTagPrefix, StringComparison.Ordinal) ? packet.Metadata[StreamDataTagPrefix.Length..] : null;
}
/// <summary>
/// An SRTP acknowledgement of either version.
/// </summary>
internal static bool IsAcknowledgement(Packet packet)
{
return (packet.Metadata != null && packet.Metadata.StartsWith(BatchedAckTag, StringComparison.Ordinal)) ||
(!IsBatchedAckData(packet.Metadata) && packet.DataBytes.Length == 8);
}
/// <summary>
/// How long ago the last packet of this session arrived.
/// </summary>
internal TimeSpan TimeSinceLastPacket
{
get { return Stopwatch.GetElapsedTime(Volatile.Read(ref LastPacketTimestamp)); }
}
/// <summary>
/// Handles a packet, that this client didn't get from the modem itself.
/// </summary>
internal void Receive(Packet packet)
{
OnPacketReceived(packet, delegate { });
}
private void OnPacketReceived(Packet packet, Action k)
{
if (IsClosed)
{
return;
}
if (packet.ConnectionID != ConnectionID || packet.QueryType != QueryType || !packet.Transmitter.Equals(CommunicatingWith))
{
ModemAPIDebugger.OutputDebugMessage("SRTPClient MISMATCH CID OR QT!!!!!!!!!");
return;
}
Volatile.Write(ref LastPacketTimestamp, Stopwatch.GetTimestamp());
try
{
byte[] dataReceived = packet.DataBytes;
if (packet.Metadata == BatchedAckTag)
{
HandleBatchedAcknowledgement(dataReceived);
return;
}
if (packet.Metadata != null && packet.Metadata.StartsWith(StreamAckTagPrefix, StringComparison.Ordinal))
{
// an acknowledgement of another stream (for example of an older client with the same ConnectionID) acknowledges nothing here
if (packet.Metadata.AsSpan(StreamAckTagPrefix.Length).SequenceEqual(StreamId))
{
HandleBatchedAcknowledgement(dataReceived);
}
return;
}
// parse received packet
if (dataReceived.Length < 8)
{
OnError(16, "Packet too short.");
return;
}
long id = BinaryPrimitives.ReadInt64BigEndian(dataReceived);
if (id < 0)
{
OnError(17, $"Packet with a negative sequential number {id}.");
return;
}
if (dataReceived.Length == 8)
{
// == ack receiver ==
PeerAcknowledgesEveryPacket = true;
if (InternalState.TryRemove(id, out ReliablePacketInformation? acknowledgedInfo))
{
OnAckReceived(id);
lock (AcknowledgementLock)
{
long roundTrip = RoundTripOf(acknowledgedInfo);
if (roundTrip >= 0)
{
SampleRoundTrip(roundTrip, id, 1);
}
AdvanceLowestUnacknowledged();
}
AcknowledgementsReceived(1);
}
return;
}
// == enqueue packets ==
bool batched = IsBatchedAckData(packet.Metadata);
string? streamId = StreamIdOf(packet);
if (streamId != null)
{
bool foreign = false;
bool firstOfThisStream = false;
lock (ReceiveLock)
{
if (PeerStreamId == null)
{
PeerStreamId = streamId;
}
else if (streamId != PeerStreamId)
{
foreign = true;
firstOfThisStream = streamId != ReportedForeignStreamId;
ReportedForeignStreamId = streamId;
}
}
if (foreign)
{
// a message of another stream: the sender started over with the same ConnectionID. Acknowledging it here
// as a repeat would lose it, so it is neither acknowledged nor delivered (SRTPServer opens a new session for it;
// anybody else learns about it once per new stream, so it can create a new client)
if (firstOfThisStream && ReportsForeignStreams)
{
OnError(18, $"The remote side started a new stream ({streamId}) with the same ConnectionID, its messages are ignored by this client, which belongs to stream {PeerStreamId}. Create a new SRTPClient to receive it.");
}
return;
}
}
bool tooDeep = false;
bool acknowledgeNow = !batched; // older peers expect an acknowledgement for every packet
lock (ReceiveLock)
{
if (batched)
{
PeerUsesBatchedAcks = true;
}
if (id <= HighestContiguousReceived || ReorderingBuffer.ContainsKey(id))
{
// a retransmission: our acknowledgement got lost or late, so repeat it now
acknowledgeNow = true;
}
else if (LastReceived + MaxPacketNoFromFuture < id)
{
tooDeep = true;
}
else
{
bool inOrder = id == HighestContiguousReceived + 1;
ReorderingBuffer.TryAdd(id, dataReceived);
while (ReorderingBuffer.ContainsKey(HighestContiguousReceived + 1))
{
HighestContiguousReceived++;
}
if (batched && !inOrder)
{
// in-order packets get acknowledged once they are delivered, but a gap means a loss: the sender
// retransmits a hole once FastRetransmitAfterPackets packets after it are reported, so report them
// as soon as there are enough, and then every few packets until the hole is filled
OutOfOrderSinceAcknowledgement++;
acknowledgeNow = OutOfOrderSinceAcknowledgement % (FastRetransmitAfterPackets + 1) == FastRetransmitAfterPackets;
}
}
}
if (tooDeep)
{
OnError(-996, $"Packet {id} is too deep into the future.");
return;
}
WakeUpReorderTask();
if (!acknowledgeNow)
{
return;
}
if (batched)
{
SendBatchedAcknowledgement();
}
else
{
UnivSend(dataReceived.AsSpan(0, 8).ToArray());
ModemAPIDebugger.OutputDebugMessage($"UnivSend acknowledgement for packet {id}");
}
}
catch (Exception e)
{
OnError(-1, "Exception: " + e.ToString());
}
}
private void HandleBatchedAcknowledgement(byte[] acknowledgement)
{
if (acknowledgement.Length < 8)
{
OnError(16, "Packet too short.");
return;
}
long cumulative = BinaryPrimitives.ReadInt64BigEndian(acknowledgement);
int acknowledged = 0;
List<ReliablePacketInformation>? lost = null;
lock (AcknowledgementLock)
{
// one sample per acknowledgement: the packet sent last, it waited the least for the acknowledgement to be sent
long roundTrip = long.MaxValue;
long upTo = Math.Min(cumulative, Interlocked.Read(ref SequentialPacketNumber) - 1);
for (long id = LowestUnacknowledged; id <= upTo; id++)
{
if (InternalState.TryRemove(id, out ReliablePacketInformation? info))
{
acknowledged++;
OnAckReceived(id);
roundTrip = MinRoundTrip(roundTrip, info);
}
}
if (upTo >= LowestUnacknowledged)
{
LowestUnacknowledged = upTo + 1;
}
long highestAcknowledged = upTo;
for (int bit = 0; bit < Math.Min((acknowledgement.Length - 8) * 8, SelectiveAckBits); bit++)
{
if ((acknowledgement[8 + bit / 8] & (1 << (bit % 8))) != 0 && InternalState.TryRemove(cumulative + 1 + bit, out ReliablePacketInformation? info))
{
acknowledged++;
OnAckReceived(cumulative + 1 + bit);
roundTrip = MinRoundTrip(roundTrip, info);
highestAcknowledged = cumulative + 1 + bit;
}
}
if (roundTrip != long.MaxValue)
{
SampleRoundTrip(roundTrip, highestAcknowledged, acknowledged);
}
// the window start doesn't move past selectively acknowledged packets: they are received, but not delivered
// yet, and the receiver only takes packets up to its delivered position + MaxPacketNoFromFuture
lost = FindLostPackets(acknowledgement, cumulative);
}
if (acknowledged > 0)
{
AcknowledgementsReceived(acknowledged);
}
if (lost != null)
{
// fast retransmit: the holes are resent now instead of after TicksTimeout
foreach (ReliablePacketInformation info in lost)
{
UnivSend(info.Data, StreamDataTag);
info.UpdateTimeStamp();
OnRetransmit(info.Id);
}
// the holes are in ascending order: the last one is the newest loss
HalveWindowOnLoss(lost[^1].Id);
}
}
/// <summary>
/// Time from the sending of the packet till its acknowledgement, or -1 if it was retransmitted: then it is unknown,
/// which of the copies got acknowledged (Karn's algorithm).
/// </summary>
private static long RoundTripOf(ReliablePacketInformation info)
{
if (info.RetransmissionCounter > 0 || info.FastRetransmittedBefore >= 0)
{
return -1;
}
return Stopwatch.GetElapsedTime(Volatile.Read(ref info.TimeStamp)).Ticks;
}
private static long MinRoundTrip(long current, ReliablePacketInformation info)
{
long roundTrip = RoundTripOf(info);
return roundTrip >= 0 && roundTrip < current ? roundTrip : current;
}
/// <summary>
/// Updates the retransmission timeout with a measured round trip, as RFC 6298: SRTT + 4·RTTVAR, not shorter than the
/// timeout given to the constructor and not longer than 60 s (unless the given timeout is longer).
/// The adaptive window takes the sample too. Must be called under <see cref="AcknowledgementLock"/>.
/// </summary>
/// <param name="acknowledgedId">The highest sequential number the acknowledgement acknowledged</param>
/// <param name="acknowledgedCount">How many packets the acknowledgement acknowledged</param>
private void SampleRoundTrip(long roundTrip, long acknowledgedId, int acknowledgedCount)
{
DelayWindow.Sample(acknowledgedId, acknowledgedCount, Interlocked.Read(ref SequentialPacketNumber), MaxUnackedPackets, Stopwatch.GetElapsedTime(0).Ticks);
if (SmoothedRttTicks < 0)
{
SmoothedRttTicks = roundTrip;
RttVarianceTicks = roundTrip / 2;
}
else
{
RttVarianceTicks = (3 * RttVarianceTicks + Math.Abs(SmoothedRttTicks - roundTrip)) / 4;
SmoothedRttTicks = (7 * SmoothedRttTicks + roundTrip) / 8;
}
long timeout = Math.Clamp(SmoothedRttTicks + 4 * RttVarianceTicks, TicksTimeout, Math.Max(TicksTimeout, MaxRetransmissionTimeoutTicks));
Volatile.Write(ref RetransmissionTimeoutTicks, timeout);
Volatile.Write(ref BackoffDoublings, 0);
}
/// <summary>
/// Doubles the wait of every packet on a timeout, but not more often than once per the current wait, so packets
/// timing out together double it once. Called by the retransmission task only.
/// </summary>
private void BackOff(long currentTimeout)
{
if (Volatile.Read(ref BackoffDoublings) < MaxBackoffDoublings && Stopwatch.GetElapsedTime(LastBackoffTimestamp).Ticks > currentTimeout)
{
Interlocked.Increment(ref BackoffDoublings);
LastBackoffTimestamp = Stopwatch.GetTimestamp();
}
}
/// <summary>
/// Finds the holes in a selective acknowledgement: packets not reported as received, while at least
/// <see cref="FastRetransmitAfterPackets"/> packets after them are. Must be called under <see cref="AcknowledgementLock"/>.
/// </summary>
/// <returns>Packets to retransmit right away or null</returns>
private List<ReliablePacketInformation>? FindLostPackets(byte[] acknowledgement, long cumulative)
{
int bits = Math.Min((acknowledgement.Length - 8) * 8, SelectiveAckBits);
long highestReported = -1;
for (int bit = bits - 1; bit >= 0; bit--)
{
if ((acknowledgement[8 + bit / 8] & (1 << (bit % 8))) != 0)
{
highestReported = cumulative + 1 + bit;
break;
}
}
if (highestReported < 0)
{
return null;
}
List<ReliablePacketInformation>? lost = null;
long sent = Interlocked.Read(ref SequentialPacketNumber);
for (long id = cumulative + 1; id <= highestReported - FastRetransmitAfterPackets; id++)
{
int bit = (int)(id - cumulative - 1);
if ((acknowledgement[8 + bit / 8] & (1 << (bit % 8))) != 0 || !InternalState.TryGetValue(id, out ReliablePacketInformation? info))
{
continue;
}
// a hole is resent once; it is resent again only when packets sent after that retransmission arrive
// without it, which means the retransmission got lost too
if (info.FastRetransmittedBefore < 0 || highestReported >= info.FastRetransmittedBefore + FastRetransmitAfterPackets)
{
info.FastRetransmittedBefore = sent;
(lost ??= []).Add(info);
}
}
return lost;
}
/// <summary>
/// Moves the window start past every acknowledged packet. Must be called under <see cref="AcknowledgementLock"/>.
/// </summary>
private void AdvanceLowestUnacknowledged()
{
// Transmit adds a packet before counting it, so every number below SequentialPacketNumber is either waiting or acknowledged
while (LowestUnacknowledged < Interlocked.Read(ref SequentialPacketNumber) && !InternalState.ContainsKey(LowestUnacknowledged))
{
LowestUnacknowledged++;
}
}
/// <summary>
/// With <see cref="PacketLossBasedCongestionControl"/>, halves the window on a loss, once per loss event: packets sent
/// before the last halving were sent with the old window, so their losses don't halve it again (as TCP NewReno).
/// Halving once per timeout instead let the window outgrow the link for seconds on fast links, and the mass losses
/// after it stopped the transmission until the retransmission timeout.
/// </summary>
/// <param name="lostId">Sequential number of the lost packet</param>
private void HalveWindowOnLoss(long lostId)
{
if (!PacketLossBasedCongestionControl)
{
return;
}
lock (CongestionLock)
{
if (lostId >= RecoveryPoint)
{
ThrottlingPower = Math.Clamp(ThrottlingPower / 2, 0.0001, 1);
RecoveryPoint = Interlocked.Read(ref SequentialPacketNumber);
}
}
}
private void AcknowledgementsReceived(int count)
{
if (PacketLossBasedCongestionControl)
{
lock (CongestionLock)
{
ThrottlingPower = Math.Clamp(ThrottlingPower + 0.1 * count / MaxUnackedPackets, 0.0001, 1);
}
}
// free slots in the window: wake up Transmit and WaitForAcknowledgements
lock (WindowLock)
{
Monitor.PulseAll(WindowLock);
}
}
private void SendBatchedAcknowledgement()
{
byte[] acknowledgement;
long cumulative;
string tag;
lock (ReceiveLock)
{
if (!PeerUsesBatchedAcks)
{
return;
}
// tells which stream is acknowledged; senders without a stream ID (older ones) get the plain tag they know
tag = PeerStreamId != null ? StreamAckTagPrefix + PeerStreamId : BatchedAckTag;
UnacknowledgedPackets = 0;
OutOfOrderSinceAcknowledgement = 0;
// only delivered packets are acknowledged as a whole, so the sender can't get further ahead of the
// application than the window, and the receiving buffer stays bounded
cumulative = LastReceived;
Span<byte> bitmap = stackalloc byte[SelectiveAckBits / 8];
bitmap.Clear();
int bitmapLength = 0;
// received, but not delivered yet: reported selectively, so they don't get retransmitted
if (!ReorderingBuffer.IsEmpty)
{
for (int bit = 0; bit < SelectiveAckBits; bit++)
{
if (ReorderingBuffer.ContainsKey(cumulative + 1 + bit))
{
bitmap[bit / 8] |= (byte)(1 << (bit % 8));
bitmapLength = bit / 8 + 1;
}
}
}
acknowledgement = new byte[8 + bitmapLength];
BinaryPrimitives.WriteInt64BigEndian(acknowledgement, cumulative);
bitmap[..bitmapLength].CopyTo(acknowledgement.AsSpan(8));
}
UnivSend(acknowledgement, tag);
OnAckTransmitted(cumulative);
}
private void SendDelayedAcknowledgement()
{
bool due;
lock (ReceiveLock)
{
due = UnacknowledgedPackets > 0 &&
Stopwatch.GetElapsedTime(FirstUnacknowledgedTimestamp).TotalMilliseconds >= AckDelayMilliseconds;
}
if (due)
{
SendBatchedAcknowledgement();
}
}
private void WakeUpReorderTask()
{
if (ReorderSignal.CurrentCount != 0)
{
return;
}
try
{
ReorderSignal.Release();
}
catch (SemaphoreFullException)
{
// another thread has already woken it up
}
}
public bool AreAllPacketsFromReorderingBufferIncludedInAlreadyReceived()
{
foreach (long pno in ReorderingBuffer.Keys)
{
if (pno > LastReceived)
{
return false;
}
}
return true;
}
/// <summary>
/// Counts packets for reordering.
/// </summary>
/// <returns>How many packets are in the reordering buffer of this instance of SRTPClient</returns>
public int CountReorderingPackets()
{
return ReorderingBuffer.Count;
}
public void ClearReorderingBuffer()
{
foreach (long pno in ReorderingBuffer.Keys)
{
if (pno <= LastReceived)
{
ReorderingBuffer.TryRemove(pno, out _);
}
}
}
/// <summary>
/// Sends a message. Can be called from several threads at once: every message gets its own sequential number, and the
/// messages are delivered in the order their calls took the numbers.
/// </summary>
/// <exception cref="OperationCanceledException">The remote side is considered dead (too many retransmissions)</exception>
/// <exception cref="InvalidOperationException">The client was closed</exception>
/// <exception cref="TimeoutException">The window stayed full for <see cref="TransmitTimeOutInTicks"/></exception>
/// <exception cref="ArgumentOutOfRangeException">data is empty or longer than <see cref="MaxMessageLength"/></exception>
public void Transmit(byte[] data)
{
// the cause of the failure is reported before the fact that the client got closed because of it
if (FailedDueToTooManyRetxAttepms)
{
Close();
throw new OperationCanceledException("Client was cancelled by the retransmission thread: too many retransmission attempts.");
}
if (IsClosed)
{
throw new InvalidOperationException("This client is in an invalid state \"Closed\". To transmit data, it must be in state \"Opened\"");
}
if (data.Length > MaxMessageLength || data.Length == 0)
{
throw new ArgumentOutOfRangeException(nameof(data), $"data must contain not more than {MaxMessageLength} bytes and not less than 1 byte");
}
byte[] data_ = new byte[data.Length + 8];
data.CopyTo(data_, 8);
lock (TransmitLock)
{
// wait for a free slot in the window, acknowledgements wake this thread up
WaitForWindow(delegate () { return SequentialPacketNumber - Volatile.Read(ref LowestUnacknowledged) < CurrentWindow; });
long id = SequentialPacketNumber;
BinaryPrimitives.WriteInt64BigEndian(data_.AsSpan(), id);
// added before the number is counted: everything below SequentialPacketNumber is waiting or acknowledged
InternalState.TryAdd(id, new(id, Stopwatch.GetTimestamp(), data_));
DelayWindow.PacketSent(data_.Length);
Interlocked.Increment(ref SequentialPacketNumber);
UnivSend(data_, StreamDataTag);
}
}
/// <summary>
/// Blocks until the remote side acknowledges every transmitted packet. Call it before <see cref="Close"/>, otherwise
/// packets lost on the way would never be retransmitted.
/// </summary>
/// <exception cref="TimeoutException">Not everything was acknowledged in <see cref="TransmitTimeOutInTicks"/></exception>
/// <exception cref="InvalidOperationException">The client was closed</exception>
/// <exception cref="OperationCanceledException">The remote side is considered dead</exception>
public void WaitForAcknowledgements()
{
WaitForWindow(delegate () { return InternalState.IsEmpty; });
}
private void WaitForWindow(Func<bool> isReady)
{
long start = Stopwatch.GetTimestamp();
while (true)
{
lock (WindowLock)
{
// checked before isReady: Close() empties the unacknowledged packets, which must not look like "everything acknowledged"
if (!IsClosed && !FailedDueToTooManyRetxAttepms && isReady())
{
return;
}
if (!IsClosed && !FailedDueToTooManyRetxAttepms && Stopwatch.GetElapsedTime(start) <= TimeSpan.FromTicks(TransmitTimeOutInTicks))
{
// the timeout only matters if a wake up got lost or the window size changed
Monitor.Wait(WindowLock, 100);
continue;
}
}
if (FailedDueToTooManyRetxAttepms)
{
Close();
throw new OperationCanceledException("Client was cancelled by the retransmission thread: too many retransmission attempts.");
}
if (IsClosed)
{
throw new InvalidOperationException("This client is in an invalid state \"Closed\". To transmit data, it must be in state \"Opened\"");
}
throw new TimeoutException("Transmit timed out. Normally this will mean that the remote side is dead and you want to Close() this SRTPClient.");
}
}
public void Close()
{
// the retransmission thread, Transmit and the owner can all close the client, but it closes only once
if (Interlocked.Exchange(ref CloseStarted, 1) == 1)
{
return;
}
if (!IsClosed && !SkipFinalAcknowledgement && Volatile.Read(ref UnacknowledgedPackets) > 0)
{
// don't leave the sender waiting for a delayed acknowledgement, that will never come
SendBatchedAcknowledgement();
}
IsClosed = true;
Modem.DetachReceiveEventNoUnfragment(OnPacketReceived);
WakeUpReorderTask();
ReorderingBuffer.Clear();
InternalState.Clear();
lock (WindowLock)
{
Monitor.PulseAll(WindowLock);
}
MessageReceivedHandler = delegate { };
OnClose(this);
}
public bool WasPacketReceived(long packno)
{
return packno <= HighestContiguousReceived || ReorderingBuffer.ContainsKey(packno);
}
private void UnivSend(byte[]? data, string? metadata = null)
{
try
{
WaitForSendSlot();
if (data == null)
{
return;
}
if (CommunicatingWith == null)
{
OnError(1048576, "This client does not communicate with any remote system.");
return;
}
Modem.LowLevelTransmit(data, CommunicatingWith, QueryType, ConnectionID, metadata);
}
catch (Exception ex)
{
OnError(1800, "UNIVSEND failed: " + ex);
}
}
/// <summary>
/// Paces sends to one per <see cref="TicksPacketDelay"/> on average. Instead of spinning between every two packets,
/// the thread sleeps only once it gets ahead of the schedule, and catches up after an oversleep by sending a short burst.
/// </summary>
private void WaitForSendSlot()
{
if (TicksPacketDelay <= 0)
{
return;
}
long delay = TicksPacketDelay * Stopwatch.Frequency / TimeSpan.TicksPerSecond;
long maxLag = Stopwatch.Frequency / 50; // 20 ms, longer than the Windows timer resolution
long minSleep = Stopwatch.Frequency / 500; // 2 ms
long wait;
lock (PacingLock)
{
long now = Stopwatch.GetTimestamp();
if (NextSendTimestamp < now - maxLag)
{
// the client was idle, not oversleeping, so there is nothing to catch up
NextSendTimestamp = now;
}
wait = NextSendTimestamp - now;
NextSendTimestamp += delay;
}
if (wait >= minSleep)
{
Thread.Sleep(TimeSpan.FromTicks(wait * TimeSpan.TicksPerSecond / Stopwatch.Frequency));
}
}
private void ForceReadAllAvailablePackets()
{
while (!DeliveryHeld)
{
byte[]? dataFromBuffer;
bool acknowledge = false;
lock (ReceiveLock)
{
// removing and counting the packet together keeps it "received" for duplicate checks at every moment
if (!ReorderingBuffer.TryRemove(LastReceived + 1, out dataFromBuffer))
{
return;
}
LastReceived++;
if (PeerUsesBatchedAcks)
{
if (UnacknowledgedPackets++ == 0)
{
FirstUnacknowledgedTimestamp = Stopwatch.GetTimestamp();
}
acknowledge = UnacknowledgedPackets >= AckEveryPackets;
}
}
try
{
MessageReceivedHandler(this, dataFromBuffer[8..]); // call user events
}
catch (Exception e)
{
// the message counts as delivered (it was handed over), and the next ones go on being delivered
OnError(-2, "OnMessageReceived threw an exception: " + e);
}
if (acknowledge)
{
SendBatchedAcknowledgement();