-
Notifications
You must be signed in to change notification settings - Fork 712
Expand file tree
/
Copy pathcsteamnetworkingsockets.cpp
More file actions
2514 lines (2145 loc) · 82.7 KB
/
csteamnetworkingsockets.cpp
File metadata and controls
2514 lines (2145 loc) · 82.7 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
//====== Copyright Valve Corporation, All rights reserved. ====================
#include "csteamnetworkingsockets.h"
#include "steamnetworkingsockets_lowlevel.h"
#include "steamnetworkingsockets_connections.h"
#include "steamnetworkingsockets_udp.h"
#include "../steamnetworkingsockets_certstore.h"
#include "crypto.h"
#ifdef STEAMNETWORKINGSOCKETS_STANDALONELIB
#include <steam/steamnetworkingsockets.h>
#endif
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_STEAMNETWORKINGMESSAGES
#include "csteamnetworkingmessages.h"
#endif
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_FAKEIP
#include <steam/steamnetworkingfakeip.h>
#endif
// Needed for the platform checks below
#if defined(__APPLE__)
#include "AvailabilityMacros.h"
#include "TargetConditionals.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
ISteamNetworkingSockets::~ISteamNetworkingSockets() {}
ISteamNetworkingUtils::~ISteamNetworkingUtils() {}
// Put everything in a namespace, so we don't violate the one definition rule
namespace SteamNetworkingSocketsLib {
/////////////////////////////////////////////////////////////////////////////
//
// Configuration Variables
//
/////////////////////////////////////////////////////////////////////////////
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketLoss_Send, 0.0f, 0.0f, 100.0f );
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketLoss_Recv, 0.0f, 0.0f, 100.0f );
DEFINE_GLOBAL_CONFIGVAL( int32, FakePacketLag_Send, 0, 0, 5000 );
DEFINE_GLOBAL_CONFIGVAL( int32, FakePacketLag_Recv, 0, 0, 5000 );
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketReorder_Send, 0.0f, 0.0f, 100.0f );
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketReorder_Recv, 0.0f, 0.0f, 100.0f );
DEFINE_GLOBAL_CONFIGVAL( int32, FakePacketReorder_Time, 15, 0, 5000 );
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketDup_Send, 0.0f, 0.0f, 100.0f );
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketDup_Recv, 0.0f, 0.0f, 100.0f );
DEFINE_GLOBAL_CONFIGVAL( int32, FakePacketDup_TimeMax, 10, 0, 5000 );
DEFINE_GLOBAL_CONFIGVAL( int32, PacketTraceMaxBytes, -1, -1, 99999 );
DEFINE_GLOBAL_CONFIGVAL( int32, FakeRateLimit_Send_Rate, 0, 0, 1024*1024*1024 );
DEFINE_GLOBAL_CONFIGVAL( int32, FakeRateLimit_Send_Burst, 16*1024, 0, 1024*1024 );
DEFINE_GLOBAL_CONFIGVAL( int32, FakeRateLimit_Recv_Rate, 0, 0, 1024*1024*1024 );
DEFINE_GLOBAL_CONFIGVAL( int32, FakeRateLimit_Recv_Burst, 16*1024, 0, 1024*1024 );
DEFINE_GLOBAL_CONFIGVAL( void *, Callback_AuthStatusChanged, nullptr );
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_STEAMNETWORKINGMESSAGES
DEFINE_GLOBAL_CONFIGVAL( void*, Callback_MessagesSessionRequest, nullptr );
DEFINE_GLOBAL_CONFIGVAL( void*, Callback_MessagesSessionFailed, nullptr );
#endif
DEFINE_GLOBAL_CONFIGVAL( void *, Callback_CreateConnectionSignaling, nullptr );
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_FAKEIP
DEFINE_GLOBAL_CONFIGVAL( void *, Callback_FakeIPResult, nullptr );
#endif
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, TimeoutInitial, 10000, 0, INT32_MAX );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, TimeoutConnected, 10000, 0, INT32_MAX );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, SendBufferSize, 512*1024, 4*1024, 0x10000000 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, RecvBufferSize, 1024*1024, 4*1024, 0x10000000 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, RecvBufferMessages, 1000, 2, 0x10000000 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, RecvMaxMessageSize, 512*1024, 64, 0x10000000 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, RecvMaxSegmentsPerPacket, k_cbSteamNetworkingSocketsMaxUDPMsgLen, 1, k_cbSteamNetworkingSocketsMaxUDPMsgLen );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int64, ConnectionUserData, -1 ); // no limits here
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, SendRateMin, 256*1024, 1024, 0x10000000 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, SendRateMax, 256*1024, 1024, 0x10000000 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, NagleTime, 5000, 0, 20000 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, MTU_PacketSize, 1300, k_cbSteamNetworkingSocketsMinMTUPacketSize, k_cbSteamNetworkingSocketsMaxUDPMsgLen );
#ifdef STEAMNETWORKINGSOCKETS_OPENSOURCE
// We don't have a trusted third party, so allow this by default,
// and don't warn about it
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, IP_AllowWithoutAuth, 2, 0, 2 );
#else
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, IP_AllowWithoutAuth, 0, 0, 2 );
#endif
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, Unencrypted, 0, 0, 3 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, SymmetricConnect, 0, 0, 1 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, LocalVirtualPort, -1, -1, INT32_MAX );
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_DUALWIFI
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, DualWifi_Enable, 1, 0, k_nDualWifiEnable_MAX );
#endif
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, LogLevel_AckRTT, k_ESteamNetworkingSocketsDebugOutputType_Warning, k_ESteamNetworkingSocketsDebugOutputType_Error, k_ESteamNetworkingSocketsDebugOutputType_Everything );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, LogLevel_PacketDecode, k_ESteamNetworkingSocketsDebugOutputType_Warning, k_ESteamNetworkingSocketsDebugOutputType_Error, k_ESteamNetworkingSocketsDebugOutputType_Everything );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, LogLevel_Message, k_ESteamNetworkingSocketsDebugOutputType_Warning, k_ESteamNetworkingSocketsDebugOutputType_Error, k_ESteamNetworkingSocketsDebugOutputType_Everything );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, LogLevel_PacketGaps, k_ESteamNetworkingSocketsDebugOutputType_Warning, k_ESteamNetworkingSocketsDebugOutputType_Error, k_ESteamNetworkingSocketsDebugOutputType_Everything );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, LogLevel_P2PRendezvous, k_ESteamNetworkingSocketsDebugOutputType_Warning, k_ESteamNetworkingSocketsDebugOutputType_Error, k_ESteamNetworkingSocketsDebugOutputType_Everything );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( void *, Callback_ConnectionStatusChanged, nullptr );
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_DIAGNOSTICSUI
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, EnableDiagnosticsUI, 1, 0, 1 );
#endif
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_ICE
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( std::string, P2P_STUN_ServerList, "" );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( std::string, P2P_TURN_ServerList, "" );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( std::string, P2P_TURN_UserList, "" );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( std::string, P2P_TURN_PassList, "" );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, P2P_Transport_ICE_Implementation, 0, 0, 2 );
COMPILE_TIME_ASSERT( k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_Default == -1 );
COMPILE_TIME_ASSERT( k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_Disable == 0 );
#ifdef STEAMNETWORKINGSOCKETS_OPENSOURCE
// There is no such thing as "default" if we don't have some sort of platform
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, P2P_Transport_ICE_Enable, k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_All, k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_Disable, k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_All );
#else
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, P2P_Transport_ICE_Enable, k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_Default, k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_Default, k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_All );
#endif
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, P2P_Transport_ICE_Penalty, 0, 0, INT_MAX );
#endif
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_SDR
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( std::string, SDRClient_DebugTicketAddress, "" );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, P2P_Transport_SDR_Penalty, 0, 0, INT_MAX );
#endif
static GlobalConfigValueEntry *s_pFirstGlobalConfigEntry = nullptr;
static bool s_bConfigValueTableInitted = false;
static std::vector<GlobalConfigValueEntry *> s_vecConfigValueTable; // Sorted by value
static std::vector<GlobalConfigValueEntry *> s_vecConnectionConfigValueTable; // Sorted by offset
GlobalConfigValueEntry::GlobalConfigValueEntry(
ESteamNetworkingConfigValue eValue,
const char *pszName,
ESteamNetworkingConfigDataType eDataType,
ESteamNetworkingConfigScope eScope,
int cbOffsetOf
) : m_eValue{ eValue }
, m_pszName{ pszName }
, m_eDataType{ eDataType }
, m_eScope{ eScope }
, m_cbOffsetOf{cbOffsetOf}
, m_pNextEntry( s_pFirstGlobalConfigEntry )
{
s_pFirstGlobalConfigEntry = this;
AssertMsg( !s_bConfigValueTableInitted, "Attempt to register more config values after table is already initialized" );
s_bConfigValueTableInitted = false;
}
static void EnsureConfigValueTableInitted()
{
SteamNetworkingGlobalLock::AssertHeldByCurrentThread( "EnsureConfigValueTableInitted" );
if ( s_bConfigValueTableInitted )
return;
for ( GlobalConfigValueEntry *p = s_pFirstGlobalConfigEntry ; p ; p = p->m_pNextEntry )
{
s_vecConfigValueTable.push_back( p );
if ( p->m_eScope == k_ESteamNetworkingConfig_Connection )
s_vecConnectionConfigValueTable.push_back( p );
}
// Sort in ascending order by value, so we can binary search
std::sort( s_vecConfigValueTable.begin(), s_vecConfigValueTable.end(),
[]( GlobalConfigValueEntry *a, GlobalConfigValueEntry *b ) { return a->m_eValue < b->m_eValue; } );
// Sort by struct offset, so that ConnectionConfig::Init will access memory in a sane way.
// This doesn't really matter, though.
std::sort( s_vecConnectionConfigValueTable.begin(), s_vecConnectionConfigValueTable.end(),
[]( GlobalConfigValueEntry *a, GlobalConfigValueEntry *b ) { return a->m_cbOffsetOf < b->m_cbOffsetOf; } );
// Rebuild linked list, in order, and safety check for duplicates
const int N = len( s_vecConfigValueTable );
for ( int i = 1 ; i < N ; ++i )
{
s_vecConfigValueTable[i-1]->m_pNextEntry = s_vecConfigValueTable[i];
AssertMsg1( s_vecConfigValueTable[i-1]->m_eValue < s_vecConfigValueTable[i]->m_eValue, "Registered duplicate config value %d", s_vecConfigValueTable[i]->m_eValue );
}
s_vecConfigValueTable[N-1]->m_pNextEntry = nullptr;
s_pFirstGlobalConfigEntry = nullptr;
s_bConfigValueTableInitted = true; // Set this flag LAST
}
static GlobalConfigValueEntry *FindConfigValueEntry( ESteamNetworkingConfigValue eSearchVal )
{
Assert( s_bConfigValueTableInitted );
// Binary search
int l = 0;
int r = len( s_vecConfigValueTable )-1;
Assert( r > 0 ); // Order of operations -- table not initialized!
while ( l <= r )
{
int m = (l+r)>>1;
GlobalConfigValueEntry *mp = s_vecConfigValueTable[m];
if ( eSearchVal < mp->m_eValue )
r = m-1;
else if ( eSearchVal > mp->m_eValue )
l = m+1;
else
return mp;
}
// Not found
return nullptr;
}
void ConnectionConfig::Init( ConnectionConfig *pInherit )
{
Assert( s_bConfigValueTableInitted );
for ( GlobalConfigValueEntry *pEntry : s_vecConnectionConfigValueTable )
{
ConfigValueBase *pVal = (ConfigValueBase *)((intptr_t)this + pEntry->m_cbOffsetOf );
if ( pInherit )
{
pVal->m_pInherit = (ConfigValueBase *)((intptr_t)pInherit + pEntry->m_cbOffsetOf );
}
else
{
// Assume the relevant members are the same, no matter
// what type T, so just use int32 arbitrarily
pVal->m_pInherit = &( static_cast< GlobalConfigValueBase<int32> * >( pEntry ) )->m_value;
}
}
}
/////////////////////////////////////////////////////////////////////////////
//
// Table of active sockets
//
/////////////////////////////////////////////////////////////////////////////
CUtlHashMap<uint16, CSteamNetworkConnectionBase *, std::equal_to<uint16>, Identity<uint16> > g_mapConnections;
CUtlHashMap<int, CSteamNetworkPollGroup *, std::equal_to<int>, Identity<int> > g_mapPollGroups;
TableLock g_tables_lock;
// Table of active listen sockets. Listen sockets and this table are protected
// by the global lock.
CUtlHashMap<int, CSteamNetworkListenSocketBase *, std::equal_to<int>, Identity<int> > g_mapListenSockets;
static bool BConnectionStateExistsToAPI( ESteamNetworkingConnectionState eState )
{
switch ( eState )
{
default:
Assert( false );
return false;
case k_ESteamNetworkingConnectionState_None:
case k_ESteamNetworkingConnectionState_Dead:
case k_ESteamNetworkingConnectionState_FinWait:
case k_ESteamNetworkingConnectionState_Linger:
return false;
case k_ESteamNetworkingConnectionState_Connecting:
case k_ESteamNetworkingConnectionState_FindingRoute:
case k_ESteamNetworkingConnectionState_Connected:
case k_ESteamNetworkingConnectionState_ClosedByPeer:
case k_ESteamNetworkingConnectionState_ProblemDetectedLocally:
return true;
}
}
static CSteamNetworkConnectionBase *InternalGetConnectionByHandle( HSteamNetConnection sock, ConnectionScopeLock &scopeLock, const char *pszLockTag, bool bForAPI )
{
if ( sock == 0 )
return nullptr;
// Take locks by "trying" and using a short timeout. The table lock
// should only be held by any one thread for an extremely short period
// of time, so if we end up waiting/looping here, it should be blocked
// on the connection lock. In general we should very seldom need
// to actually loop here, but doing this protects against a deadlock,
// because in rare situations we do need to take the locks in the
// opposite order.
for (;;)
{
// First take the table lock
TableScopeLock tableScopeLock;
if ( !tableScopeLock.TryLock( g_tables_lock, 1, nullptr ) )
continue;
int idx = g_mapConnections.Find( uint16( sock ) );
if ( idx == g_mapConnections.InvalidIndex() )
break;
CSteamNetworkConnectionBase *pResult = g_mapConnections[ idx ];
if ( !pResult )
{
AssertMsg( false, "g_mapConnections corruption!" );
break;
}
if ( uint16( pResult->m_hConnectionSelf ) != uint16( sock ) )
{
AssertMsg( false, "Connection map corruption!" );
break;
}
// Fetch the state of the connection. This is OK to do
// even if we don't have the lock. If the connection
// is already dead we can avoid even trying to take
// the lock. That's good because cleaning up is one
// of the rare cases where we take locks in the opposite
// order, so we want to avoid that.
ESteamNetworkingConnectionState s = pResult->GetState();
if ( s == k_ESteamNetworkingConnectionState_Dead )
break;
if ( bForAPI )
{
if ( !BConnectionStateExistsToAPI( s ) )
break;
}
// State looks good, try to lock the connection.
// NOTE: we still (briefly) hold the table lock!
// Taking the locks in this order (table, then connection)
// is the most common case by far, but in very rare
// cases we might need to take them in the opposite
// order, hence the loop
if ( !scopeLock.TryLock( *pResult->m_pLock, 1, pszLockTag ) )
continue;
// Re-check the connection state, in case something changed
// while we were waiting on the lock
s = pResult->GetState();
if ( s != k_ESteamNetworkingConnectionState_Dead )
{
if ( !bForAPI || BConnectionStateExistsToAPI( s ) )
{
// NOTE: Exiting this scope will invoke TableScopeLock destructor,
// which will unlock the table lock here, OUT OF ORDER of the order
// that we took the locks. That's intentional! We don't need that
// lock anymore, we have locked the connection that we want.
return pResult;
}
}
// Connection found in table, but should not be returned to the caller.
// Go ahead and immediately unlock the connection lock, the caller should not
// need it.
scopeLock.Unlock();
break;
}
return nullptr;
}
CSteamNetworkConnectionBase *GetConnectionByHandle( HSteamNetConnection sock, ConnectionScopeLock &scopeLock )
{
SteamNetworkingGlobalLock::AssertHeldByCurrentThread();
return InternalGetConnectionByHandle( sock, scopeLock, nullptr, false );
}
inline CSteamNetworkConnectionBase *GetConnectionByHandleForAPI( HSteamNetConnection sock, ConnectionScopeLock &scopeLock, const char *pszLockTag )
{
return InternalGetConnectionByHandle( sock, scopeLock, pszLockTag, true );
}
static CSteamNetworkListenSocketBase *GetListenSocketByHandle( HSteamListenSocket sock )
{
SteamNetworkingGlobalLock::AssertHeldByCurrentThread(); // listen sockets are protected by the global lock!
if ( sock == k_HSteamListenSocket_Invalid )
return nullptr;
AssertMsg( !(sock & 0x80000000), "A poll group handle was used where a listen socket handle was expected" );
int idx = sock & 0xffff;
if ( !g_mapListenSockets.IsValidIndex( idx ) )
return nullptr;
CSteamNetworkListenSocketBase *pResult = g_mapListenSockets[ idx ];
if ( pResult->m_hListenSocketSelf != sock )
{
// Slot was reused, but this handle is now invalid
return nullptr;
}
return pResult;
}
CSteamNetworkPollGroup *GetPollGroupByHandle( HSteamNetPollGroup hPollGroup, PollGroupScopeLock &scopeLock, const char *pszLockTag )
{
if ( hPollGroup == k_HSteamNetPollGroup_Invalid )
return nullptr;
AssertMsg( (hPollGroup & 0x80000000), "A listen socket handle was used where a poll group handle was expected" );
int idx = hPollGroup & 0xffff;
TableScopeLock tableScopeLock( g_tables_lock );
if ( !g_mapPollGroups.IsValidIndex( idx ) )
return nullptr;
CSteamNetworkPollGroup *pResult = g_mapPollGroups[ idx ];
// Make sure poll group is the one they really asked for, and also
// handle deletion race condition
while ( pResult->m_hPollGroupSelf == hPollGroup )
{
if ( scopeLock.TryLock( pResult->m_lock, 1, pszLockTag ) )
return pResult;
}
// Slot was reused, but this handle is now invalid,
// or poll group deleted race condition
return nullptr;
}
/////////////////////////////////////////////////////////////////////////////
//
// CSteamSocketNetworkingBase
//
/////////////////////////////////////////////////////////////////////////////
std::vector<CSteamNetworkingSockets *> CSteamNetworkingSockets::s_vecSteamNetworkingSocketsInstances;
CSteamNetworkingSockets::CSteamNetworkingSockets( CSteamNetworkingUtils *pSteamNetworkingUtils )
: m_bHaveLowLevelRef( false )
, m_pSteamNetworkingUtils( pSteamNetworkingUtils )
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_STEAMNETWORKINGMESSAGES
, m_pSteamNetworkingMessages( nullptr )
#endif
#ifdef STEAMNETWORKINGSOCKETS_CAN_REQUEST_CERT
, m_scheduleCheckRenewCert( this, &CSteamNetworkingSockets::CheckAuthenticationPrerequisites )
#endif
, m_bEverTriedToGetCert( false )
, m_bEverGotCert( false )
, m_mutexPendingCallbacks( "pending_callbacks" )
{
m_connectionConfig.Init( nullptr );
InternalClearIdentity();
}
void CSteamNetworkingSockets::InternalClearIdentity()
{
m_identity.Clear();
m_msgSignedCert.Clear();
m_msgCert.Clear();
m_keyPrivateKey.Wipe();
#ifdef STEAMNETWORKINGSOCKETS_CAN_REQUEST_CERT
m_CertStatus.m_eAvail = k_ESteamNetworkingAvailability_NeverTried;
m_CertStatus.m_debugMsg[0] = '\0';
#else
m_CertStatus.m_eAvail = k_ESteamNetworkingAvailability_CannotTry;
V_strcpy_safe( m_CertStatus.m_debugMsg, "No certificate authority" );
#endif
m_AuthenticationStatus = m_CertStatus;
m_bEverTriedToGetCert = false;
m_bEverGotCert = false;
}
void CSteamNetworkingSockets::InternalOnGotIdentity( int nIdentitySetFlags )
{
// No base class action
}
CSteamNetworkingSockets::~CSteamNetworkingSockets()
{
SteamNetworkingGlobalLock::AssertHeldByCurrentThread();
Assert( !m_bHaveLowLevelRef ); // Called destructor directly? Use Destroy()!
}
#ifdef STEAMNETWORKINGSOCKETS_OPENSOURCE
bool CSteamNetworkingSockets::BInitGameNetworkingSockets( const SteamNetworkingIdentity *pIdentity, SteamDatagramErrMsg &errMsg )
{
AssertMsg( !m_bHaveLowLevelRef, "Initted interface twice?" );
// Make sure low level socket support is ready
if ( !BInitLowLevel( errMsg ) )
return false;
if ( pIdentity )
m_identity = *pIdentity;
else
CacheIdentity();
return true;
}
#endif
bool CSteamNetworkingSockets::BInitLowLevel( SteamNetworkingErrMsg &errMsg )
{
if ( m_bHaveLowLevelRef )
return true;
if ( !BSteamNetworkingSocketsLowLevelAddRef( errMsg) )
return false;
// Add us to list of extant instances only after we have done some initialization
if ( !has_element( s_vecSteamNetworkingSocketsInstances, this ) )
s_vecSteamNetworkingSocketsInstances.push_back( this );
m_bHaveLowLevelRef = true;
return true;
}
void CSteamNetworkingSockets::KillConnections()
{
SteamNetworkingGlobalLock::AssertHeldByCurrentThread( "CSteamNetworkingSockets::KillConnections" );
TableScopeLock tableScopeLock( g_tables_lock );
// Nuke all messages endpoints. We need to do this because the sessions hold
// pointers to objects that we are about to destroy.
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_STEAMNETWORKINGMESSAGES
FOR_EACH_HASHMAP( m_mapMessagesEndpointByVirtualPort, idx )
{
m_mapMessagesEndpointByVirtualPort[idx]->DestroyMessagesEndPoint();
Assert( !m_mapMessagesEndpointByVirtualPort.IsValidIndex( idx ) ); // It should have removed itself from the map!
}
Assert( m_pSteamNetworkingMessages == nullptr );
Assert( m_mapMessagesEndpointByVirtualPort.Count() == 0 );
m_pSteamNetworkingMessages = nullptr; // Buuuuut we'll slam it, too, in case there's a bug
m_mapMessagesEndpointByVirtualPort.Purge();
#endif
// Destroy all of my connections
CSteamNetworkConnectionBase::ProcessDeletionList();
FOR_EACH_HASHMAP( g_mapConnections, idx )
{
CSteamNetworkConnectionBase *pConn = g_mapConnections[idx];
if ( pConn->m_pSteamNetworkingSocketsInterface == this )
{
ConnectionScopeLock connectionLock( *pConn );
// Check if it was left open, then do what we can to clean it up.
// (If we can fire off a quick cleanup packet to our peer, do that.)
if ( pConn->BStateIsActive() )
{
SpewMsg( "[%s] Cleaning up open connection on system shutdown", pConn->GetDescription() );
pConn->APICloseConnection( k_ESteamNetConnectionEnd_AppException_Max, "SteamNetworkingSockets shutdown", false );
}
pConn->ConnectionQueueDestroy();
}
}
CSteamNetworkConnectionBase::ProcessDeletionList();
// Destroy all of my listen sockets
FOR_EACH_HASHMAP( g_mapListenSockets, idx )
{
CSteamNetworkListenSocketBase *pSock = g_mapListenSockets[idx];
if ( pSock->m_pSteamNetworkingSocketsInterface == this )
{
DbgVerify( CloseListenSocket( pSock->m_hListenSocketSelf ) );
Assert( !g_mapListenSockets.IsValidIndex( idx ) );
}
}
// Destroy all of my poll groups
FOR_EACH_HASHMAP( g_mapPollGroups, idx )
{
CSteamNetworkPollGroup *pPollGroup = g_mapPollGroups[idx];
if ( pPollGroup->m_pSteamNetworkingSocketsInterface == this )
{
DbgVerify( DestroyPollGroup( pPollGroup->m_hPollGroupSelf ) );
Assert( !g_mapPollGroups.IsValidIndex( idx ) );
}
}
}
void CSteamNetworkingSockets::Destroy()
{
SteamNetworkingGlobalLock::AssertHeldByCurrentThread( "CSteamNetworkingSockets::Destroy" );
FreeResources();
// Remove from list of extant instances, if we are there
find_and_remove_element( s_vecSteamNetworkingSocketsInstances, this );
delete this;
}
void CSteamNetworkingSockets::FreeResources()
{
KillConnections();
// Clear identity and crypto stuff.
// If we are re-initialized, we might get new ones
InternalClearIdentity();
// Mark us as no longer being setup
if ( m_bHaveLowLevelRef )
{
m_bHaveLowLevelRef = false;
SteamNetworkingSocketsLowLevelDecRef();
}
}
bool CSteamNetworkingSockets::BHasAnyConnections() const
{
TableScopeLock tableScopeLock( g_tables_lock );
for ( CSteamNetworkConnectionBase *pConn: g_mapConnections.IterValues() )
{
if ( pConn->m_pSteamNetworkingSocketsInterface == this )
return true;
}
return false;
}
bool CSteamNetworkingSockets::BHasAnyListenSockets() const
{
TableScopeLock tableScopeLock( g_tables_lock );
for ( CSteamNetworkListenSocketBase *pSock: g_mapListenSockets.IterValues() )
{
if ( pSock->m_pSteamNetworkingSocketsInterface == this )
return true;
}
return false;
}
bool CSteamNetworkingSockets::GetIdentity( SteamNetworkingIdentity *pIdentity )
{
SteamNetworkingGlobalLock scopeLock( "GetIdentity" );
InternalGetIdentity();
if ( pIdentity )
*pIdentity = m_identity;
return !m_identity.IsInvalid();
}
int CSteamNetworkingSockets::GetSecondsUntilCertExpiry() const
{
if ( !m_msgSignedCert.has_cert() )
return INT_MIN;
Assert( m_msgSignedCert.has_ca_signature() ); // Connections may use unsigned certs in certain situations, but we never use them here
Assert( m_msgCert.has_key_data() );
Assert( m_msgCert.has_time_expiry() ); // We should never generate keys without an expiry!
int nSeconduntilExpiry = (long)m_msgCert.time_expiry() - (long)m_pSteamNetworkingUtils->GetTimeSecure();
return nSeconduntilExpiry;
}
bool CSteamNetworkingSockets::GetCertificateRequest( int *pcbBlob, void *pBlob, SteamNetworkingErrMsg &errMsg )
{
SteamNetworkingGlobalLock scopeLock( "GetCertificateRequest" );
// If we don't have a private key, generate one now.
CECSigningPublicKey pubKey;
if ( m_keyPrivateKey.IsValid() )
{
DbgVerify( m_keyPrivateKey.GetPublicKey( &pubKey ) );
}
else
{
CCrypto::GenerateSigningKeyPair( &pubKey, &m_keyPrivateKey );
}
// Fill out the request
CMsgSteamDatagramCertificateRequest msgRequest;
CMsgSteamDatagramCertificate &msgCert =*msgRequest.mutable_cert();
// Our public key
msgCert.set_key_type( CMsgSteamDatagramCertificate_EKeyType_ED25519 );
DbgVerify( pubKey.GetRawDataAsStdString( msgCert.mutable_key_data() ) );
// Our identity, if we know it
InternalGetIdentity();
if ( !m_identity.IsInvalid() && !m_identity.IsLocalHost() )
{
SteamNetworkingIdentityToProtobuf( m_identity, msgCert, identity_string, legacy_identity_binary, legacy_steam_id );
}
// Are we a hosted server running in a data center?
// Then cert should be restricted to that PoP
SteamNetworkingPOPID popid = GetHostedDedicatedServerPOPID();
if ( popid )
msgCert.add_gameserver_datacenter_ids( popid );
// Check size
int cb = ProtoMsgByteSize( msgRequest );
if ( !pBlob )
{
*pcbBlob = cb;
return true;
}
if ( cb > *pcbBlob )
{
*pcbBlob = cb;
V_sprintf_safe( errMsg, "%d byte buffer not big enough; %d bytes required", *pcbBlob, cb );
return false;
}
*pcbBlob = cb;
uint8 *p = (uint8 *)pBlob;
DbgVerify( msgRequest.SerializeWithCachedSizesToArray( p ) == p + cb );
return true;
}
bool CSteamNetworkingSockets::SetCertificate( const void *pCertificate, int cbCertificate, SteamNetworkingErrMsg &errMsg )
{
SteamNetworkingGlobalLock scopeLock( "SetCertificate" );
int nIdentitySetFlags = 0; // Allowing any reading/writing to the durable cache as appropriate
return InternalSetCertificate( pCertificate, cbCertificate, errMsg, nIdentitySetFlags );
}
bool CSteamNetworkingSockets::InternalSetCertificate( const void *pCertificate, int cbCertificate, SteamNetworkingErrMsg &errMsg, int nIdentitySetFlags )
{
SteamNetworkingGlobalLock::AssertHeldByCurrentThread( "InternalSetCertificate" );
// Crack the blob
CMsgSteamDatagramCertificateSigned msgCertSigned;
if ( !msgCertSigned.ParseFromArray( pCertificate, cbCertificate ) )
{
V_strcpy_safe( errMsg, "CMsgSteamDatagramCertificateSigned failed protobuf parse" );
return false;
}
// Crack the cert, and check the signature. If *we* aren't even willing
// to trust it, assume that our peers won't either
CMsgSteamDatagramCertificate msgCert;
time_t authTime = m_pSteamNetworkingUtils->GetTimeSecure();
const CertAuthScope *pAuthScope = CertStore_CheckCert( msgCertSigned, msgCert, authTime, errMsg );
if ( !pAuthScope )
{
SpewWarning( "SetCertificate: We are not currently able to verify our own cert! %s. Continuing anyway!", errMsg );
}
// Extract the identity from the cert
SteamNetworkingErrMsg tempErrMsg;
SteamNetworkingIdentity certIdentity;
int r = SteamNetworkingIdentityFromCert( certIdentity, msgCert, tempErrMsg );
if ( r < 0 )
{
V_sprintf_safe( errMsg, "Cert has invalid identity. %s", tempErrMsg );
return false;
}
// If we already have an identity, it must match the cert
bool bSetIdentity = false;
if ( m_identity.IsInvalid() || m_identity.IsLocalHost() )
{
bSetIdentity = true;
}
else if ( !( m_identity == certIdentity ) )
{
V_sprintf_safe( errMsg, "Cert is for identity '%s'. We are '%s'", SteamNetworkingIdentityRender( certIdentity ).c_str(), SteamNetworkingIdentityRender( m_identity ).c_str() );
return false;
}
// We currently only support one key type
if ( msgCert.key_type() != CMsgSteamDatagramCertificate_EKeyType_ED25519 || msgCert.key_data().size() != 32 )
{
V_strcpy_safe( errMsg, "Cert has invalid public key" );
return false;
}
// FIXME - should we check if we already have a newer, equivalent cert?
// Does cert contain a private key?
if ( msgCertSigned.has_private_key_data() )
{
// The degree to which the key is actually "private" is not
// really known to us. However there are some use cases where
// we will accept a cert
const std::string &private_key_data = msgCertSigned.private_key_data();
if ( m_keyPrivateKey.IsValid() )
{
// We already chose a private key, so the cert must match.
// For the most common use cases, we choose a private
// key and it never leaves the current process.
if ( !m_keyPrivateKey.BMatchesRawData( private_key_data.data(), private_key_data.length() ) )
{
V_strcpy_safe( errMsg, "Private key mismatch" );
return false;
}
}
else
{
// We haven't chosen a private key yet, so we'll accept this one.
if ( !m_keyPrivateKey.SetRawDataFromStdString( private_key_data ) )
{
V_strcpy_safe( errMsg, "Invalid private key" );
return false;
}
}
}
else if ( !m_keyPrivateKey.IsValid() )
{
// WAT
V_strcpy_safe( errMsg, "Cannot set cert. No private key?" );
return false;
}
// Make sure the cert actually matches our public key.
if ( memcmp( msgCert.key_data().c_str(), m_keyPrivateKey.GetPublicKeyRawData(), 32 ) != 0 )
{
V_strcpy_safe( errMsg, "Cert public key does not match our private key" );
return false;
}
// Make sure the cert authorizes us for the App we think we are running
AppId_t nAppID = m_pSteamNetworkingUtils->GetAppID();
if ( !CheckCertAppID( msgCert, pAuthScope, nAppID, tempErrMsg ) )
{
V_sprintf_safe( errMsg, "Cert does not authorize us for App %u", nAppID );
return false;
}
// If we don't know our identity, then set it now. Otherwise,
// it better match.
if ( bSetIdentity )
{
m_identity = certIdentity;
SpewMsg( "Local identity established from certificate. We are '%s'\n", SteamNetworkingIdentityRender( m_identity ).c_str() );
}
// Save it off
m_msgSignedCert = std::move( msgCertSigned );
m_msgCert = std::move( msgCert );
// If shouldn't already be expired.
AssertMsg( GetSecondsUntilCertExpiry() > 0, "Cert already invalid / expired?" );
// If we just got our identity, let derived classes take action. But our caller is
// setting a specific cert, so don't try to load any other cert from the cache
if ( bSetIdentity )
InternalOnGotIdentity( nIdentitySetFlags | k_nIdentitySetFlag_NoLoadCert );
// We've got a valid cert
SetCertStatus( k_ESteamNetworkingAvailability_Current, "OK" );
// Make sure we have everything else we need to do authentication.
// This will also make sure we have renewal scheduled
AuthenticationNeeded();
// OK
return true;
}
void CSteamNetworkingSockets::ResetIdentity( const SteamNetworkingIdentity *pIdentity )
{
SteamNetworkingGlobalLock scopeLock( "ResetIdentity" );
KillConnections();
InternalClearIdentity();
if ( pIdentity )
{
m_identity = *pIdentity;
if ( !m_identity.IsInvalid() && !m_identity.IsLocalHost() )
{
int nIdentitySetFlags = k_nIdentitySetFlag_NoSave; // Allow us to check the durable cache for any credentials, but we know we are empty, so don't save anything
InternalOnGotIdentity( nIdentitySetFlags );
}
}
}
ESteamNetworkingAvailability CSteamNetworkingSockets::InitAuthentication()
{
SteamNetworkingGlobalLock scopeLock( "InitAuthentication" );
// Check/fetch prerequisites
AuthenticationNeeded();
// Return status
return m_AuthenticationStatus.m_eAvail;
}
void CSteamNetworkingSockets::CheckAuthenticationPrerequisites( SteamNetworkingMicroseconds usecNow )
{
#ifdef STEAMNETWORKINGSOCKETS_CAN_REQUEST_CERT
SteamNetworkingGlobalLock::AssertHeldByCurrentThread();
if ( !BCanRequestCert() )
return;
// Check if we're in flight already.
bool bInFlight = BCertRequestInFlight();
// Do we already have a cert?
if ( m_msgSignedCert.has_cert() )
{
//Assert( m_CertStatus.m_eAvail == k_ESteamNetworkingAvailability_Current );
// How much more life does it have in it?
int nSeconduntilExpiry = GetSecondsUntilCertExpiry();
if ( nSeconduntilExpiry < 0 )
{
// It's already expired, we might as well discard it now.
SpewMsg( "Cert expired %d seconds ago. Discarding and requesting another\n", -nSeconduntilExpiry );
m_msgSignedCert.Clear();
m_msgCert.Clear();
m_keyPrivateKey.Wipe();
// Update cert status
SetCertStatus( k_ESteamNetworkingAvailability_Previously, "Expired" );
}
else
{
// If request is already active, don't do any of the work below, and don't spam while we wait, since this function may be called frequently.
if ( bInFlight )
return;
// Check if it's time to renew
int nSecondsUntilRenew = nSeconduntilExpiry - k_nSecCertExpirySeekRenew;
if ( nSecondsUntilRenew > 0 )
{
// Schedule a wakeup
constexpr SteamNetworkingMicroseconds kFudge = k_nMillion*3/2;
SteamNetworkingMicroseconds usecTargetCheck = std::min( usecNow + nSecondsUntilRenew*k_nMillion + kFudge, usecNow + 600*k_nMillion );
SteamNetworkingMicroseconds usecScheduledCheck = m_scheduleCheckRenewCert.GetScheduleTime();
if ( usecScheduledCheck <= usecTargetCheck + kFudge*2 )
{
// Currently scheduled time is good enough. Don't constantly update the schedule time,
// that involves a (small amount) of work. Just wait for it
}
else
{
// Schedule a check later
m_scheduleCheckRenewCert.Schedule( usecTargetCheck );
// !TEST! Spew cert expiry
long long expiry = m_msgCert.time_expiry(); Assert( expiry > 0 );
long long now = m_pSteamNetworkingUtils->GetTimeSecure();
long long nSecondsUntilExpiry = expiry - now;
SpewMsg( "Certificate expires in %lldh%02lldm at %lld (current time %lld), will renew in %dh%02dm\n",
nSecondsUntilExpiry/3600, ( nSecondsUntilExpiry/60 ) % 60, expiry, now,
nSecondsUntilRenew/3600, (nSecondsUntilRenew/60)%60 );
}
return;
}
// Currently valid, but it's time to renew. Spew about this.
SpewMsg( "Cert expires in %d seconds. Requesting another, but keeping current cert in case request fails\n", nSeconduntilExpiry );
}
}
// If a request is already active, then we just need to wait for it to complete
if ( bInFlight )
return;
// Invoke platform code to begin fetching a cert
BeginFetchCertAsync();
#endif
}
void CSteamNetworkingSockets::SetCertStatus( ESteamNetworkingAvailability eAvail, const char *pszFmt, ... )
{
char msg[ sizeof(m_CertStatus.m_debugMsg) ];
va_list ap;
va_start( ap, pszFmt );
V_vsprintf_safe( msg, pszFmt, ap );
va_end( ap );
// Mark success or an attempt
if ( eAvail == k_ESteamNetworkingAvailability_Current )
m_bEverGotCert = true;
if ( eAvail == k_ESteamNetworkingAvailability_Attempting || eAvail == k_ESteamNetworkingAvailability_Retrying )
m_bEverTriedToGetCert = true;
// If we failed, but we previously succeeded, convert to "previously"
if ( eAvail == k_ESteamNetworkingAvailability_Failed && m_bEverGotCert )
eAvail = k_ESteamNetworkingAvailability_Previously;
// No change?
if ( m_CertStatus.m_eAvail == eAvail && V_stricmp( m_CertStatus.m_debugMsg, msg ) == 0 )
return;
// Update
m_CertStatus.m_eAvail = eAvail;
V_strcpy_safe( m_CertStatus.m_debugMsg, msg );
// Check if our high level authentication status changed
DeduceAuthenticationStatus();
}
void CSteamNetworkingSockets::DeduceAuthenticationStatus()
{
// For the base class, the overall authentication status is identical to the status of
// our cert. (Derived classes may add additional criteria)
SetAuthenticationStatus( m_CertStatus );
}
void CSteamNetworkingSockets::SetAuthenticationStatus( const SteamNetAuthenticationStatus_t &newStatus )
{
SteamNetworkingGlobalLock::AssertHeldByCurrentThread();
// No change?
bool bStatusChanged = newStatus.m_eAvail != m_AuthenticationStatus.m_eAvail;
if ( !bStatusChanged && V_strcmp( m_AuthenticationStatus.m_debugMsg, newStatus.m_debugMsg ) == 0 )
return;
// Update
m_AuthenticationStatus = newStatus;
// Re-cache identity
InternalGetIdentity();
// Post a callback, but only if the high level status changed. Don't post a callback just
// because the message changed
if ( bStatusChanged )
{
// Spew
SpewMsg( "AuthStatus (%s): %s (%s)",
SteamNetworkingIdentityRender( m_identity ).c_str(),
GetAvailabilityString( m_AuthenticationStatus.m_eAvail ), m_AuthenticationStatus.m_debugMsg );
QueueCallback( m_AuthenticationStatus, g_Config_Callback_AuthStatusChanged.Get() );
}
}
#ifdef STEAMNETWORKINGSOCKETS_CAN_REQUEST_CERT