-
Notifications
You must be signed in to change notification settings - Fork 596
/
steamnetworkingsockets_connections.cpp
4368 lines (3691 loc) · 155 KB
/
steamnetworkingsockets_connections.cpp
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
//====== Copyright Valve Corporation, All rights reserved. ====================
#include <time.h>
#include <steam/isteamnetworkingsockets.h>
#include "steamnetworkingsockets_connections.h"
#include "steamnetworkingsockets_lowlevel.h"
#include "../steamnetworkingsockets_certstore.h"
#include "csteamnetworkingsockets.h"
#include "crypto.h"
#include "tier0/memdbgoff.h"
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_STEAMNETWORKINGMESSAGES
#include "csteamnetworkingmessages.h"
#endif
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_DIAGNOSTICSUI
#include "../../common/steammessages_gamenetworkingui.pb.h"
#endif
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_FAKEIP
#include <steam/steamnetworkingfakeip.h>
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#ifdef __GNUC__
// error: assuming signed overflow does not occur when assuming that (X + c) < X is always false [-Werror=strict-overflow]
// current steamrt:scout gcc "g++ (SteamRT 4.8.4-1ubuntu15~12.04+steamrt1.2+srt1) 4.8.4" requires this at the top due to optimizations
#pragma GCC diagnostic ignored "-Wstrict-overflow"
#endif
// Put everything in a namespace, so we don't violate the one definition rule
namespace SteamNetworkingSocketsLib {
const int k_nMaxRecentLocalConnectionIDs = 256;
static CUtlVectorFixed<uint16,k_nMaxRecentLocalConnectionIDs> s_vecRecentLocalConnectionIDs;
/// Check if we've sent a "spam reply", meaning a reply to an incoming
/// message that could be random spoofed garbage. Returns false if we've
/// recently sent one and cannot send any more right now without risking
/// being taken advantage of. Returns true if we haven't sent too many
/// such packets recently, and it's OK to send one now. (If true is returned,
/// it's assumed that you will send one.)
bool BCheckGlobalSpamReplyRateLimit( SteamNetworkingMicroseconds usecNow )
{
static SteamNetworkingMicroseconds s_usecLastSpamReplySent;
if ( s_usecLastSpamReplySent + k_nMillion/4 > usecNow )
return false;
s_usecLastSpamReplySent = usecNow;
return true;
}
// Hack code used to generate C++ code to add a new CA key to the table above
//void KludgePrintPublicKey()
//{
// CECSigningPublicKey key;
// char *x = strdup( "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJrsoE4XUc5iaNVpACyh4fobLbwm02tOo6AIOtNygpuE" );
// DbgVerify( key.LoadFromAndWipeBuffer( x, strlen(x) ) );
// CUtlStringBuilder bufText;
// for ( uint32 i = 0 ; i < key.GetLength() ; ++i )
// {
// bufText.AppendFormat("\\x%02x", key.GetData()[i] );
// }
// SHA256Digest_t digest;
// CCrypto::GenerateSHA256Digest( key.GetData(), key.GetLength(), &digest );
// SpewWarning( "TrustedKey( %llullu, \"%s\" )\n", LittleQWord( *(uint64*)&digest ), bufText.String() );
//}
/////////////////////////////////////////////////////////////////////////////
//
// Message storage
//
/////////////////////////////////////////////////////////////////////////////
void CSteamNetworkingMessage::DefaultFreeData( SteamNetworkingMessage_t *pMsg )
{
free( pMsg->m_pData );
}
void CSteamNetworkingMessage::ReleaseFunc( SteamNetworkingMessage_t *pIMsg )
{
CSteamNetworkingMessage *pMsg = static_cast<CSteamNetworkingMessage *>( pIMsg );
// Free up the buffer, if we have one
if ( pMsg->m_pData && pMsg->m_pfnFreeData )
(*pMsg->m_pfnFreeData)( pMsg );
pMsg->m_pData = nullptr; // Just for grins
// We must not currently be in any queue. In fact, our parent
// might have been destroyed.
Assert( !pMsg->m_links.m_pQueue );
Assert( !pMsg->m_links.m_pPrev );
Assert( !pMsg->m_links.m_pNext );
Assert( !pMsg->m_linksSecondaryQueue.m_pQueue );
Assert( !pMsg->m_linksSecondaryQueue.m_pPrev );
Assert( !pMsg->m_linksSecondaryQueue.m_pNext );
// Self destruct
// FIXME Should avoid this dynamic memory call with some sort of pooling
delete pMsg;
}
CSteamNetworkingMessage *CSteamNetworkingMessage::New( uint32 cbSize )
{
// FIXME Should avoid this dynamic memory call with some sort of pooling
CSteamNetworkingMessage *pMsg = new CSteamNetworkingMessage;
// NOTE: Intentionally not memsetting the whole thing;
// this struct is pretty big.
// Allocate buffer if requested
if ( cbSize )
{
pMsg->m_pData = malloc( cbSize );
if ( pMsg->m_pData == nullptr )
{
delete pMsg;
SpewError( "Failed to allocate %d-byte message buffer", cbSize );
return nullptr;
}
pMsg->m_cbSize = cbSize;
pMsg->m_pfnFreeData = CSteamNetworkingMessage::DefaultFreeData;
}
else
{
pMsg->m_cbSize = 0;
pMsg->m_pData = nullptr;
pMsg->m_pfnFreeData = nullptr;
}
// Clear identity
pMsg->m_conn = k_HSteamNetConnection_Invalid;
pMsg->m_identityPeer.m_eType = k_ESteamNetworkingIdentityType_Invalid;
pMsg->m_identityPeer.m_cbSize = 0;
// Set the release function
pMsg->m_pfnRelease = ReleaseFunc;
// Clear these fields
pMsg->m_nConnUserData = 0;
pMsg->m_usecTimeReceived = 0;
pMsg->m_nMessageNumber = 0;
pMsg->m_nChannel = -1;
pMsg->m_nFlags = 0;
pMsg->m_idxLane = 0;
pMsg->m_links.Clear();
pMsg->m_linksSecondaryQueue.Clear();
return pMsg;
}
void CSteamNetworkingMessage::Unlink()
{
// Unlink from any queues we are in
UnlinkFromQueue( &CSteamNetworkingMessage::m_links );
UnlinkFromQueue( &CSteamNetworkingMessage::m_linksSecondaryQueue );
}
ShortDurationLock g_lockAllRecvMessageQueues( "all_recv_msg_queue" );
void SteamNetworkingMessageQueue::AssertLockHeld() const
{
if ( m_pRequiredLock )
m_pRequiredLock->AssertHeldByCurrentThread();
}
void SteamNetworkingMessageQueue::PurgeMessages()
{
AssertLockHeld();
while ( !empty() )
{
CSteamNetworkingMessage *pMsg = m_pFirst;
pMsg->Unlink();
Assert( m_pFirst != pMsg );
pMsg->Release();
}
Assert( m_nMessageCount == 0 );
}
int SteamNetworkingMessageQueue::RemoveMessages( SteamNetworkingMessage_t **ppOutMessages, int nMaxMessages )
{
int nMessagesReturned = 0;
AssertLockHeld();
while ( !empty() && nMessagesReturned < nMaxMessages )
{
// Locate message, put into caller's list
CSteamNetworkingMessage *pMsg = m_pFirst;
ppOutMessages[nMessagesReturned++] = pMsg;
// Unlink from all queues
pMsg->Unlink();
// That should have unlinked from *us*, so it shouldn't be in our queue anymore
Assert( m_pFirst != pMsg );
}
return nMessagesReturned;
}
/////////////////////////////////////////////////////////////////////////////
//
// CSteamNetworkPollGroup
//
/////////////////////////////////////////////////////////////////////////////
CSteamNetworkPollGroup::CSteamNetworkPollGroup( CSteamNetworkingSockets *pInterface )
: m_pSteamNetworkingSocketsInterface( pInterface )
, m_hPollGroupSelf( k_HSteamListenSocket_Invalid )
{
// Object creation is rare; to keep things simple we require the global lock
SteamNetworkingGlobalLock::AssertHeldByCurrentThread();
m_queueRecvMessages.m_pRequiredLock = &g_lockAllRecvMessageQueues;
}
CSteamNetworkPollGroup::~CSteamNetworkPollGroup()
{
// Object deletion is rare; to keep things simple we require the global lock
SteamNetworkingGlobalLock::AssertHeldByCurrentThread();
m_lock.AssertHeldByCurrentThread();
FOR_EACH_VEC_BACK( m_vecConnections, i )
{
CSteamNetworkConnectionBase *pConn = m_vecConnections[i];
ConnectionScopeLock connectionLock( *pConn ); // NOTE: It's OK to take more than one lock here, because we hold the global lock
Assert( pConn->m_pPollGroup == this );
pConn->RemoveFromPollGroup();
Assert( m_vecConnections.Count() == i );
}
// We should not have any messages now! but if we do, unlink them
{
ShortDurationScopeLock lockMessageQueues( g_lockAllRecvMessageQueues );
Assert( m_queueRecvMessages.empty() );
// But if we do, unlink them but leave them in the main queue.
while ( !m_queueRecvMessages.empty() )
{
CSteamNetworkingMessage *pMsg = m_queueRecvMessages.m_pFirst;
// The poll group queue is the "secondary queue"
Assert( pMsg->m_linksSecondaryQueue.m_pQueue == &m_queueRecvMessages );
// They should be in some other queue (for the connection) as the main queue.
// That owns them and make sure they get deleted!
Assert( pMsg->m_links.m_pQueue != nullptr );
// OK, do the work
pMsg->UnlinkFromQueue( &CSteamNetworkingMessage::m_linksSecondaryQueue );
// Make sure it worked.
Assert( pMsg != m_queueRecvMessages.m_pFirst );
}
}
// Remove us from global table, if we're in it
if ( m_hPollGroupSelf != k_HSteamNetPollGroup_Invalid )
{
g_tables_lock.AssertHeldByCurrentThread();
int idx = m_hPollGroupSelf & 0xffff;
if ( g_mapPollGroups.IsValidIndex( idx ) && g_mapPollGroups[ idx ] == this )
{
g_mapPollGroups[ idx ] = nullptr; // Just for grins
g_mapPollGroups.RemoveAt( idx );
}
else
{
AssertMsg( false, "Poll group handle bookkeeping bug!" );
}
m_hPollGroupSelf = k_HSteamNetPollGroup_Invalid;
}
// Unlock, so our lock debugging doesn't complain.
// Here we assume that we're only locked once
m_lock.unlock();
}
void CSteamNetworkPollGroup::AssignHandleAndAddToGlobalTable()
{
// Object creation is rare; to keep things simple we require the global lock
SteamNetworkingGlobalLock::AssertHeldByCurrentThread();
g_tables_lock.AssertHeldByCurrentThread();
Assert( m_hPollGroupSelf == k_HSteamNetPollGroup_Invalid );
// We actually don't do map "lookups". We assume the number of listen sockets
// is going to be reasonably small.
static int s_nDummy;
++s_nDummy;
int idx = g_mapPollGroups.Insert( s_nDummy, this );
Assert( idx < 0x1000 );
// Use upper 15 bits as a connection sequence number, so that listen socket handles
// are not reused within a short time period.
// (The top bit is reserved, so that listen socket handles and poll group handles
// come from a different namespace, so that we can immediately detect using the wrong
// and make that bug more obvious.)
static uint32 s_nUpperBits = 0;
s_nUpperBits += 0x10000;
if ( s_nUpperBits & 0x10000000 )
s_nUpperBits = 0x10000;
// Set the handle
m_hPollGroupSelf = HSteamNetPollGroup( idx | s_nUpperBits | 0x80000000 );
}
/////////////////////////////////////////////////////////////////////////////
//
// CSteamNetworkListenSocketBase
//
/////////////////////////////////////////////////////////////////////////////
CSteamNetworkListenSocketBase::CSteamNetworkListenSocketBase( CSteamNetworkingSockets *pSteamNetworkingSocketsInterface )
: m_hListenSocketSelf( k_HSteamListenSocket_Invalid )
, m_pSteamNetworkingSocketsInterface( pSteamNetworkingSocketsInterface )
{
m_connectionConfig.Init( &pSteamNetworkingSocketsInterface->m_connectionConfig );
}
CSteamNetworkListenSocketBase::~CSteamNetworkListenSocketBase()
{
SteamNetworkingGlobalLock::AssertHeldByCurrentThread();
AssertMsg( m_mapChildConnections.Count() == 0, "Destroy() not used properly" );
// Remove us from global table, if we're in it
if ( m_hListenSocketSelf != k_HSteamListenSocket_Invalid )
{
TableScopeLock tableScopeLock( g_tables_lock ); // NOTE: We can do this since listen sockets are protected by the global lock, not an object lock
int idx = m_hListenSocketSelf & 0xffff;
if ( g_mapListenSockets.IsValidIndex( idx ) && g_mapListenSockets[ idx ] == this )
{
g_mapListenSockets[ idx ] = nullptr; // Just for grins
g_mapListenSockets.RemoveAt( idx );
}
else
{
AssertMsg( false, "Listen socket handle bookkeeping bug!" );
}
m_hListenSocketSelf = k_HSteamListenSocket_Invalid;
}
#ifdef STEAMNETWORKINGSOCKETS_STEAMCLIENT
Assert( !m_pLegacyPollGroup ); // Should have been cleaned up by Destroy()
#endif
}
bool CSteamNetworkListenSocketBase::BInitListenSocketCommon( int nOptions, const SteamNetworkingConfigValue_t *pOptions, SteamDatagramErrMsg &errMsg )
{
SteamNetworkingGlobalLock::AssertHeldByCurrentThread();
Assert( m_hListenSocketSelf == k_HSteamListenSocket_Invalid );
// Assign us a handle, and add us to the global table
{
// We actually don't do map "lookups". We assume the number of listen sockets
// is going to be reasonably small.
static int s_nDummy;
++s_nDummy;
int idx = g_mapListenSockets.Insert( s_nDummy, this );
Assert( idx < 0x1000 );
// Use upper 15 bits as a connection sequence number, so that listen socket handles
// are not reused within a short time period.
// (The top bit is reserved, so that listen socket handles and poll group handles
// come from a different namespace, so that we can immediately detect using the wrong
// and make that bug more obvious.)
static uint32 s_nUpperBits = 0;
s_nUpperBits += 0x10000;
if ( s_nUpperBits & 0x10000000 )
s_nUpperBits = 0x10000;
// Add it to our table of listen sockets
m_hListenSocketSelf = HSteamListenSocket( idx | s_nUpperBits );
}
// Set options, if any
if ( pOptions )
{
for ( int i = 0 ; i < nOptions ; ++i )
{
if ( !m_pSteamNetworkingSocketsInterface->m_pSteamNetworkingUtils->SetConfigValueStruct( pOptions[i], k_ESteamNetworkingConfig_ListenSocket, m_hListenSocketSelf ) )
{
V_sprintf_safe( errMsg, "Error setting option %d", pOptions[i].m_eValue );
return false;
}
}
}
else if ( nOptions != 0 )
{
V_strcpy_safe( errMsg, "Options list is NULL, but nOptions != 0?" );
return false;
}
// Check if symmetric is enabled, then make sure it's supported.
// It cannot be changed after listen socket creation
m_connectionConfig.SymmetricConnect.Lock();
if ( BSymmetricMode() )
{
if ( !BSupportsSymmetricMode() )
{
V_strcpy_safe( errMsg, "Symmetric mode not supported" );
return false;
}
}
// OK
return true;
}
void CSteamNetworkListenSocketBase::Destroy()
{
SteamNetworkingGlobalLock::AssertHeldByCurrentThread();
// Destroy all child connections
FOR_EACH_HASHMAP( m_mapChildConnections, h )
{
CSteamNetworkConnectionBase *pChild = m_mapChildConnections[ h ];
ConnectionScopeLock connectionLock( *pChild );
Assert( pChild->m_pParentListenSocket == this );
Assert( pChild->m_hSelfInParentListenSocketMap == h );
int n = m_mapChildConnections.Count();
pChild->ConnectionQueueDestroy();
Assert( m_mapChildConnections.Count() == n-1 );
(void)n; // Suppress warning if asserts aren't enabled
}
#ifdef STEAMNETWORKINGSOCKETS_STEAMCLIENT
if ( m_pLegacyPollGroup )
{
m_pLegacyPollGroup->m_lock.lock(); // Don't use scope object. It will unlock when we destruct
m_pLegacyPollGroup.reset();
}
#endif
// Self destruct
delete this;
}
bool CSteamNetworkListenSocketBase::APIGetAddress( SteamNetworkingIPAddr *pAddress )
{
// Base class doesn't know
return false;
}
bool CSteamNetworkListenSocketBase::BSupportsSymmetricMode()
{
return false;
}
bool CSteamNetworkListenSocketBase::BAddChildConnection( CSteamNetworkConnectionBase *pConn, SteamNetworkingErrMsg &errMsg )
{
pConn->AssertLocksHeldByCurrentThread();
// Safety check
if ( pConn->m_pParentListenSocket || pConn->m_hSelfInParentListenSocketMap != -1 || pConn->m_hConnectionSelf != k_HSteamNetConnection_Invalid )
{
Assert( pConn->m_pParentListenSocket == nullptr );
Assert( pConn->m_hSelfInParentListenSocketMap == -1 );
Assert( pConn->m_hConnectionSelf == k_HSteamNetConnection_Invalid );
V_sprintf_safe( errMsg, "Cannot add child connection - connection already has a parent or is in connection map?" );
return false;
}
if ( pConn->m_identityRemote.IsInvalid() || !pConn->m_unConnectionIDRemote )
{
Assert( !pConn->m_identityRemote.IsInvalid() );
Assert( pConn->m_unConnectionIDRemote );
V_sprintf_safe( errMsg, "Cannot add child connection - connection not initialized with remote identity/ConnID" );
return false;
}
RemoteConnectionKey_t key{ pConn->m_identityRemote, pConn->m_unConnectionIDRemote };
if ( m_mapChildConnections.Find( key ) != m_mapChildConnections.InvalidIndex() )
{
V_sprintf_safe( errMsg, "Duplicate child connection! %s %u", SteamNetworkingIdentityRender( pConn->m_identityRemote ).c_str(), pConn->m_unConnectionIDRemote );
AssertMsg1( false, "%s", errMsg );
return false;
}
// Setup linkage
pConn->m_pParentListenSocket = this;
pConn->m_hSelfInParentListenSocketMap = m_mapChildConnections.Insert( key, pConn );
pConn->m_bConnectionInitiatedRemotely = true;
// Connection configuration will inherit from us
pConn->m_connectionConfig.Init( &m_connectionConfig );
// If we are possibly providing an old interface that did not have poll groups,
// add the connection to the default poll group. (But note that certain use cases,
// e.g. custom signaling, the poll group may have already been assigned by the app code.
// Don't override it, if so.)
#ifdef STEAMNETWORKINGSOCKETS_STEAMCLIENT
if ( !pConn->m_pPollGroup )
{
if ( !m_pLegacyPollGroup )
m_pLegacyPollGroup.reset( new CSteamNetworkPollGroup( m_pSteamNetworkingSocketsInterface ) );
pConn->SetPollGroup( m_pLegacyPollGroup.get() );
}
#endif
return true;
}
void CSteamNetworkListenSocketBase::AboutToDestroyChildConnection( CSteamNetworkConnectionBase *pConn )
{
Assert( pConn->m_pParentListenSocket == this );
int hChild = pConn->m_hSelfInParentListenSocketMap;
pConn->m_pParentListenSocket = nullptr;
pConn->m_hSelfInParentListenSocketMap = -1;
if ( m_mapChildConnections[ hChild ] == pConn )
{
m_mapChildConnections[ hChild ] = nullptr; // just for kicks
m_mapChildConnections.RemoveAt( hChild );
}
else
{
AssertMsg( false, "Listen socket child list corruption!" );
FOR_EACH_HASHMAP( m_mapChildConnections, h )
{
if ( m_mapChildConnections[h] == pConn )
m_mapChildConnections.RemoveAt(h);
}
}
}
/////////////////////////////////////////////////////////////////////////////
//
// Abstract connection classes
//
/////////////////////////////////////////////////////////////////////////////
CSteamNetworkConnectionBase::CSteamNetworkConnectionBase( CSteamNetworkingSockets *pSteamNetworkingSocketsInterface, ConnectionScopeLock &scopeLock )
: ILockableThinker( m_defaultLock )
, m_pSteamNetworkingSocketsInterface( pSteamNetworkingSocketsInterface )
{
m_hConnectionSelf = k_HSteamNetConnection_Invalid;
m_eConnectionState = k_ESteamNetworkingConnectionState_None;
m_eConnectionWireState = k_ESteamNetworkingConnectionState_None;
m_usecWhenEnteredConnectionState = 0;
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_DIAGNOSTICSUI
m_usecWhenNextDiagnosticsUpdate = k_nThinkTime_Never;
#endif
m_usecWhenSentConnectRequest = 0;
m_usecWhenCreated = 0;
m_ulHandshakeRemoteTimestamp = 0;
m_usecWhenReceivedHandshakeRemoteTimestamp = 0;
m_eEndReason = k_ESteamNetConnectionEnd_Invalid;
m_szEndDebug[0] = '\0';
memset( &m_identityLocal, 0, sizeof(m_identityLocal) );
memset( &m_identityRemote, 0, sizeof(m_identityRemote) );
m_unConnectionIDLocal = 0;
m_unConnectionIDRemote = 0;
m_pParentListenSocket = nullptr;
m_pPollGroup = nullptr;
m_hSelfInParentListenSocketMap = -1;
m_bCertHasIdentity = false;
m_bCryptKeysValid = false;
m_eNegotiatedCipher = k_ESteamNetworkingSocketsCipher_INVALID;
m_cbEncryptionOverhead = k_cbAESGCMTagSize;
memset( m_szAppName, 0, sizeof( m_szAppName ) );
memset( m_szDescription, 0, sizeof( m_szDescription ) );
m_bConnectionInitiatedRemotely = false;
m_pTransport = nullptr;
m_nSupressStateChangeCallbacks = 0;
// Initialize configuration using parent interface for now.
m_connectionConfig.Init( &m_pSteamNetworkingSocketsInterface->m_connectionConfig );
// We should always hold the lock while initializing a connection
m_pLock = &m_defaultLock;
scopeLock.Lock( *m_pLock );
}
CSteamNetworkConnectionBase::~CSteamNetworkConnectionBase()
{
Assert( m_eConnectionState == k_ESteamNetworkingConnectionState_Dead );
Assert( m_eConnectionWireState == k_ESteamNetworkingConnectionState_Dead );
Assert( m_queueRecvMessages.empty() );
Assert( m_pParentListenSocket == nullptr );
Assert( m_pMessagesEndPointSessionOwner == nullptr );
SteamNetworkingGlobalLock::AssertHeldByCurrentThread();
g_tables_lock.AssertHeldByCurrentThread();
// Remove from global connection list
if ( m_hConnectionSelf != k_HSteamNetConnection_Invalid )
{
int idx = g_mapConnections.Find( uint16( m_hConnectionSelf ) );
if ( idx == g_mapConnections.InvalidIndex() || g_mapConnections[ idx ] != this )
{
AssertMsg( false, "Connection list bookeeping corruption" );
FOR_EACH_HASHMAP( g_mapConnections, i )
{
if ( g_mapConnections[i] == this )
g_mapConnections.RemoveAt( i );
}
}
else
{
g_mapConnections[ idx ] = nullptr; // Just for grins
g_mapConnections.RemoveAt( idx );
}
m_hConnectionSelf = k_HSteamNetConnection_Invalid;
}
// Save connection ID so we avoid using the same thing in the very near future.
if ( m_unConnectionIDLocal )
{
// Trim history to max. If we're really cycling through connections fast, this
// history won't be very useful, but that should be an extremely rare edge case,
// and the worst thing that happens is that we have a higher chance of reusing
// a connection ID that shares the same bottom 16 bits.
while ( s_vecRecentLocalConnectionIDs.Count() >= k_nMaxRecentLocalConnectionIDs )
s_vecRecentLocalConnectionIDs.Remove( 0 );
s_vecRecentLocalConnectionIDs.AddToTail( (uint16)m_unConnectionIDLocal );
// Clear it, since this function should be idempotent
m_unConnectionIDLocal = 0;
}
}
static std::vector<CSteamNetworkConnectionBase *> s_vecPendingDeleteConnections;
static ShortDurationLock s_lockPendingDeleteConnections( "connection_delete_queue" );
void CSteamNetworkConnectionBase::ConnectionQueueDestroy()
{
AssertLocksHeldByCurrentThread();
// Make sure all resources have been freed, etc
FreeResources();
// We don't need to be in the thinker list
IThinker::ClearNextThinkTime();
// Put into list
s_lockPendingDeleteConnections.lock();
s_vecPendingDeleteConnections.push_back(this);
s_lockPendingDeleteConnections.unlock();
}
void CSteamNetworkConnectionBase::ProcessDeletionList()
{
SteamNetworkingGlobalLock::AssertHeldByCurrentThread();
if ( s_vecPendingDeleteConnections.empty() )
return;
// Swap into a temp vector. Our lock hygiene code doesn't
// want us to take a ShortDurationLock and then take any
// other locks.
s_lockPendingDeleteConnections.lock();
std::vector<CSteamNetworkConnectionBase *> vecTemp( std::move( s_vecPendingDeleteConnections ) );
s_vecPendingDeleteConnections.clear();
s_lockPendingDeleteConnections.unlock();
// Now actually process the list. We need the tables
// lock in order to remove connections from global tables.
TableScopeLock tablesLock( g_tables_lock );
for ( CSteamNetworkConnectionBase *pConnection: vecTemp )
{
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_STEAMNETWORKINGMESSAGES
CMessagesEndPointSession *pMessagesSession = pConnection->m_pMessagesEndPointSessionOwner;
if ( pMessagesSession )
{
ConnectionScopeLock scopeLock( *pMessagesSession->m_pLock );
pMessagesSession->SetNextThinkTimeASAP();
pMessagesSession->UnlinkConnectionNow( pConnection );
Assert( pConnection->m_pMessagesEndPointSessionOwner == nullptr );
}
#endif
delete pConnection;
}
}
void CConnectionTransport::TransportDestroySelfNow()
{
AssertLocksHeldByCurrentThread();
// Call virtual functions while we still can
TransportFreeResources();
// Self destruct NOW
delete this;
}
void CConnectionTransport::TransportFreeResources()
{
}
void CSteamNetworkConnectionBase::FreeResources()
{
AssertLocksHeldByCurrentThread();
// Make sure we're marked in the dead state, and also if we were in an
// API-visible state, this will queue the state change notification
// while we still know who our listen socket is (if any).
//
// NOTE: Once this happens, any table lookup that finds us will return NULL.
// So we basically don't exist to you if all you have is a handle
SetState( k_ESteamNetworkingConnectionState_Dead, SteamNetworkingSockets_GetLocalTimestamp() );
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_FAKEIP
m_fakeIPRefRemote.Clear();
#endif
// Discard any messages that weren't retrieved
g_lockAllRecvMessageQueues.lock();
m_queueRecvMessages.PurgeMessages();
g_lockAllRecvMessageQueues.unlock();
// If we are in a poll group, remove us from the group
RemoveFromPollGroup();
// Detach from the listen socket that owns us, if any
if ( m_pParentListenSocket )
m_pParentListenSocket->AboutToDestroyChildConnection( this );
// Make sure and clean out crypto keys and such now
ClearCrypto();
// Clean up our transport
DestroyTransport();
}
void CSteamNetworkConnectionBase::DestroyTransport()
{
AssertLocksHeldByCurrentThread( "DestroyTransport" );
if ( m_pTransport )
{
m_pTransport->TransportDestroySelfNow();
m_pTransport = nullptr;
}
}
void CSteamNetworkConnectionBase::RemoveFromPollGroup()
{
AssertLocksHeldByCurrentThread( "RemoveFromPollGroup" );
if ( !m_pPollGroup )
return;
PollGroupScopeLock pollGroupLock( m_pPollGroup->m_lock );
// Scan all of our messages, and make sure they are not in the secondary queue
{
ShortDurationScopeLock lockMessageQueues( g_lockAllRecvMessageQueues );
for ( CSteamNetworkingMessage *pMsg = m_queueRecvMessages.m_pFirst ; pMsg ; pMsg = pMsg->m_links.m_pNext )
{
Assert( pMsg->m_links.m_pQueue == &m_queueRecvMessages );
// It *should* be in the secondary queue of the poll group
Assert( pMsg->m_linksSecondaryQueue.m_pQueue == &m_pPollGroup->m_queueRecvMessages );
// OK, do the work
pMsg->UnlinkFromQueue( &CSteamNetworkingMessage::m_linksSecondaryQueue );
}
}
// Remove us from the poll group's list. DbgVerify because we should be in the list!
DbgVerify( m_pPollGroup->m_vecConnections.FindAndFastRemove( this ) );
// We're not in a poll group anymore
m_pPollGroup = nullptr;
}
void CSteamNetworkConnectionBase::SetPollGroup( CSteamNetworkPollGroup *pPollGroup )
{
AssertLocksHeldByCurrentThread( "SetPollGroup" );
// Quick early-out for no change
if ( m_pPollGroup == pPollGroup )
return;
// Clearing it?
if ( !pPollGroup )
{
RemoveFromPollGroup();
return;
}
// Grab locks for old and new poll groups. Remember, we can take multiple locks without
// worrying about deadlock because we hold the global lock
PollGroupScopeLock pollGroupLockNew( pPollGroup->m_lock );
PollGroupScopeLock pollGroupLockOld;
if ( m_pPollGroup )
pollGroupLockOld.Lock( m_pPollGroup->m_lock );
// Scan all messages that are already queued for this connection,
// and insert them into the poll groups queue in the (approximate)
// appropriate spot. Using local timestamps should be really close
// for ordering messages between different connections. Remember
// that the API very clearly does not provide strong guarantees
// regarding ordering of messages from different connections, and
// really anybody who is expecting or relying on such guarantees
// is probably doing something wrong.
{
ShortDurationScopeLock lockMessageQueues( g_lockAllRecvMessageQueues );
CSteamNetworkingMessage *pInsertBefore = pPollGroup->m_queueRecvMessages.m_pFirst;
for ( CSteamNetworkingMessage *pMsg = m_queueRecvMessages.m_pFirst ; pMsg ; pMsg = pMsg->m_links.m_pNext )
{
Assert( pMsg->m_links.m_pQueue == &m_queueRecvMessages );
// Unlink it from existing poll group queue, if any
if ( pMsg->m_linksSecondaryQueue.m_pQueue )
{
Assert( m_pPollGroup && pMsg->m_linksSecondaryQueue.m_pQueue == &m_pPollGroup->m_queueRecvMessages );
pMsg->UnlinkFromQueue( &CSteamNetworkingMessage::m_linksSecondaryQueue );
}
else
{
Assert( !m_pPollGroup );
}
// Scan forward in the poll group message queue, until we find the insertion point
for (;;)
{
// End of queue?
if ( !pInsertBefore )
{
pMsg->LinkToQueueTail( &CSteamNetworkingMessage::m_linksSecondaryQueue, &pPollGroup->m_queueRecvMessages );
break;
}
Assert( pInsertBefore->m_linksSecondaryQueue.m_pQueue == &pPollGroup->m_queueRecvMessages );
if ( pInsertBefore->m_usecTimeReceived > pMsg->m_usecTimeReceived )
{
pMsg->LinkBefore( pInsertBefore, &CSteamNetworkingMessage::m_linksSecondaryQueue, &pPollGroup->m_queueRecvMessages );
break;
}
pInsertBefore = pInsertBefore->m_linksSecondaryQueue.m_pNext;
}
}
}
// Tell previous poll group, if any, that we are no longer with them
if ( m_pPollGroup )
{
DbgVerify( m_pPollGroup->m_vecConnections.FindAndFastRemove( this ) );
}
// Link to new poll group
m_pPollGroup = pPollGroup;
Assert( !m_pPollGroup->m_vecConnections.HasElement( this ) );
m_pPollGroup->m_vecConnections.AddToTail( this );
}
bool CSteamNetworkConnectionBase::BInitConnection( SteamNetworkingMicroseconds usecNow, int nOptions, const SteamNetworkingConfigValue_t *pOptions, SteamDatagramErrMsg &errMsg )
{
AssertLocksHeldByCurrentThread( "Base::BInitConnection" );
// Should only be called while we are in the initial state
Assert( GetState() == k_ESteamNetworkingConnectionState_None );
// Make sure MTU values are initialized
UpdateMTUFromConfig( true );
Assert( m_hConnectionSelf == k_HSteamNetConnection_Invalid );
Assert( m_pParentListenSocket == nullptr || m_pSteamNetworkingSocketsInterface == m_pParentListenSocket->m_pSteamNetworkingSocketsInterface );
// We need to know who we are
if ( m_identityLocal.IsInvalid() )
{
if ( !m_pSteamNetworkingSocketsInterface->GetIdentity( &m_identityLocal ) )
{
V_strcpy_safe( errMsg, "We don't know our local identity." );
return false;
}
}
m_eEndReason = k_ESteamNetConnectionEnd_Invalid;
m_szEndDebug[0] = '\0';
m_statsEndToEnd.Init( usecNow, ELinkActivityLevel::Disconnected ); // Until we go connected don't try to send acks, etc
m_usecWhenCreated = usecNow;
// Select random connection ID, and make sure it passes certain sanity checks
{
Assert( m_unConnectionIDLocal == 0 );
// OK, even though *usually* we cannot take the table lock after holding
// a connection lock (since we often take them in the opposite order),
// in this case it's OK because:
//
// 1.) We hold the global lock AND
// 2.) This is a new connection, and not previously in the table so there is no way
// for any other thread that might be holding the table lock at this time to
// subsequently try to wait on any locks that we hold.
TableScopeLock tableLock( g_tables_lock );
// We make sure the lower 16 bits are unique. Make sure we don't have too many connections.
// This definitely could be relaxed, but honestly we don't expect this library to be used in situations
// where you need that many connections.
if ( g_mapConnections.Count() >= 0x1fff )
{
V_strcpy_safe( errMsg, "Too many connections." );
return false;
}
int tries = 0;
for (;;) {
if ( ++tries > 10000 )
{
V_strcpy_safe( errMsg, "Unable to find unique connection ID" );
return false;
}
CCrypto::GenerateRandomBlock( &m_unConnectionIDLocal, sizeof(m_unConnectionIDLocal) );
// Make sure neither half is zero
if ( ( m_unConnectionIDLocal & 0xffff ) == 0 )
continue;
if ( ( m_unConnectionIDLocal & 0xffff0000 ) == 0 )
continue;
// Check recent connections
if ( s_vecRecentLocalConnectionIDs.HasElement( (uint16)m_unConnectionIDLocal ) )
continue;
// Check active connections
if ( g_mapConnections.HasElement( (uint16)m_unConnectionIDLocal ) )
continue;
// This one's good
break;
}
// Let's use the the connection ID as the connection handle. It's random, not reused
// within a short time interval, and we print it in our debugging in places, and you
// can see it on the wire for debugging. In the past we has a "clever" method of
// assigning the handle that had some cute performance tricks for lookups and
// guaranteeing handles wouldn't be reused. But making it be the same as the
// ConnectionID is probably just more useful and less confusing.
m_hConnectionSelf = m_unConnectionIDLocal;
// Add it to our table of active sockets.
g_mapConnections.Insert( int16( m_hConnectionSelf ), this );
} // Release table scope lock
// Set options, if any
if ( pOptions )
{
for ( int i = 0 ; i < nOptions ; ++i )
{
if ( !m_pSteamNetworkingSocketsInterface->m_pSteamNetworkingUtils->SetConfigValueStruct( pOptions[i], k_ESteamNetworkingConfig_Connection, m_hConnectionSelf ) )
{
V_sprintf_safe( errMsg, "Error setting option %d", pOptions[i].m_eValue );
return false;
}
}
}
else if ( nOptions != 0 )
{
V_strcpy_safe( errMsg, "Options list is NULL, but nOptions != 0?" );
return false;
}
// Bind effective user data into the connection now. It can no longer be inherited
m_connectionConfig.ConnectionUserData.Set( m_connectionConfig.ConnectionUserData.Get() );
// Make sure a description has been set for debugging purposes
SetDescription();
// Clear everything out
ClearCrypto();
// We should still be in the initial state
Assert( GetState() == k_ESteamNetworkingConnectionState_None );
// Take action to start obtaining a cert, or if we already have one, then set it now
InitConnectionCrypto( usecNow );
if ( GetState() != k_ESteamNetworkingConnectionState_None )
{
Assert( GetState() == k_ESteamNetworkingConnectionState_ProblemDetectedLocally );
V_sprintf_safe( errMsg, "Crypto init error. %s", m_szEndDebug );
return false;
}
// Start with a single lane
DbgVerify( SNP_ConfigureLanes( 1, nullptr, nullptr ) == k_EResultOK );
return true;
}
bool CSteamNetworkConnectionBase::BSupportsSymmetricMode()
{
return false;
}