forked from catid/tonk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTonkineseConnection.cpp
More file actions
2396 lines (1967 loc) · 81.2 KB
/
Copy pathTonkineseConnection.cpp
File metadata and controls
2396 lines (1967 loc) · 81.2 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: Connection class
\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 Tonk 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 "TonkineseConnection.h"
namespace tonk {
static logger::Channel ModuleLogger("Connection", MinimumLogLevel);
//------------------------------------------------------------------------------
// Tools
static std::string GetConnectionLogPrefix(const std::string& hostname, uint16_t port)
{
std::ostringstream oss;
oss << "[" << hostname << ":" << port << "] ";
return oss.str();
}
//------------------------------------------------------------------------------
// DNS Hostname Resolution
void HostnameResolverState::InitializeResolvedAddressList(
const asio::ip::tcp::resolver::results_type& results)
{
// Copy the resolved addresses
ResolvedIPAddresses.clear();
ResolvedIPAddresses.reserve(results.size());
for (const auto& result : results) {
ResolvedIPAddresses.emplace_back(result.endpoint().address());
}
ConnectRequestsRemaining = (unsigned)ResolvedIPAddresses.size();
// Select the first address to connect to at random
siamese::PCGRandom prng;
prng.Seed(siamese::GetTimeUsec());
ConnectAddrIndex = static_cast<int>(prng.Next() % ConnectRequestsRemaining);
}
Result HostnameResolverState::GetNextServerAddress(asio::ip::address& addr)
{
// If there are no TCP addresses resolved:
if (ResolvedIPAddresses.empty()) {
return Result("Connection failed", "Hostname did not resolve", ErrorType::Tonk, Tonk_ConnectionTimeout);
}
// Try the next connection address
if (++ConnectAddrIndex >= static_cast<unsigned>(ResolvedIPAddresses.size())) {
ConnectAddrIndex = 0;
}
// Try once per server in the list
if (ConnectRequestsRemaining <= 0) {
return Result("Connection failed", "No servers responded", ErrorType::Tonk, Tonk_ConnectionTimeout);
}
--ConnectRequestsRemaining;
addr = ResolvedIPAddresses[ConnectAddrIndex];
if (addr.is_v4()) {
return Result::Success();
}
try
{
// Workaround fix: IPv6 loopback is not handled properly by asio to_v4()
if (addr.is_loopback())
{
addr = asio::ip::address_v4::loopback();
return Result::Success();
}
addr = addr.to_v4();
}
catch (...)
{
}
// Unable to convert, keep as IPv6
return Result::Success();
}
//------------------------------------------------------------------------------
// Connection
Connection::Connection()
: Logger("Connection", MinimumLogLevel)
{
ActiveConnectionCount++;
}
Connection::~Connection()
{
ActiveConnectionCount--;
}
Result Connection::InitializeIncomingConnection(
const Dependencies& deps,
const TonkSocketConfig* socketConfig,
uint64_t encryptionKey,
const UDPAddress& peerAddress,
uint64_t receiveUsec,
DatagramBuffer datagram)
{
/*
It is one of the goals of this function to stay as simple as possible
because this code runs in the datagram processing thread and blocks
processing the datagrams from other peers.
*/
Result result;
try
{
Deps = deps;
SocketConfig = socketConfig;
EncryptionKey = encryptionKey;
// Add reference to socket
Deps.SocketRefCount->IncrementReferences();
AsioEventStrand = MakeUniqueNoThrow<asio::io_context::strand>(*Deps.Context);
if (!AsioEventStrand)
{
result = Result::OutOfMemory();
goto OnError;
}
SelfRefCount.IncrementReferences();
AsioEventStrand->post([this, receiveUsec, peerAddress, datagram]()
{
Result initResult = completeIncomingConnection(peerAddress);
if (initResult.IsGood())
{
// Process first datagram
TONK_DEBUG_ASSERT(AsioEventStrand->running_in_this_thread());
Result result = Incoming.ProcessDatagram(
receiveUsec,
peerAddress,
datagram.Data,
datagram.Bytes);
if (result.IsFail()) {
onDecodeFailure(result);
}
}
datagram.Free();
if (initResult.IsFail())
{
// Send connection rejection:
DatagramBuffer datagramBuffer;
datagramBuffer.AllocatorForFree = Outgoing.GetWriteAllocator();
datagramBuffer.Bytes = protocol::kDisconnectBytes;
datagramBuffer.Data = datagramBuffer.AllocatorForFree->Allocate(protocol::kDisconnectBytes);
datagramBuffer.FreePtr = datagramBuffer.Data;
if (datagramBuffer.Data)
{
protocol::GenerateDisconnect(EncryptionKey, datagramBuffer.Data);
Deps.UDPSender->Send(
peerAddress,
datagramBuffer,
&SelfRefCount);
// Let Send() decrement SelfRefCount
return;
}
}
SelfRefCount.DecrementReferences();
});
}
catch (...)
{
TONK_DEBUG_BREAK(); // Should never happen except out of memory error
result = Result("Connection::InitializeIncomingConnection", "Exception!", ErrorType::Tonk);
goto OnError;
}
return result;
OnError:
Shutdown();
return result;
}
Result Connection::completeIncomingConnection(const UDPAddress& peerUDPAddress)
{
Result result;
try
{
Logger.SetPrefix(GetConnectionLogPrefix(
peerUDPAddress.address().to_string(),
peerUDPAddress.port()));
result = initSubsystems();
if (result.IsFail()) {
goto OnError;
}
// Update the peer address for outgoing data
Outgoing.SetPeerUDPAddress(peerUDPAddress);
// Initialize timers for incoming connection
resetTimers(SocketConfig->ConnectionTimeoutUsec, true);
/*
This is the right time to assign a Connection Id, before any
messages are queued for delivery to the peer.
The Connection Id is used to reconnect if the source IP address or
port changes during a connection. Both client and server in a
connection are assigned a Connection Id by the other side.
And both peers are able to change their source address by sending
a valid datagram with the ID flag set.
*/
if (!Deps.IdMap->InsertAndAssignId(LocallyAssignedIdForRemoteHost, this))
{
// Id assignment can only fail if too many clients were allowed to
// connect, which should not be possible.
TONK_DEBUG_BREAK();
Logger.Warning("completeConnectionInitialization: Failed to insert new connection into id map");
}
// Write control channel data before the OnConnect() callback so that
// any tonk_flush() will include the control channel data in the first
// UDP response datagram
queueAddressAndIdChangeMessage(peerUDPAddress);
TonkAddress appAddress;
SetTonkAddressStr(appAddress, peerUDPAddress);
// FIXME: If this asserts we currently seem to shut down uncleanly
const uint32_t appDecision = SocketConfig->OnIncomingConnection(
SocketConfig->AppContextPtr,
GetTonkConnection(),
&appAddress,
&ConnectionConfig);
if (TONK_DENY_CONNECTION == appDecision)
{
result = Result("Connection::completeConnectionInitialization", "Application OnIncomingConnection() callback denied connection", ErrorType::Tonk);
goto OnError;
}
MakeCallbacksOptional(ConnectionConfig);
// TBD: We could call OnConnect() here and some apps may have lower
// latency to establish connections. It is already possible to react
// with the same speed to the OnIncomingConnection() callback though.
// Right now OnConnect() is called when the first ID update control
// message is received from the client.
//ConnectionConfig.OnConnect(ConnectionConfig.AppContextPtr, GetTonkConnection());
/*
For the server, we do not want to delay delivery of the client's ID
until the next timed or application flush, so perform a flush here.
This still allows the application to submit data in the first round.
*/
TONK_DEBUG_ASSERT(AsioEventStrand->running_in_this_thread());
// Buffer enough flush space for the first connection request message
Result flushResult = Outgoing.Flush();
if (flushResult.IsFail()) {
SelfRefCount.StartShutdown(Tonk_Error, flushResult);
}
postNextTimer();
}
catch (...)
{
TONK_DEBUG_BREAK(); // Should never happen except out of memory error
result = Result("Connection::completeConnectionInitialization", "Exception!", ErrorType::Tonk);
goto OnError;
}
OnError:
if (result.IsFail())
{
Logger.Warning("Connection::completeIncomingConnection failed: ", result.ToJson());
Shutdown();
}
return result;
}
Result Connection::InitializeOutgoingConnection(
const Dependencies& deps,
const TonkSocketConfig* socketConfig,
const TonkConnectionConfig& connectionConfig,
const char* serverHostname,
uint16_t serverPort)
{
Result result;
try
{
Deps = deps;
SocketConfig = socketConfig;
ConnectionConfig = connectionConfig;
// Add reference to socket
Deps.SocketRefCount->IncrementReferences();
Logger.SetPrefix(GetConnectionLogPrefix(serverHostname, serverPort));
AsioEventStrand = MakeUniqueNoThrow<asio::io_context::strand>(*Deps.Context);
if (!AsioEventStrand)
{
result = Result::OutOfMemory();
goto OnError;
}
ResolverState = MakeUniqueNoThrow<HostnameResolverState>();
ResolverState->ServerUDPPort = serverPort;
ResolverState->Resolver = MakeUniqueNoThrow<asio::ip::tcp::resolver>(*Deps.Context);
#ifdef TONK_DISABLE_OUTGOING_ENCRYPTION
EncryptionKey = 0;
#else // TONK_DISABLE_OUTGOING_ENCRYPTION
uint8_t keyBytes[8];
result = SecureRandom_Next(keyBytes, 8);
if (result.IsFail()) {
goto OnError;
}
EncryptionKey = siamese::ReadU64_LE(keyBytes);
#endif // TONK_DISABLE_OUTGOING_ENCRYPTION
result = initSubsystems();
if (result.IsFail()) {
goto OnError;
}
// Start attaching handshake to each outgoing datagram
Outgoing.StartHandshakeC2SConnect(EncryptionKey);
// Initialize timers for outgoing connection
resetTimers(SocketConfig->ConnectionTimeoutUsec, false);
//----------------------------------------------------------------------
// Connection creation cannot fail past this point
//----------------------------------------------------------------------
// Allow any protocol
static const std::string kAnyProtocolStr = "";
// Kick off async resolve after initialization
SelfRefCount.IncrementReferences();
ResolverState->Resolver->async_resolve(serverHostname, kAnyProtocolStr,
[this](const asio::error_code& error, const asio::ip::tcp::resolver::results_type& results)
{
onResolve(error, results);
SelfRefCount.DecrementReferences();
});
/*
This is the right time to assign a Connection Id, before any
messages are queued for delivery to the peer.
The Connection Id is used to reconnect if the source IP address or
port changes during a connection. Both client and server in a
connection are assigned a Connection Id by the other side.
And both peers are able to change their source address by sending
a valid datagram with the ID flag set.
*/
if (!Deps.IdMap->InsertAndAssignId(LocallyAssignedIdForRemoteHost, this))
{
// Id assignment can only fail if too many clients were allowed to
// connect, which should not be possible.
TONK_DEBUG_BREAK();
Logger.Warning("Failed to insert new connection into map");
}
postNextTimer();
/*
Do not immediately flush queued messages - The application decides
when to flush the initial data so that it can be included in the
first connection request datagram to the server.
*/
}
catch (...)
{
TONK_DEBUG_BREAK(); // Should never happen except out of memory error
result = Result("Connection::InitializeOutgoingConnection", "Exception!", ErrorType::Tonk);
}
OnError:
if (result.IsFail())
{
Logger.Warning("Connection::InitializeOutgoingConnection failed: ", result.ToJson());
Shutdown();
}
return result;
}
Result Connection::InitializeP2PConnection(
const Dependencies& deps,
const TonkSocketConfig* socketConfig,
uint32_t rendezvousServerConnectionId,
const protocol::P2PConnectParams& startParams)
{
/*
It is one of the goals of this function to stay as simple as possible
because this code runs in the datagram processing thread and blocks
processing the datagrams from other peers.
*/
Result result;
try
{
Deps = deps;
SocketConfig = socketConfig;
EncryptionKey = startParams.EncryptionKey;
// Add reference to socket
Deps.SocketRefCount->IncrementReferences();
AsioEventStrand = MakeUniqueNoThrow<asio::io_context::strand>(*Deps.Context);
if (!AsioEventStrand)
{
result = Result::OutOfMemory();
goto OnError;
}
Logger.SetPrefix(GetConnectionLogPrefix(
startParams.PeerExternalAddress.address().to_string(),
startParams.PeerExternalAddress.port()));
result = initSubsystems();
if (result.IsFail())
goto OnError;
// Initialize timers for P2P connection (ignores ConnectionTimeoutUsec setting)
#ifdef TONK_DISABLE_RANDOM_ROUND
resetTimers(SocketConfig->ConnectionTimeoutUsec, false);
#else
resetTimers(protocol::kP2PConnectionTimeout, false);
#endif
HolePuncher = MakeUniqueNoThrow<NATHolePuncher>(startParams);
if (!HolePuncher)
{
result = Result::OutOfMemory();
goto OnError;
}
HolePuncher->RendezvousServerConnectionId = rendezvousServerConnectionId;
// Write 5 byte probe data array
static_assert(protocol::kNATProbeBytes == 5, "Update this");
siamese::WriteU16_LE(HolePuncher->ProbeData, (uint16_t)(startParams.GetOutgoingProbeKey() >> 16));
HolePuncher->ProbeData[2] = static_cast<uint8_t>(protocol::Unconnected_P2PNATProbe);
siamese::WriteU16_LE(HolePuncher->ProbeData + 3, (uint16_t)startParams.GetOutgoingProbeKey());
HolePuncher->RoundTicker = MakeUniqueNoThrow<asio::steady_timer>(*Deps.Context);
if (!HolePuncher->RoundTicker)
{
result = Result::OutOfMemory();
goto OnError;
}
/*
This is the right time to assign a Connection Id, before any
messages are queued for delivery to the peer.
The Connection Id is used to reconnect if the source IP address or
port changes during a connection. Both client and server in a
connection are assigned a Connection Id by the other side.
And both peers are able to change their source address by sending
a valid datagram with the ID flag set.
*/
if (!Deps.IdMap->InsertAndAssignId(LocallyAssignedIdForRemoteHost, this))
{
// Id assignment can only fail if too many clients were allowed to
// connect, which should not be possible.
TONK_DEBUG_BREAK();
Logger.Warning("InitializeP2PConnection: Failed to insert new connection into id map");
}
TonkAddress appAddress;
SetTonkAddressStr(appAddress, startParams.PeerExternalAddress);
// FIXME: If this asserts we currently seem to shut down uncleanly
const uint32_t appDecision = SocketConfig->OnP2PConnectionStart(
SocketConfig->AppContextPtr,
GetTonkConnection(),
&appAddress,
&ConnectionConfig);
if (TONK_DENY_CONNECTION == appDecision)
{
result = Result("Connection::InitializeP2PConnection", "Application OnP2PConnectionStart() callback denied connection", ErrorType::Tonk);
goto OnError;
}
MakeCallbacksOptional(ConnectionConfig);
Logger.Debug("App accepted P2P connection request. Waiting for NAT probe key = ", HexString(startParams.GetExpectedIncomingProbeKey()));
// Start listening to probes with the correct key
const bool insertSuccess = Deps.P2PKeyMap->InsertByKey(
startParams.GetExpectedIncomingProbeKey(),
this);
if (!insertSuccess)
{
TONK_DEBUG_BREAK(); // Should never happen
Logger.Warning("InitializeP2PConnection: Unable to insert into P2P key map");
}
startNextNATProbeRoundTimer();
postNextTimer();
}
catch (...)
{
TONK_DEBUG_BREAK(); // Should never happen except out of memory error
result = Result("Connection::InitializeP2PConnection", "Exception!", ErrorType::Tonk);
goto OnError;
}
OnError:
if (result.IsFail())
{
Logger.Warning("Connection::InitializeP2PConnection failed: ", result.ToJson());
Shutdown();
}
return result;
}
Result Connection::initSubsystems()
{
#ifdef TONK_DETAILED_STATS
// Cycle the detail statistics
Deets.NextWrite();
Deets.GetWritePtr()->TimestampUsec = siamese::GetTimeUsec();
#endif // TONK_DETAILED_STATS
memset(&CachedLocalAddress, 0, sizeof(CachedLocalAddress));
memset(&LastIdAndAddressSent, 0, sizeof(LastIdAndAddressSent));
const bool enableCompression = \
(SocketConfig->Flags & TONK_FLAGS_DISABLE_COMPRESSION) == 0;
const bool enablePadding = \
(SocketConfig->Flags & TONK_FLAGS_ENABLE_PADDING) != 0;
Result result = Outgoing.Initialize({
enableCompression,
enablePadding,
&Logger,
Deps.UDPSender,
&SelfRefCount,
#ifdef TONK_DETAILED_STATS
&Deets,
#endif // TONK_DETAILED_STATS
&SenderControl
},
EncryptionKey);
if (result.IsFail()) {
return result;
}
// Initialize Incoming object given the app context
result = Incoming.Initialize({
&SelfRefCount,
this,
&TimeSync,
&Outgoing,
&ReceiverControl,
#ifdef TONK_DETAILED_STATS
&Deets,
#endif // TONK_DETAILED_STATS
&Logger
},
EncryptionKey,
&ConnectionConfig,
GetTonkConnection());
if (result.IsFail()) {
return result;
}
// Configure the bandwidth limit
SenderBandwidthControl::Parameters sparams;
sparams.MaximumBPS = (unsigned)SocketConfig->BandwidthLimitBPS;
if (sparams.MaximumBPS > TONK_MAX_BPS) {
sparams.MaximumBPS = TONK_MAX_BPS;
}
// Initialize bandwidth control
SenderControl.Initialize({
&TimeSync,
&Logger
},
sparams);
ReceiverControl.Initialize({
&TimeSync,
&Logger
});
// Create the timer
Ticker = MakeUniqueNoThrow<asio::steady_timer>(*Deps.Context);
if (!Ticker) {
return Result::OutOfMemory();
}
return Result::Success();
}
void Connection::resetTimers(uint32_t noDataTimeoutUsec, bool connectionEstablished)
{
const uint64_t nowUsec = GetTicksUsec();
// Tick the no-data timeout once
NoDataTimer.SetTimeoutUsec(noDataTimeoutUsec, Timer::Behavior::Stop);
NoDataTimer.Start(nowUsec);
// Tick the flow control timer repeatedly
TimeSyncTimer.SetTimeoutUsec(
connectionEstablished ? protocol::kTimeSyncIntervalUsec : protocol::kConnectionIntervalUsec,
Timer::Behavior::Restart);
TimeSyncTimer.Start(nowUsec);
// Tick the acknowledgement timer repeatedly
AcknowledgementTimer.SetTimeoutUsec(protocol::kMinAckIntervalUsec, Timer::Behavior::Restart);
AcknowledgementTimer.Start(nowUsec);
// Tick the app's OnTick() timer repeatedly
AppTimer.SetTimeoutUsec(SocketConfig->TimerIntervalUsec, Timer::Behavior::Restart);
AppTimer.Start(nowUsec);
Logger.Debug("Reset no data timeout to ", noDataTimeoutUsec, " usec");
}
void Connection::onResolve(const asio::error_code& error, const asio::ip::tcp::resolver::results_type& results)
{
if (SelfRefCount.IsShutdown()) {
Logger.Warning("Ignoring onResolve() result during disco");
return;
}
Result lookupResult;
if (error) {
lookupResult = Result("Connection::onResolve", error.message(), ErrorType::Asio, error.value());
}
else if (results.empty()) {
lookupResult = Result("Connection::onResolve", "No results", ErrorType::Tonk, Tonk_HostnameLookup);
}
if (lookupResult.IsFail()) {
SelfRefCount.StartShutdown(Tonk_HostnameLookup, lookupResult);
return;
}
Logger.Debug("Resolve success: ", results.size(), " results");
ResolverState->InitializeResolvedAddressList(results);
// Post a connect to this address
startConnectingToNextAddress();
}
void Connection::startConnectingToNextAddress()
{
if (SelfRefCount.IsShutdown()) {
return;
}
Result result;
try
{
asio::ip::address ip_addr;
result = ResolverState->GetNextServerAddress(ip_addr);
if (result.IsFail()) {
goto OnError;
}
Logger.Info("Attempting UDP-based connection with ", ip_addr.to_string(), " : ", ResolverState->ServerUDPPort);
// Update peer address
setPeerAddress(UDPAddress(ip_addr, ResolverState->ServerUDPPort));
}
catch (...)
{
result = Result("Connection::startConnectingToNextAddress", "Exception!");
goto OnError;
}
return;
OnError:
SelfRefCount.StartShutdown(Tonk_Error, result);
}
void Connection::OnICMPError(const asio::error_code& error)
{
AsioEventStrand->post([this, error]()
{
const bool isOutgoingConnection = (ResolverState != nullptr);
/*
IF Connection Was Established
OR This Was NOT The Connection Initiator
THEN
Disconnect asychronously with network failure error
ELSE
This is a client trying to connect given hostname,
so try the next hostname.
END IF
*/
if (ConnectionEstablished || !isOutgoingConnection)
{
SelfRefCount.StartShutdown(Tonk_NetworkFailed,
Result("Connection::OnICMPError",
error.message(),
ErrorType::Asio,
error.value()));
}
else
{
Logger.Debug("Selecting next server to connect to");
// This is a client trying to connect given hostname,
// so try the next hostname.
startConnectingToNextAddress();
}
SelfRefCount.DecrementReferences();
});
}
void Connection::OnUDPDatagram(
uint64_t receiveUsec,
const UDPAddress& addr,
DatagramBuffer datagram)
{
/*
TBD: This might be more efficient if we add incoming datagrams to a
linked list and only post() a task if the list is empty. This needs
benchmarking with a real application in order to evaluate the value
of the extra complexity. The intent would be to reduce the average
latency of processing the second (and later) datagrams.
*/
AsioEventStrand->post([this, receiveUsec, addr, datagram]()
{
TONK_DEBUG_ASSERT(AsioEventStrand->running_in_this_thread());
Result result = this->Incoming.ProcessDatagram(receiveUsec, addr, datagram.Data, datagram.Bytes);
if (result.IsFail()) {
onDecodeFailure(result);
}
datagram.Free();
SelfRefCount.DecrementReferences();
});
}
void Connection::onDecodeFailure(const Result& error)
{
TONK_DEBUG_ASSERT(error.IsFail());
const bool isUnauthenticatedData = \
error.Error->Type == ErrorType::Tonk &&
error.Error->Code == Tonk_BogonData;
if (isUnauthenticatedData)
{
// Disabled this log
//Logger.Debug("Bogon data ignored: ", error.ToJson());
return;
}
Logger.Error("Authenticated datagram decode failure: ", error.ToJson());
SelfRefCount.StartShutdown(Tonk_InvalidData, error);
}
void Connection::OnNATProbe(
const UDPAddress& addr,
uint32_t key,
ConnectionAddrMap* addrMap,
IUDPSender* sender)
{
AsioEventStrand->post([this, addr, key, addrMap, sender]()
{
TONK_DEBUG_ASSERT(AsioEventStrand->running_in_this_thread());
if (!HolePuncher) {
Logger.Warning("Ignoring NAT probe from unrelated port");
}
else if (!HolePuncher->SeenProbe)
{
HolePuncher->SeenProbe = true;
Logger.Warning("NAT probe from ", addr.address().to_string(), " : ", addr.port(), " - key = ", HexString(key));
// Start attaching handshake to each outgoing datagram
Outgoing.StartHandshakePeer2PeerConnect(HolePuncher->StartParams.GetOutgoingHandshakeKey());
// Update source and destination addresses
setPeerAddressAndSource(addrMap, sender, addr);
}
else {
Logger.Warning("Ignoring extra probe from ", addr.address().to_string(), " : ", addr.port(), " - key = ", HexString(key));
}
SelfRefCount.DecrementReferences();
});
}
void Connection::OnP2PConnection(
uint64_t receiveUsec,
const UDPAddress& addr,
DatagramBuffer datagram,
uint64_t handshakeKey,
ConnectionAddrMap* addrMap,
IUDPSender* sender)
{
AsioEventStrand->post([this, receiveUsec, addr, datagram, handshakeKey, addrMap, sender]()
{
TONK_DEBUG_ASSERT(AsioEventStrand->running_in_this_thread());
if (!HolePuncher)
{
TONK_DEBUG_BREAK(); // Should never happen
Logger.Warning("Ignoring P2P connect: P2P connection is not in progress");
}
else if (handshakeKey != HolePuncher->StartParams.GetExpectedIncomingHandshakeKey())
{
Logger.Warning("Ignoring P2P connect: HandshakeKey=", HexString(handshakeKey),
" IncomingKey=", HexString(HolePuncher->StartParams.GetExpectedIncomingHandshakeKey()),
" does not match from ", addr.address().to_string(), " : ", addr.port());
}
else
{
// If we have seen a probe already, and this peer is the tie-breaker:
if (HolePuncher->SeenProbe && HolePuncher->StartParams.WinTies)
{
// Ignore connection requests as tie-breaker if we have already seen a probe.
// It is the job of the tie-breaker to make the connection request.
ModuleLogger.Warning("Ignoring connection request - We are tie breaker and received a probe already");
}
else
{
/*
(1) Have seen probe (2) I am not tie-breaker
Switch to the new sender/source pair.
(1) Have *not* seen probe yet (2) I am/not tie-breaker
No connection requests have been sent yet.
Peer got a probe and we got a connection request, so go with it.
*/
// In any case this counts as a probe received
HolePuncher->SeenProbe = true;
// If the peer address or source is changing:
if (Outgoing.GetPeerUDPAddress() != addr ||
addrMap != Deps.AddressMap)
{
ModuleLogger.Warning("Switching NAT port pairs for tie-breaker. New dest: ",
addr.address().to_string(), ":", addr.port());
// It is safe to update these from this thread because
// datagrams are only sent from this strand.
setPeerAddressAndSource(addrMap, sender, addr);
}
else
{
ModuleLogger.Debug("Repeated connection request from the same source address - No change needed");
}
}
// Process data attached to the handshake regardless of outcome above
Result result = Incoming.ProcessDatagram(receiveUsec, addr, datagram.Data, datagram.Bytes);
if (result.IsFail()) {
onDecodeFailure(result);
}
datagram.Free();
}
SelfRefCount.DecrementReferences();
});
}
void Connection::postNextTimer()
{
Ticker->expires_after(std::chrono::microseconds(protocol::kSendTimerTickIntervalUsec));
Ticker->async_wait(([this](const asio::error_code& error)
{
// Note: Dispatch invokes on the same thread if possible.
// It often executes immediately.
AsioEventStrand->dispatch([this, error]() {
if (error) {
onTimerError(error);
}
else if (TimerTickResult::TickAgain == onTimerTick()) {
postNextTimer();
}
});
}));
}
void Connection::onTimerError(const asio::error_code& error)
{
/*
Our Timer failed for some reason unexpectedly. Maybe this happens during shutdown.
This error is not recoverable so we should begin the disconnect process.
*/
SelfRefCount.StartShutdown(Tonk_NetworkFailed,
Result("Connection::onTimerError",
error.message(),
ErrorType::Asio,
error.value()));
// Report close to application since timer will no longer fire
reportClose();
removeFromMaps();
}
Connection::TimerTickResult Connection::onTimerTick()
{
const uint64_t nowUsec = GetTicksUsec();
#ifdef TONK_DETAILED_STATS
// Cycle the detail statistics
Deets.NextWrite();
Deets.GetWritePtr()->TimestampUsec = nowUsec;
#endif // TONK_DETAILED_STATS
// If the TonkConnection's parent TonkSocket is shut down:
if (Deps.SocketRefCount->IsShutdown())
{
SelfRefCount.StartShutdown(
Tonk_AppRequest,
Result("Connection::onTimerTick", "App shutdown in progress", ErrorType::Tonk, Tonk_AppRequest));
}
// If this TonkConnection is disconnected:
if (SelfRefCount.IsShutdown()) {
return onDiscoTimerTick();
}
// If no data has been received for too long:
if (NoDataTimer.IsExpired(nowUsec))
{
SelfRefCount.StartShutdown(
Tonk_RemoteTimeout,
Result("Connection::onTimerTick", "No data from peer (Connection timeout)"));
return TimerTickResult::TickAgain;
}
// If peer should be sending acks but none are received:
if (!Outgoing.PeerCaughtUp() &&
Outgoing.GetLastAckReceiveUsec() != 0 &&
(int64_t)(nowUsec - Outgoing.GetLastAckReceiveUsec() - protocol::kNoAckSquelchTimeoutUsec) > 0)
{
// Squelch sender
SenderControl.Squelch();
if (RemoteAssignedIdForLocalHost != TONK_INVALID_ID)
{