-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathTonkineseOutgoing.cpp
More file actions
1730 lines (1376 loc) · 59.4 KB
/
Copy pathTonkineseOutgoing.cpp
File metadata and controls
1730 lines (1376 loc) · 59.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
/** \file
\brief Tonk Implementation: Outgoing Message Queue
\copyright Copyright (c) 2017-2018 Christopher A. Taylor. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Tonkinese nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "TonkineseOutgoing.h"
namespace tonk {
static logger::Channel ModuleLogger("Outgoing", MinimumLogLevel);
#ifdef TONK_ENABLE_VERBOSE_OUTGOING
#define TONK_VERBOSE_OUTGOING_LOG(...) ModuleLogger.Info(__VA_ARGS__);
// Statistics for recovery send rate
static uint64_t m_Recovery = 0;
static uint64_t m_Reliable = 0;
#else
#define TONK_VERBOSE_OUTGOING_LOG(...) ;
#endif
//------------------------------------------------------------------------------
// Constants
/// Padding seed domain for PCGRandom
static const uint64_t kPaddingSeedDomain = 123456;
//------------------------------------------------------------------------------
// Tools
NonceT SessionOutgoing::writeNonce(uint8_t* footer, unsigned& footerBytesOut)
{
// Note nonce can roll over here back to 0, and that is okay because this
// is not intended to provide real data security.
NonceT nonce = NextNonce++;
// Choose the number of bytes to send:
footerBytesOut = 3;
#ifdef TONK_ENABLE_NONCE_COMPRESSION
if (ShouldCompressSequenceNumbers)
{
// Use the magnitude of the difference between this nonce and the peer's
// next expected nonce to decide how many bytes to send for the field.
int32_t mag = (int32_t)nonce - (int32_t)LastAck.PeerNextExpectedNonce.ToUnsigned();
#if 1
if (mag == 1) {
footerBytesOut = 0;
}
else
#endif
{
if (mag < 0) {
TONK_DEBUG_BREAK(); // Should never happen
mag = -mag;
}
++mag;
TONK_DEBUG_ASSERT(mag < 0x800000);
if (mag < 0x80) {
footerBytesOut = 1;
}
else if (mag < 0x8000) {
footerBytesOut = 2;
}
}
}
#endif
protocol::WriteFooterField(footer, (uint32_t)nonce, footerBytesOut);
return nonce;
}
/// Get number of bytes used to represent the given packet number in our protocol
/// taking into account the peer's next expected sequence number
unsigned SessionOutgoing::getPacketNumBytes(int32_t packetNum) const
{
TONK_UNUSED(packetNum);
#ifdef TONK_ENABLE_SEQNO_COMPRESSION
if (ShouldCompressSequenceNumbers)
{
// The peer uses its next expected sequence number to decompress the
// numbers we send. By the time a new datagram arrives, that number
// may have advanced from that last one acknowledged through the last
// one that was sent. When sending a new sequence number, include
// enough bits so that any possible number can decode the new one.
// So, take the larger of the distances from each end.
int32_t mag = (int32_t)packetNum - (int32_t)LastAck.PeerNextExpectedSeqNum;
if (mag < 0) {
mag = -mag;
}
TONK_DEBUG_ASSERT(mag < 0x800000);
int32_t mag2 = (int32_t)packetNum - (int32_t)NextSequenceNumber;
if (mag2 < 0) {
mag2 = -mag2;
}
TONK_DEBUG_ASSERT(mag2 < 0x800000);
if (mag < mag2) {
mag = mag2;
}
// Add one to handle ambiguity due to two's complement negatives
// having one more value of precision than positive numbers
++mag;
// Choose the number of bytes to send:
if (mag < 0x80) {
return 1;
}
else if (mag < 0x8000) {
return 2;
}
}
#endif // TONK_ENABLE_SEQNO_COMPRESSION
return 3;
}
//------------------------------------------------------------------------------
// OutgoingQueuedDatagram
#ifdef TONK_DETAILED_STATS
void OutgoingQueuedDatagram::AddMessageStats(
unsigned messageType,
unsigned messageBytes)
{
Stats[Stats_FramingBytesSent] += protocol::kMessageFrameBytes;
if (messageType == protocol::MessageType_AckAck ||
messageType == protocol::MessageType_Acknowledgements)
{
Stats[Stats_AcksBytesSent] += messageBytes;
}
else if (messageType == protocol::MessageType_Unreliable) {
Stats[Stats_UnreliableBytesSent] += messageBytes;
}
else if (messageType == protocol::MessageType_Unordered) {
Stats[Stats_UnorderedBytesSent] += messageBytes;
}
else if (messageType == protocol::MessageType_TimeSync ||
messageType == protocol::MessageType_Control ||
messageType == protocol::MessageType_Padding)
{
Stats[Stats_ControlBytesSent] += messageBytes;
}
else if (messageType >= protocol::MessageType_LowPri) {
Stats[Stats_LowPriBytesSent] += messageBytes;
}
else if (messageType >= protocol::MessageType_Reliable) {
Stats[Stats_ReliableBytesSent] += messageBytes;
}
TONK_DEBUG_ASSERT(messageType != protocol::MessageType_Compressed);
}
void OutgoingQueuedDatagram::ZeroStats()
{
for (int i = 0; i < Stats_QueueCount; ++i) {
Stats[i] = 0;
}
}
void OutgoingQueuedDatagram::AccumulateStats(OutgoingQueuedDatagram* other)
{
for (int i = 0; i < Stats_QueueCount; ++i) {
Stats[i] += other->Stats[i];
}
}
#endif // TONK_DETAILED_STATS
//------------------------------------------------------------------------------
// OutgoingQueue
bool OutgoingQueue::Append(
unsigned messageType,
const uint8_t* messageData,
unsigned messageBytes)
{
TONK_VERBOSE_OUTGOING_LOG("OutgoingQueue::Append messageType=", messageType,
" messageBytes=", messageBytes, " OutBuffer=", OutBuffer);
OutgoingQueuedDatagram* datagram = OutBuffer;
if (!datagram)
{
TONK_VERBOSE_OUTGOING_LOG("Append: OutBuffer is null - abort");
return false;
}
const unsigned writeBytes = static_cast<unsigned>(
protocol::kMessageFrameBytes + messageBytes);
const unsigned nextWriteOffset = datagram->NextWriteOffset;
if (nextWriteOffset + writeBytes > Common->MaxMessageSectionBytes)
{
TONK_VERBOSE_OUTGOING_LOG("Append: nextWriteOffset=", nextWriteOffset,
" + writeBytes=", writeBytes, " > ", Common->MaxMessageSectionBytes);
return false;
}
uint8_t* messagePtr = datagram->Data + nextWriteOffset;
// Write 2-byte message frame header
protocol::WriteMessageFrameHeader(messagePtr, messageType, messageBytes);
// Copy message into place
memcpy(messagePtr + protocol::kMessageFrameBytes, messageData, messageBytes);
// Record that the data was written
datagram->NextWriteOffset = nextWriteOffset + writeBytes;
// Update queued bytes
QueuedBytes += writeBytes;
TONK_VERBOSE_OUTGOING_LOG("Append: WROTE TO DATAGRAM datagram->NextWriteOffset=",
datagram->NextWriteOffset, " + writeBytes=", writeBytes, " MaxMessageSectionBytes=",
Common->MaxMessageSectionBytes, " QueuedBytes=", QueuedBytes);
#ifdef TONK_DETAILED_STATS
datagram->AddMessageStats(messageType, messageBytes);
#endif // TONK_DETAILED_STATS
return true;
}
size_t OutgoingQueue::AppendSplitReliable(
unsigned messageType,
const uint8_t* messageData,
size_t messageBytes)
{
TONK_VERBOSE_OUTGOING_LOG("OutgoingQueue::AppendSplitReliable messageType=", messageType,
" messageBytes=", messageBytes, " OutBuffer=", OutBuffer);
OutgoingQueuedDatagram* datagram = OutBuffer;
if (!datagram)
{
TONK_VERBOSE_OUTGOING_LOG("AppendSplitReliable: OutBuffer is null - abort");
return 0;
}
const unsigned nextWriteOffset = datagram->NextWriteOffset;
const unsigned bufferBytes = Common->MaxMessageSectionBytes;
// If there is not enough room left in the datagram then return false
if (nextWriteOffset + protocol::kMessageFrameBytes + protocol::kMessageSplitMinimumBytes > bufferBytes)
{
TONK_VERBOSE_OUTGOING_LOG("AppendSplitReliable: nextWriteOffset=", nextWriteOffset,
" + overhead=", (protocol::kMessageFrameBytes + protocol::kMessageSplitMinimumBytes),
" > bufferBytes=", bufferBytes);
return 0;
}
unsigned writeBytes = static_cast<unsigned>(protocol::kMessageFrameBytes + messageBytes);
// If there are more bytes to write than space available:
if (nextWriteOffset + writeBytes > bufferBytes)
{
TONK_VERBOSE_OUTGOING_LOG("AppendSplitReliable: nextWriteOffset=", nextWriteOffset,
" + writeBytes=", writeBytes, " > bufferBytes=", bufferBytes);
TONK_DEBUG_ASSERT(bufferBytes >= nextWriteOffset);
writeBytes = bufferBytes - nextWriteOffset;
TONK_DEBUG_ASSERT(writeBytes >= protocol::kMessageFrameBytes);
messageBytes = static_cast<size_t>(writeBytes - protocol::kMessageFrameBytes);
TONK_VERBOSE_OUTGOING_LOG("AppendSplitReliable: Now writeBytes=", writeBytes,
" messageBytes=", messageBytes);
}
else
{
TONK_VERBOSE_OUTGOING_LOG("AppendSplitReliable: FINAL MESSAGE");
messageType += TonkChannel_Count; // Mark as final message
}
uint8_t* messagePtr = datagram->Data + nextWriteOffset;
// Write 2-byte message frame header
protocol::WriteMessageFrameHeader(
messagePtr,
messageType,
static_cast<unsigned>(messageBytes));
// Copy message into place
memcpy(messagePtr + protocol::kMessageFrameBytes, messageData, messageBytes);
TONK_DEBUG_ASSERT(messageType >= protocol::MessageType_Reliable);
// Record that the data was written
datagram->NextWriteOffset = nextWriteOffset + writeBytes;
// Update queued bytes
QueuedBytes += writeBytes;
TONK_VERBOSE_OUTGOING_LOG("AppendSplitReliable: WROTE TO DATAGRAM datagram->NextWriteOffset=",
datagram->NextWriteOffset, " + writeBytes=", writeBytes, " MaxMessageSectionBytes=",
Common->MaxMessageSectionBytes, " QueuedBytes=", QueuedBytes);
#ifdef TONK_DETAILED_STATS
datagram->AddMessageStats(messageType, static_cast<unsigned>(messageBytes));
#endif // TONK_DETAILED_STATS
return messageBytes;
}
Result OutgoingQueue::PushAndGetFreshBuffer()
{
if (OutBuffer)
{
// If there was no data written yet:
if (OutBuffer->NextWriteOffset <= 0) {
return Result::Success();
}
const unsigned neededBytes = OutBuffer->NextWriteOffset + kAllocatedOverheadBytes;
// Reduce memory usage
Common->WriteAllocator.Shrink(OutBuffer,
neededBytes);
// Link at end of list (After NewestQueued)
if (NewestQueued) {
NewestQueued->Next = OutBuffer;
}
else {
OldestQueued = OutBuffer;
}
NewestQueued = OutBuffer;
TONK_DEBUG_ASSERT(OutBuffer->Next == nullptr);
TONK_VERBOSE_OUTGOING_LOG("PushAndGetFreshBuffer : Flushed OutBuffer = ", OutBuffer);
}
OutBuffer = (OutgoingQueuedDatagram*)Common->WriteAllocator.Allocate(
kQueueHeaderBytes + Common->UDPMaxDatagramBytes);
if (!OutBuffer) {
return Result::OutOfMemory();
}
OutBuffer->Initialize();
TONK_VERBOSE_OUTGOING_LOG("PushAndGetFreshBuffer : Created new OutBuffer = ", OutBuffer);
return Result::Success();
}
OutgoingQueuedDatagram* OutgoingQueue::FlushPeek()
{
// If there is no data in the queue:
if (QueuedBytes <= 0) {
return nullptr;
}
// Get next datagram from the queue
OutgoingQueuedDatagram* datagram = OldestQueued;
if (datagram) {
TONK_VERBOSE_OUTGOING_LOG("FlushPeek -> OldestQueued = ", datagram);
return datagram;
}
// TBD: To simplify this code path, we do not handle OOM properly here.
// This function actually returns a Result object, but it only fails
// if we run out of memory. Since this is a critical code path it seems
// okay to leave it out.
PushAndGetFreshBuffer();
// Return the oldest queued datagram in the list
datagram = OldestQueued;
TONK_DEBUG_ASSERT(datagram != nullptr); // Should never happen
TONK_VERBOSE_OUTGOING_LOG("FlushPeek (Pushed) -> OldestQueued = ", datagram);
return datagram;
}
bool OutgoingQueue::PopIsEmpty()
{
OutgoingQueuedDatagram* datagram = OldestQueued;
TONK_DEBUG_ASSERT(datagram != nullptr);
// Advance the list head
OldestQueued = datagram->Next;
// Update queued bytes
TONK_DEBUG_ASSERT(QueuedBytes >= datagram->NextWriteOffset);
QueuedBytes -= datagram->NextWriteOffset;
// If this was the end of the list:
if (!OldestQueued)
{
NewestQueued = nullptr;
return true;
}
return false;
}
//------------------------------------------------------------------------------
// SessionOutgoing
Result SessionOutgoing::Initialize(
const Dependencies& deps,
uint64_t key)
{
Deps = deps;
for (unsigned i = 0; i < Queue_Count; ++i) {
Queues[i].SetCommon(this);
}
// Initially assume worst-case MTU available
UDPMaxDatagramBytes = protocol::kMinPossibleDatagramByteLimit;
MaxMessageSectionBytes = UDPMaxDatagramBytes - protocol::kMaxOverheadBytes;
Encryptor.Initialize(key);
// Clear remote address
memset(&CachedRemoteAddress, 0, sizeof(CachedRemoteAddress));
// Create the FEC encoder object
FECEncoder = siamese_encoder_create();
if (!FECEncoder) {
return Result("SessionOutgoing::Initialize", "siamese_encoder_create failed", ErrorType::Siamese);
}
#ifdef TONK_ENABLE_RANDOM_PADDING
// Seed the padding PRNG
PaddingPRNG.Seed(key, kPaddingSeedDomain);
#endif // TONK_ENABLE_RANDOM_PADDING
return Compressor.Initialize(protocol::kCompressionAllocateBytes);
}
void SessionOutgoing::ChangeEncryptionKey(uint64_t key)
{
Encryptor.Initialize(key);
}
void SessionOutgoing::Shutdown()
{
uint64_t stats[SiameseEncoderStats_Count];
SiameseResult result = siamese_encoder_stats(FECEncoder, stats, SiameseEncoderStats_Count);
if (result != Siamese_Success) {
Deps.Logger->Error("Unable to retrieve siamese encoder stats");
}
else {
Deps.Logger->Debug("Siamese encoder stats:" \
" Memory used = ", stats[SiameseEncoderStats_MemoryUsed] / 1000, " KB" \
", Originals sent = ", stats[SiameseEncoderStats_OriginalCount],
", Recoveries sent = ", stats[SiameseEncoderStats_RecoveryCount]);
}
Deps.Logger->Debug("Write allocator memory used: ",
WriteAllocator.GetUsedMemory() / 1000, " KB");
siamese_encoder_free(FECEncoder);
// Note: Allocations are freed automatically by FECEncoder object
}
#ifdef TONK_ENABLE_RANDOM_PADDING
// LUT for unif->exp RV with a mean of ~8 bytes
// Hand-adjusted to not spike quite so high...
// Values must not exceed kMaxRandomPaddingBytes
static const uint8_t TONK_RAND_PAD_EXP[256] = {
15, 14, 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12,
15, 14, 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12,
15, 14, 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12,
11, 11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10, 10, 10, 10, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0
};
#endif // TONK_ENABLE_RANDOM_PADDING
Result SessionOutgoing::sendQueuedReliable(
OutgoingQueuedDatagram* datagram,
unsigned reliableOffset)
{
TONK_DEBUG_ASSERT(datagram->NextWriteOffset >= reliableOffset);
if (datagram->NextWriteOffset <= reliableOffset) {
sendQueuedDatagram(datagram, 0, 0);
return Result::Success();
}
SiameseOriginalPacket original;
original.Data = datagram->Data + reliableOffset;
original.DataBytes = datagram->NextWriteOffset - reliableOffset;
original.PacketNum = 0;
// Add reliable data to the Siamese FEC encoder
const int addResult = siamese_encoder_add(FECEncoder, &original);
if (addResult != Siamese_Success) {
TONK_DEBUG_BREAK(); // Should never happen
return Result("SessionOutgoing::Flush", "siamese_encoder_add failed", ErrorType::Siamese, addResult);
}
const unsigned packetNum = original.PacketNum;
const unsigned packetNumBytes = getPacketNumBytes(packetNum);
// Update last sent packet sequence number.
// Used for AckAck generation and sequence number compression
TONK_DEBUG_ASSERT(NextSequenceNumber == packetNum);
NextSequenceNumber = SIAMESE_PACKET_NUM_INC(packetNum);
sendQueuedDatagram(datagram, packetNumBytes, packetNum);
#ifdef TONK_ENABLE_VERBOSE_OUTGOING
m_Reliable++;
#endif // TONK_ENABLE_VERBOSE_OUTGOING
return Result::Success();
}
void SessionOutgoing::sendQueuedDatagram(
OutgoingQueuedDatagram* datagram,
unsigned sequenceNumberBytes,
unsigned sequenceNumber)
{
// If this function changes, also update PostRecovery() and PostDummyDatagram() to keep it in sync.
uint8_t* datagramData = datagram->Data;
unsigned messageBytes = datagram->NextWriteOffset;
TONK_DEBUG_ASSERT(messageBytes > 0);
#ifdef TONK_ENABLE_RANDOM_PADDING
unsigned paddingBytes = 0;
// If there is room for one more message in the datagram:
if (Deps.EnablePadding &&
messageBytes + protocol::kMessageFrameBytes <= MaxMessageSectionBytes)
{
// Select the number of bytes to pad
unsigned targetPadBytes = TONK_RAND_PAD_EXP[PaddingPRNG.Next() % 256];
TONK_DEBUG_ASSERT(targetPadBytes <= protocol::kMaxRandomPaddingBytes);
if (messageBytes + targetPadBytes > MaxMessageSectionBytes) {
targetPadBytes = MaxMessageSectionBytes - messageBytes;
}
// If there is at least a frame worth of padding:
if (targetPadBytes >= protocol::kMessageFrameBytes)
{
// Write frame header
protocol::WriteMessageFrameHeader(
datagramData + messageBytes,
protocol::MessageType_Padding,
targetPadBytes - protocol::kMessageFrameBytes);
// Zero the padding bytes to avoid sending confidential data
memset(
datagramData + messageBytes + protocol::kMessageFrameBytes,
0,
targetPadBytes - protocol::kMessageFrameBytes);
paddingBytes += targetPadBytes;
messageBytes += targetPadBytes;
}
}
#endif // TONK_ENABLE_RANDOM_PADDING
uint8_t* footer = datagramData + messageBytes;
uint8_t flags = protocol::kConnectionMask;
if (ShouldCompressSequenceNumbers) {
flags |= protocol::kSeqCompMask;
}
if (sequenceNumberBytes > 0)
{
flags |= sequenceNumberBytes;
protocol::WriteFooterField(footer, sequenceNumber, sequenceNumberBytes);
footer += sequenceNumberBytes;
}
// Write packet nonce to header
unsigned nonceBytes;
const NonceT nonce = writeNonce(footer, nonceBytes);
flags |= nonceBytes << 2;
footer += nonceBytes;
if (ShouldAttachHandshake)
{
flags |= protocol::kHandshakeMask;
const uint32_t b = siamese::ReadU32_LE(Handshake + 8);
const uint64_t a = siamese::ReadU64_LE(Handshake);
siamese::WriteU64_LE(footer, a);
siamese::WriteU32_LE(footer + 8, b);
footer += protocol::kHandshakeBytes;
}
// Tag checksum includes all the data before the timestamp
const unsigned taggedBytes = (unsigned)(footer - datagramData);
// Skip over the timestamp
uint8_t* timestampData = footer;
footer += protocol::kTimestampBytes;
// Write flags
footer[0] = flags;
++footer;
// Encrypt message data but not the footer
Encryptor.Cipher(datagramData, messageBytes, nonce);
// Generate the main packet data tag
uint16_t tag = Encryptor.Tag(datagramData, taggedBytes, nonce);
static_assert(protocol::kEncryptionTagBytes == 2, "Update this if that changes");
uint8_t* tagData = footer;
const unsigned sendBytes = taggedBytes + protocol::kUntaggedDatagramBytes;
DatagramBuffer datagramBuffer;
datagramBuffer.AllocatorForFree = &WriteAllocator;
datagramBuffer.Data = datagramData;
datagramBuffer.FreePtr = datagram;
datagramBuffer.Bytes = sendBytes;
TONK_DEBUG_ASSERT(Deps.UDPSender != nullptr);
TONK_DEBUG_ASSERT(HasPeerAddress);
TONK_VERBOSE_OUTGOING_LOG("sendQueuedDatagram: datagram = ", datagram, " sequenceNumber=",
sequenceNumber, " sequenceNumberBytes=", sequenceNumberBytes, " bytes=", datagramBuffer.Bytes);
#ifdef TONK_DETAILED_STATS
DetailStats* stats = Deps.Deets->GetWritePtr();
for (int i = 0; i < Stats_QueueCount; ++i) {
stats->Stats[i] += datagram->Stats[i];
}
stats->Stats[Stats_PaddingBytesSent] += paddingBytes;
stats->Stats[Stats_FootersBytesSent] += sendBytes - messageBytes;
#endif // TONK_DETAILED_STATS
// Write timestamp and final tag - Reduce noise in timestamp measurements
const uint64_t nowUsec = siamese::GetTimeUsec();
const uint32_t timestamp24 = (uint32_t)(nowUsec >> kTime23LostBits);
tag ^= Encryptor.TagInt(protocol::TimestampFlagTagInt(timestamp24, flags));
siamese::WriteU24_LE(timestampData, timestamp24);
siamese::WriteU16_LE(tagData, tag);
const unsigned compressionSavings = datagram->CompressionSavings;
// Send the data
Deps.UDPSender->Send(
PeerUDPAddress,
datagramBuffer,
Deps.ConnectionRef);
// Update bandwidth control
Deps.SenderControl->OnSendDatagram(
compressionSavings,
sendBytes,
sequenceNumberBytes > 0);
}
/*
Discussion: Where should we add data to the FEC encoder?
Per message? This would not allow us to combine messages.
This is bad for the FEC encoder because speed is O(N^2) in
the number of packets it is protecting -- fewer is better.
When messages are put in the outgoing queue? This would mean
that FEC encoder output would include data that is not sent yet.
It would cause unnecessary delays and CPU work at the decoder,
and it would slow down the send path.
Right before sending the datagram? It is in a hot path which is
unfortunate but this seems to be the only option without issues.
One advantage of this approach is that the Flush() call, when
invoked from the timer background thread, does not impact the
application main loop.
It also means we can do compression from a background thread.
*/
Result SessionOutgoing::Flush()
{
// Note: There are a number of failure paths that leak objects.
// This seems okay since in response to the error we disconnect,
// and all of these allocations get automatically freed afterwards
// If peer address is not known yet:
if (!HasPeerAddress) {
return Result::Success();
}
// Try to combine the last unreliable frames with the first reliable frames
OutgoingQueuedDatagram* finalUnreliable = nullptr;
// For the unreliable queue:
OutgoingQueue* unreliableQueue = &Queues[Queue_Unreliable];
// Quick skip for common case with no data waiting:
if (unreliableQueue->GetQueuedBytes() > 0)
// For all datagrams for this queue:
for (;;)
{
// Grab next datagram from queue (if any)
OutgoingQueuedDatagram* datagram;
bool isEmpty = true;
{
Locker locker(OutgoingQueueLock);
// Look at the next datagram
datagram = unreliableQueue->FlushPeek();
if (datagram) {
// Pop it off the front
isEmpty = unreliableQueue->PopIsEmpty();
}
}
if (!datagram) {
// Continue on to reliable queued data
break;
}
TONK_DEBUG_ASSERT(datagram->NextWriteOffset > 0);
if (isEmpty) {
finalUnreliable = datagram;
break;
}
// There are more to send- send this one now
sendQueuedUnreliable(datagram);
} // Next datagram in queue
// Combine datagrams together if compression works well enough
OutgoingQueuedDatagram* combined = nullptr;
// Separate failed compression buffers with an empty compression frame
bool prevCompressFailed = false;
// Offset to reliable data
unsigned reliableOffset = 0;
// Send Reliable queue first and then LowPri queue datagrams
for (unsigned queueIndex = Queue_Unmetered; queueIndex < Queue_Count; ++queueIndex)
{
OutgoingQueue* queue = &Queues[queueIndex];
// Quick skip for common case with no data waiting:
if (queue->GetQueuedBytes() <= 0) {
continue;
}
// For all datagrams for this queue:
for (;;)
{
// If this is a Reliable or LowPri message:
if (queueIndex >= Queue_Reliable) {
// If there is no space left:
if (Deps.SenderControl->GetAvailableBytes() <= 0) {
goto DoneSending;
}
}
const SiameseResult isReady = siamese_encoder_is_ready(FECEncoder);
if (isReady != Siamese_Success) {
//Deps.Logger->Warning("SiameseFEC not ready for more data. Delaying sending more until some data is acknowledged");
goto DoneSending;
}
// Grab next datagram from queue (if any)
// TBD: This lock is a little heavy - Sometimes it waits for
// a queue insertion to finish. It would be nicer if we flushed
// just once at the top of the Flush() and then pulled results
// off the protected queue a bit faster.
OutgoingQueuedDatagram* datagram;
{
Locker locker(OutgoingQueueLock);
datagram = queue->FlushPeek();
if (!datagram) {
// Done with this queue
break;
}
queue->PopIsEmpty();
}
const unsigned datagramBytes = datagram->NextWriteOffset;
const uint8_t* datagramData = datagram->Data;
// TBD: Always allocate the combining buffer even if it is just one unordered message
// TBD: We could be compressing directly into this buffer in some cases
if (!combined)
{
combined = (OutgoingQueuedDatagram*)WriteAllocator.Allocate(
protocol::kMaxPossibleDatagramByteLimit * 2);
if (!combined) {
return Result::OutOfMemory();
}
combined->Initialize();
// If there was some unreliable message data to combine:
if (finalUnreliable)
{
// Indicate that the reliable data starts at an offset
const unsigned unreliableBytes = finalUnreliable->NextWriteOffset;
reliableOffset = unreliableBytes;
// Combine final unreliable messages with first reliable messages
memcpy(combined->Data, finalUnreliable->Data, unreliableBytes);
combined->NextWriteOffset = unreliableBytes;
#ifdef TONK_DETAILED_STATS
combined->AccumulateStats(finalUnreliable);
#endif // TONK_DETAILED_STATS
// Prevent this from running again
WriteAllocator.Free(finalUnreliable);
finalUnreliable = nullptr;
} // End if there was a final unreliable message to combine
} // End if no 'combined' buffer allocated yet
unsigned syncOverhead = 0;
// If the data is in a reliable-in-order queue and compression is enabled:
if (queueIndex > Queue_Unmetered && Deps.EnableCompression)
{
unsigned writtenBytes = 0;
// Compress datagram to scratch space
const Result compressResult = Compressor.Compress(
datagramData,
datagramBytes,
combined->Data + combined->NextWriteOffset + protocol::kMessageFrameBytes,
writtenBytes);
if (compressResult.IsFail()) {
return compressResult;
}
// If compression succeeded:
if (writtenBytes > 0)
{
TONK_DEBUG_ASSERT(writtenBytes < datagramBytes);
// Write Compressed frame header
protocol::WriteMessageFrameHeader(
combined->Data + combined->NextWriteOffset,
protocol::MessageType_Compressed,
writtenBytes);
writtenBytes += protocol::kMessageFrameBytes;
// Clear previous compression failure
prevCompressFailed = false;
// If there is enough space to keep it in the combined datagram:
if (combined->NextWriteOffset + writtenBytes <= MaxMessageSectionBytes)
{
// Data is already in-place
combined->NextWriteOffset += writtenBytes;
// Keep track of compression savings
combined->CompressionSavings += datagramBytes + protocol::kMessageFrameBytes - writtenBytes;
#ifdef TONK_DETAILED_STATS
// TBD: Do not keep the original reliable message breakdown.
// Replace those counters with the smaller compressed sent byte count
combined->Stats[Stats_CompressedBytesSent] += writtenBytes - protocol::kMessageFrameBytes;
combined->Stats[Stats_FramingBytesSent] += protocol::kMessageFrameBytes;
combined->Stats[Stats_CompressionSavedBytes] += datagramBytes;
#endif // TONK_DETAILED_STATS
WriteAllocator.Free(datagram);
continue;
}
// Move the compressed data to a new combined datagram:
OutgoingQueuedDatagram* newCombined = (OutgoingQueuedDatagram*)WriteAllocator.Allocate(
protocol::kMaxPossibleDatagramByteLimit * 2);
if (!newCombined) {
return Result::OutOfMemory();
}
newCombined->Initialize();
memcpy(newCombined->Data, combined->Data + combined->NextWriteOffset, writtenBytes);
newCombined->NextWriteOffset = writtenBytes;
// Keep track of compression savings
newCombined->CompressionSavings = datagramBytes + protocol::kMessageFrameBytes - writtenBytes;
const Result result = shrinkWrapAndSendReliable(combined, reliableOffset);
if (result.IsFail()) {
return result;
}
combined = newCombined;
reliableOffset = 0;
#ifdef TONK_DETAILED_STATS
// TBD: Do not keep the original reliable message breakdown.
// Replace those counters with the smaller compressed sent byte count
combined->Stats[Stats_CompressedBytesSent] += writtenBytes - protocol::kMessageFrameBytes;
combined->Stats[Stats_FramingBytesSent] += protocol::kMessageFrameBytes;
#endif // TONK_DETAILED_STATS
WriteAllocator.Free(datagram);
continue;
} // End if compression succeeded
// If previous compression failed too:
if (prevCompressFailed) {
// Receiver will need a frame injected to know where the
// buffer split is at.
syncOverhead = protocol::kMessageFrameBytes;
}
prevCompressFailed = true;
} // End if compression should be attempted
else {
TONK_DEBUG_ASSERT(!prevCompressFailed); // Should not have compressed anything yet
}
// If there is not enough space:
if (combined->NextWriteOffset + datagramBytes + syncOverhead > MaxMessageSectionBytes)
{
const Result result = shrinkWrapAndSendReliable(combined, reliableOffset);
if (result.IsFail()) {
return result;
}
combined = (OutgoingQueuedDatagram*)WriteAllocator.Allocate(
protocol::kMaxPossibleDatagramByteLimit * 2);
if (!combined) {
return Result::OutOfMemory();
}
combined->Initialize();
// All data is reliable after the first reliable datagram
reliableOffset = 0;
// Reset the compression failed flag
prevCompressFailed = false;
syncOverhead = 0;
}
// If we need to write a frame to synchronize compression history:
if (syncOverhead != 0)
{
// See the "Why a Sync Frame is Needed" note in the
// PacketCompression.h header for why this is needed.
protocol::WriteMessageFrameHeader(
combined->Data + combined->NextWriteOffset,
protocol::MessageType_Compressed,
0);
#ifdef TONK_DETAILED_STATS
combined->Stats[Stats_FramingBytesSent] += protocol::kMessageFrameBytes;
#endif // TONK_DETAILED_STATS
combined->NextWriteOffset += protocol::kMessageFrameBytes;
} // End if adding sync frame
// Copy the datagram or compressed data to the end of the combined buffer
memcpy(
combined->Data + combined->NextWriteOffset,
datagramData,