-
Notifications
You must be signed in to change notification settings - Fork 628
/
steamnetworkingsockets_lowlevel.cpp
2532 lines (2139 loc) · 80.3 KB
/
steamnetworkingsockets_lowlevel.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. ====================
#if defined( _MSC_VER ) && ( _MSC_VER <= 1800 )
#pragma warning( disable: 4244 )
// 1>C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\chrono(749): warning C4244: '=' : conversion from '__int64' to 'time_t', possible loss of data (steamnetworkingsockets_lowlevel.cpp)
#endif
#ifdef __GNUC__
// src/public/tier0/basetypes.h:104:30: 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
#include <thread>
#include <mutex>
#include <atomic>
#ifdef POSIX
#include <pthread.h>
#include <sched.h>
#endif
#include "steamnetworkingsockets_lowlevel.h"
#include "../steamnetworkingsockets_platform.h"
#include "../steamnetworkingsockets_internal.h"
#include "../steamnetworkingsockets_thinker.h"
#include "steamnetworkingsockets_connections.h"
#include <vstdlib/random.h>
#include <tier1/utlpriorityqueue.h>
#include <tier1/utllinkedlist.h>
#include "crypto.h"
#include <tier0/memdbgoff.h>
// Ugggggggggg MSVC VS2013 STL bug: try_lock_for doesn't actually respect the timeout, it always ends up using an infinite timeout.
// And even in 2015, the code is calling the timer to get current time, to convert a relative time to an absolute time, and then
// waiting until that absolute time, which then calls the timer again....and subtracts it back off....It's really bad. Just go
// directly to the underlying Win32 primitives. Looks like the Visual Studio 2017 STL implementation is sane, though.
#if defined(_MSC_VER) && _MSC_VER < 1914
// NOTE - we could implement our own mutex here.
#error "std::recursive_timed_mutex doesn't work"
#endif
#ifdef _XBOX_ONE
#include <combaseapi.h>
#endif
// Time low level send/recv calls and packet processing
//#define STEAMNETWORKINGSOCKETS_LOWLEVEL_TIME_SOCKET_CALLS
#include <tier0/memdbgon.h>
namespace SteamNetworkingSocketsLib {
int g_nSteamDatagramSocketBufferSize = 256*1024;
/// Global lock for all local data structures
static Lock<RecursiveTimedMutexImpl> s_mutexGlobalLock( "global", 0 );
#if STEAMNETWORKINGSOCKETS_LOCK_DEBUG_LEVEL > 0
// By default, complain if we hold the lock for more than this long
constexpr SteamNetworkingMicroseconds k_usecDefaultLongLockHeldWarningThreshold = 5*1000;
// Debug the locks active on the cu
struct ThreadLockDebugInfo
{
static constexpr int k_nMaxHeldLocks = 8;
static constexpr int k_nMaxTags = 32;
int m_nHeldLocks = 0;
int m_nTags = 0;
SteamNetworkingMicroseconds m_usecLongLockWarningThreshold;
SteamNetworkingMicroseconds m_usecIgnoreLongLockWaitTimeUntil;
SteamNetworkingMicroseconds m_usecOuterLockStartTime; // Time when we started waiting on outermost lock (if we don't have it yet), or when we aquired the lock (if we have it)
const LockDebugInfo *m_arHeldLocks[ k_nMaxHeldLocks ];
struct Tag_t
{
const char *m_pszTag;
int m_nCount;
};
Tag_t m_arTags[ k_nMaxTags ];
};
static void (*s_fLockAcquiredCallback)( const char *tags, SteamNetworkingMicroseconds usecWaited );
static void (*s_fLockHeldCallback)( const char *tags, SteamNetworkingMicroseconds usecWaited );
static SteamNetworkingMicroseconds s_usecLockWaitWarningThreshold = 2*1000;
/// Get the per-thread debug info
static ThreadLockDebugInfo &GetThreadDebugInfo()
{
// Apple seems to hate thread_local. Is there some sort of feature
// define a can check here? It's a shame because it's really very
// efficient on MSVC, gcc, and clang on Windows and linux.
//
// Apple seems to support thread_local starting with Xcode 8.0
#if defined(__APPLE__) && __clang_major__ < 8
static pthread_key_t key;
static pthread_once_t key_once = PTHREAD_ONCE_INIT;
// One time init the TLS key
pthread_once( &key_once,
[](){ // Initialization code to run once
pthread_key_create(
&key,
[](void *ptr) { free(ptr); } // Destructor function
);
}
);
// Get current object
void *result = pthread_getspecific(key);
if ( unlikely( result == nullptr ) )
{
result = malloc( sizeof(ThreadLockDebugInfo) );
memset( result, 0, sizeof(ThreadLockDebugInfo) );
pthread_setspecific(key, result);
}
return *static_cast<ThreadLockDebugInfo *>( result );
#else
// Use thread_local
thread_local ThreadLockDebugInfo tls_lockDebugInfo;
return tls_lockDebugInfo;
#endif
}
/// If non-NULL, add a "tag" to the lock journal for the current thread.
/// This is useful so that if we hold a lock for a long time, we can get
/// an idea what sorts of operations were taking a long time.
static void AddThreadLockTag( const char *pszTag )
{
if ( !pszTag )
return;
ThreadLockDebugInfo &t = GetThreadDebugInfo();
Assert( t.m_nHeldLocks > 0 ); // Can't add a tag unless we are locked!
for ( int i = 0 ; i < t.m_nTags ; ++i )
{
if ( t.m_arTags[i].m_pszTag == pszTag )
{
++t.m_arTags[i].m_nCount;
return;
}
}
if ( t.m_nTags >= ThreadLockDebugInfo::k_nMaxTags )
return;
t.m_arTags[ t.m_nTags ].m_pszTag = pszTag;
t.m_arTags[ t.m_nTags ].m_nCount = 1;
++t.m_nTags;
}
LockDebugInfo::~LockDebugInfo()
{
// We should not be locked! If we are, remove us
ThreadLockDebugInfo &t = GetThreadDebugInfo();
for ( int i = t.m_nHeldLocks-1 ; i >= 0 ; --i )
{
if ( t.m_arHeldLocks[i] == this )
{
AssertMsg( false, "Lock '%s' being destroyed while it is held!", m_pszName );
AboutToUnlock();
}
}
}
void LockDebugInfo::AboutToLock( bool bTry )
{
ThreadLockDebugInfo &t = GetThreadDebugInfo();
// First lock held by this thread?
if ( t.m_nHeldLocks == 0 )
{
// Remember when we started trying to lock
t.m_usecOuterLockStartTime = SteamNetworkingSockets_GetLocalTimestamp();
}
else
{
// We already hold a lock. Make sure it's legal for us to take another!
// Global lock *must* always be the outermost lock. (It is legal to take other locks in
// between and then lock the global lock recursively.)
const bool bHoldGlobalLock = t.m_arHeldLocks[ 0 ] == &s_mutexGlobalLock;
AssertMsg(
bHoldGlobalLock || this != &s_mutexGlobalLock,
"Taking global lock while already holding lock '%s'", t.m_arHeldLocks[ 0 ]->m_pszName
);
// Check for taking locks in such a way that might lead to deadlocks.
// If they are only "trying", then we do allow out of order behaviour.
if ( !bTry )
{
const LockDebugInfo *pTopLock = t.m_arHeldLocks[ t.m_nHeldLocks-1 ];
// Once we take a "short duration" lock, we must not
// take any additional locks! (Including a recursive lock.)
AssertMsg( !( pTopLock->m_nFlags & LockDebugInfo::k_nFlag_ShortDuration ), "Taking lock '%s' while already holding lock '%s'", m_pszName, pTopLock->m_pszName );
// If the global lock isn't held, then no more than one
// object lock is allowed, since two different threads
// might take them in different order.
constexpr int k_nObjectFlags = LockDebugInfo::k_nFlag_Connection | LockDebugInfo::k_nFlag_PollGroup;
if (
( !bHoldGlobalLock && ( m_nFlags & k_nObjectFlags ) != 0 )
//|| ( m_nFlags & k_nFlag_Table ) // We actually do this in one place when we know it's OK. Not wirth it right now to get this situation exempted from the checking.
) {
// We must not already hold any existing object locks (except perhaps this one)
for ( int i = 0 ; i < t.m_nHeldLocks ; ++i )
{
const LockDebugInfo *pOtherLock = t.m_arHeldLocks[ i ];
AssertMsg( pOtherLock == this || !( pOtherLock->m_nFlags & k_nObjectFlags ),
"Taking lock '%s' and then '%s', while not holding the global lock", pOtherLock->m_pszName, m_pszName );
}
}
}
}
}
void LockDebugInfo::OnLocked( const char *pszTag )
{
ThreadLockDebugInfo &t = GetThreadDebugInfo();
Assert( t.m_nHeldLocks < ThreadLockDebugInfo::k_nMaxHeldLocks );
t.m_arHeldLocks[ t.m_nHeldLocks++ ] = this;
if ( t.m_nHeldLocks == 1 )
{
SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp();
SteamNetworkingMicroseconds usecTimeSpentWaitingOnLock = usecNow - t.m_usecOuterLockStartTime;
t.m_usecLongLockWarningThreshold = k_usecDefaultLongLockHeldWarningThreshold;
t.m_nTags = 0;
if ( usecTimeSpentWaitingOnLock > s_usecLockWaitWarningThreshold && usecNow > t.m_usecIgnoreLongLockWaitTimeUntil )
{
if ( pszTag )
SpewWarning( "Waited %.1fms for SteamNetworkingSockets lock [%s]", usecTimeSpentWaitingOnLock*1e-3, pszTag );
else
SpewWarning( "Waited %.1fms for SteamNetworkingSockets lock", usecTimeSpentWaitingOnLock*1e-3 );
ETW_LongOp( "lock wait", usecTimeSpentWaitingOnLock, pszTag );
}
auto callback = s_fLockAcquiredCallback; // save to temp, to prevent very narrow race condition where variable is cleared after we null check it, and we call null
if ( callback )
callback( pszTag, usecTimeSpentWaitingOnLock );
t.m_usecOuterLockStartTime = usecNow;
}
AddThreadLockTag( pszTag );
}
void LockDebugInfo::AboutToUnlock()
{
char tags[ 256 ];
SteamNetworkingMicroseconds usecElapsed = 0;
SteamNetworkingMicroseconds usecElapsedTooLong = 0;
auto lockHeldCallback = s_fLockHeldCallback;
ThreadLockDebugInfo &t = GetThreadDebugInfo();
Assert( t.m_nHeldLocks > 0 );
// Unlocking the last lock?
if ( t.m_nHeldLocks == 1 )
{
// We're about to do the final release. How long did we hold the lock?
usecElapsed = SteamNetworkingSockets_GetLocalTimestamp() - t.m_usecOuterLockStartTime;
// Too long? We need to check the threshold here because the threshold could
// change by another thread immediately after we release the lock. Also, if
// we're debugging, all bets are off. They could have hit a breakpoint, and
// we don't want to create a bunch of confusing spew with spurious asserts
if ( usecElapsed >= t.m_usecLongLockWarningThreshold && !Plat_IsInDebugSession() )
{
usecElapsedTooLong = usecElapsed;
}
if ( usecElapsedTooLong > 0 || lockHeldCallback )
{
char *p = tags;
char *end = tags + sizeof(tags) - 1;
for ( int i = 0 ; i < t.m_nTags && p+5 < end ; ++i )
{
if ( p > tags )
*(p++) = ',';
const ThreadLockDebugInfo::Tag_t &tag = t.m_arTags[i];
int taglen = std::min( int(end-p), (int)V_strlen( tag.m_pszTag ) );
memcpy( p, tag.m_pszTag, taglen );
p += taglen;
if ( tag.m_nCount > 1 )
{
int l = end-p;
if ( l <= 5 )
break;
p += V_snprintf( p, l, "(x%d)", tag.m_nCount );
}
}
*p = '\0';
}
t.m_nTags = 0;
t.m_usecOuterLockStartTime = 0; // Just for grins.
}
if ( usecElapsed > 0 && lockHeldCallback )
{
lockHeldCallback(tags, usecElapsed);
}
// Yelp if we held the lock for longer than the threshold.
if ( usecElapsedTooLong != 0 )
{
SpewWarning( "SteamNetworkingSockets lock held for %.1fms. (Performance warning). %s", usecElapsedTooLong*1e-3, tags );
ETW_LongOp( "lock held", usecElapsedTooLong, tags );
}
// NOTE: We are allowed to unlock out of order! We specifically
// do this with the table lock!
for ( int i = t.m_nHeldLocks-1 ; i >= 0 ; --i )
{
if ( t.m_arHeldLocks[i] == this )
{
--t.m_nHeldLocks;
if ( i < t.m_nHeldLocks ) // Don't do the memmove in the common case of stack pop
memmove( &t.m_arHeldLocks[i], &t.m_arHeldLocks[i+1], (t.m_nHeldLocks-i) * sizeof(t.m_arHeldLocks[0]) );
t.m_arHeldLocks[t.m_nHeldLocks] = nullptr; // Just for grins
return;
}
}
AssertMsg( false, "Unlocked a lock '%s' that wasn't held?", m_pszName );
}
void LockDebugInfo::_AssertHeldByCurrentThread( const char *pszFile, int line, const char *pszTag ) const
{
ThreadLockDebugInfo &t = GetThreadDebugInfo();
for ( int i = t.m_nHeldLocks-1 ; i >= 0 ; --i )
{
if ( t.m_arHeldLocks[i] == this )
{
AddThreadLockTag( pszTag );
return;
}
}
AssertMsg( false, "%s(%d): Lock '%s' not held", pszFile, line, m_pszName );
}
void SteamNetworkingGlobalLock::SetLongLockWarningThresholdMS( const char *pszTag, int msWarningThreshold )
{
AssertHeldByCurrentThread( pszTag );
SteamNetworkingMicroseconds usecWarningThreshold = SteamNetworkingMicroseconds{msWarningThreshold}*1000;
ThreadLockDebugInfo &t = GetThreadDebugInfo();
if ( t.m_usecLongLockWarningThreshold < usecWarningThreshold )
{
t.m_usecLongLockWarningThreshold = usecWarningThreshold;
t.m_usecIgnoreLongLockWaitTimeUntil = SteamNetworkingSockets_GetLocalTimestamp() + t.m_usecLongLockWarningThreshold;
}
}
void SteamNetworkingGlobalLock::_AssertHeldByCurrentThread( const char *pszFile, int line )
{
s_mutexGlobalLock._AssertHeldByCurrentThread( pszFile, line );
}
void SteamNetworkingGlobalLock::_AssertHeldByCurrentThread( const char *pszFile, int line, const char *pszTag )
{
s_mutexGlobalLock._AssertHeldByCurrentThread( pszFile, line );
AddThreadLockTag( pszTag );
}
#endif // #if STEAMNETWORKINGSOCKETS_LOCK_DEBUG_LEVEL > 0
void SteamNetworkingGlobalLock::Lock( const char *pszTag )
{
s_mutexGlobalLock.lock( pszTag );
}
bool SteamNetworkingGlobalLock::TryLock( const char *pszTag, int msTimeout )
{
return s_mutexGlobalLock.try_lock_for( msTimeout, pszTag );
}
void SteamNetworkingGlobalLock::Unlock()
{
s_mutexGlobalLock.unlock();
}
static void SeedWeakRandomGenerator()
{
// Seed cheesy random number generator using true source of entropy
int temp;
CCrypto::GenerateRandomBlock( &temp, sizeof(temp) );
WeakRandomSeed( temp );
}
static std::atomic<long long> s_usecTimeLastReturned;
// Start with an offset so that a timestamp of zero is always pretty far in the past.
// But round it up to nice round number, so that looking at timestamps in the debugger
// is easy to read.
const long long k_nInitialTimestampMin = k_nMillion*24*3600*30;
const long long k_nInitialTimestamp = 3000000000000ll;
COMPILE_TIME_ASSERT( 2000000000000ll < k_nInitialTimestampMin );
COMPILE_TIME_ASSERT( k_nInitialTimestampMin < k_nInitialTimestamp );
static std::atomic<long long> s_usecTimeOffset( k_nInitialTimestamp );
static std::atomic<int> s_nLowLevelSupportRefCount(0);
static volatile bool s_bManualPollMode;
/////////////////////////////////////////////////////////////////////////////
//
// Raw sockets
//
/////////////////////////////////////////////////////////////////////////////
// We don't need recursion or timeout. Just the fastest thing that works.
// Note that we could use a lock-free queue for this. But I suspect that this
// won't get enough work or have enough contention for that to be an important
// optimization
static ShortDurationLock s_mutexRunWithLockQueue( "run_with_lock_queue" );
static std::vector< ISteamNetworkingSocketsRunWithLock * > s_vecRunWithLockQueue;
ISteamNetworkingSocketsRunWithLock::~ISteamNetworkingSocketsRunWithLock() {}
bool ISteamNetworkingSocketsRunWithLock::RunOrQueue( const char *pszTag )
{
// Check if lock is available immediately
if ( !SteamNetworkingGlobalLock::TryLock( pszTag, 0 ) )
{
Queue( pszTag );
return false;
}
// Service the queue so we always do items in order
ServiceQueue();
// Let derived class do work
Run();
// Go ahead and unlock now
SteamNetworkingGlobalLock::Unlock();
// Self destruct
delete this;
// We have run
return true;
}
void ISteamNetworkingSocketsRunWithLock::Queue( const char *pszTag )
{
// Remember our tag, for accounting purposes
m_pszTag = pszTag;
// Put us into the queue
s_mutexRunWithLockQueue.lock();
s_vecRunWithLockQueue.push_back( this );
s_mutexRunWithLockQueue.unlock();
// NOTE: At this point we are subject to being run or deleted at any time!
// Make sure service thread will wake up to do something with this
WakeSteamDatagramThread();
}
void ISteamNetworkingSocketsRunWithLock::ServiceQueue()
{
// Quick check if we're empty, which will be common and can be done safely
// even if we don't hold the lock and the vector is being modified. It's
// OK if we have an occasional false positive or negative here. Work
// put into this queue does not have any guarantees about when it will get done
// beyond "run them in order they are queued" and "best effort".
if ( s_vecRunWithLockQueue.empty() )
return;
std::vector<ISteamNetworkingSocketsRunWithLock *> vecTempQueue;
// Quickly move the queue into the temp while holding the lock.
// Once it is in our temp, we can release the lock.
s_mutexRunWithLockQueue.lock();
vecTempQueue = std::move( s_vecRunWithLockQueue );
s_vecRunWithLockQueue.clear(); // Just in case assigning from std::move didn't clear it.
s_mutexRunWithLockQueue.unlock();
// Run them
for ( ISteamNetworkingSocketsRunWithLock *pItem: vecTempQueue )
{
// Make sure we hold the lock, and also set the tag for debugging purposes
SteamNetworkingGlobalLock::AssertHeldByCurrentThread( pItem->m_pszTag );
// Do the work and nuke
pItem->Run();
delete pItem;
}
}
// Try to guess if the route the specified address is probably "local".
// This is difficult to do in general. We want something that mostly works.
//
// False positives: VPNs and IPv6 addresses that appear to be nearby but are not.
// False negatives: We can't always tell if a route is local.
bool IsRouteToAddressProbablyLocal( netadr_t addr )
{
// Assume that if we are able to send to any "reserved" route, that is is local.
// Note that this will be true for VPNs, too!
if ( addr.IsReservedAdr() )
return true;
// But other cases might also be local routes. E.g. two boxes with public IPs.
// Convert to sockaddr struct so we can ask the operating system
addr.SetPort(0);
sockaddr_storage sockaddrDest;
addr.ToSockadr( &sockaddrDest );
#ifdef _WINDOWS
//
// These functions were added with Vista, so load dynamically
// in case
//
typedef
DWORD
(WINAPI *FnGetBestInterfaceEx)(
struct sockaddr *pDestAddr,
PDWORD pdwBestIfIndex
);
typedef
NETIO_STATUS
(NETIOAPI_API_*FnGetBestRoute2)(
NET_LUID *InterfaceLuid,
NET_IFINDEX InterfaceIndex,
CONST SOCKADDR_INET *SourceAddress,
CONST SOCKADDR_INET *DestinationAddress,
ULONG AddressSortOptions,
PMIB_IPFORWARD_ROW2 BestRoute,
SOCKADDR_INET *BestSourceAddress
);
static HMODULE hModule = LoadLibraryA( "Iphlpapi.dll" );
static FnGetBestInterfaceEx pGetBestInterfaceEx = hModule ? (FnGetBestInterfaceEx)GetProcAddress( hModule, "GetBestInterfaceEx" ) : nullptr;
static FnGetBestRoute2 pGetBestRoute2 = hModule ? (FnGetBestRoute2)GetProcAddress( hModule, "GetBestRoute2" ) : nullptr;;
if ( !pGetBestInterfaceEx || !pGetBestRoute2 )
return false;
NET_IFINDEX dwBestIfIndex;
DWORD r = (*pGetBestInterfaceEx)( (sockaddr *)&sockaddrDest, &dwBestIfIndex );
if ( r != NO_ERROR )
{
AssertMsg2( false, "GetBestInterfaceEx failed with result %d for address '%s'", r, CUtlNetAdrRender( addr ).String() );
return false;
}
MIB_IPFORWARD_ROW2 bestRoute;
SOCKADDR_INET bestSourceAddress;
r = (*pGetBestRoute2)(
nullptr, // InterfaceLuid
dwBestIfIndex, // InterfaceIndex
nullptr, // SourceAddress
(SOCKADDR_INET *)&sockaddrDest, // DestinationAddress
0, // AddressSortOptions
&bestRoute, // BestRoute
&bestSourceAddress // BestSourceAddress
);
if ( r != NO_ERROR )
{
AssertMsg2( false, "GetBestRoute2 failed with result %d for address '%s'", r, CUtlNetAdrRender( addr ).String() );
return false;
}
if ( bestRoute.Protocol == MIB_IPPROTO_LOCAL )
return true;
netadr_t nextHop;
if ( !nextHop.SetFromSockadr( &bestRoute.NextHop ) )
{
AssertMsg( false, "GetBestRoute2 returned invalid next hop address" );
return false;
}
nextHop.SetPort( 0 );
// https://docs.microsoft.com/en-us/windows/win32/api/netioapi/ns-netioapi-mib_ipforward_row2:
// For a remote route, the IP address of the next system or gateway en route.
// If the route is to a local loopback address or an IP address on the local
// link, the next hop is unspecified (all zeros). For a local loopback route,
// this member should be an IPv4 address of 0.0.0.0 for an IPv4 route entry
// or an IPv6 address address of 0::0 for an IPv6 route entry.
if ( !nextHop.HasIP() )
return true;
if ( nextHop == addr )
return true;
// If final destination is on the same IPv6/56 prefix, then assume
// it's a local route. This is an arbitrary prefix size to use,
// but it's a compromise. We think that /64 probably has too
// many false negatives, but /48 has have too many false positives.
if ( addr.GetType() == k_EIPTypeV6 )
{
if ( nextHop.GetType() == k_EIPTypeV6 )
{
if ( memcmp( addr.GetIPV6Bytes(), nextHop.GetIPV6Bytes(), 7 ) == 0 )
return true;
}
netadr_t netdrBestSource;
if ( netdrBestSource.SetFromSockadr( &bestSourceAddress ) && netdrBestSource.GetType() == k_EIPTypeV6 )
{
if ( memcmp( addr.GetIPV6Bytes(), netdrBestSource.GetIPV6Bytes(), 7 ) == 0 )
return true;
}
}
#else
// FIXME - Writeme
#endif
// Nope
return false;
}
/////////////////////////////////////////////////////////////////////////////
//
// Raw sockets
//
/////////////////////////////////////////////////////////////////////////////
inline IRawUDPSocket::IRawUDPSocket() {}
inline IRawUDPSocket::~IRawUDPSocket() {}
class CRawUDPSocketImpl final : public IRawUDPSocket
{
public:
STEAMNETWORKINGSOCKETS_DECLARE_CLASS_OPERATOR_NEW
~CRawUDPSocketImpl()
{
closesocket( m_socket );
#ifdef WIN32
WSACloseEvent( m_event );
#endif
}
/// Descriptor from the OS
SOCKET m_socket;
/// What address families are supported by this socket?
int m_nAddressFamilies;
/// Who to notify when we receive a packet on this socket.
/// This is set to null when we are asked to close the socket.
CRecvPacketCallback m_callback;
/// An event that will be set when the socket has data that we can read.
#ifdef WIN32
WSAEVENT m_event = INVALID_HANDLE_VALUE;
#endif
// Implements IRawUDPSocket
virtual bool BSendRawPacketGather( int nChunks, const iovec *pChunks, const netadr_t &adrTo ) const override;
virtual void Close() override;
//// Send a packet, for really realz right now. (No checking for fake loss or lag.)
inline bool BReallySendRawPacket( int nChunks, const iovec *pChunks, const netadr_t &adrTo ) const
{
Assert( m_socket != INVALID_SOCKET );
// Add a tag. If we end up holding the lock for a long time, this tag
// will tell us how many packets were sent
SteamNetworkingGlobalLock::AssertHeldByCurrentThread( "SendUDPacket" );
// Convert address to BSD interface
struct sockaddr_storage destAddress;
socklen_t addrSize;
if ( m_nAddressFamilies & k_nAddressFamily_IPv6 )
{
addrSize = sizeof(sockaddr_in6);
adrTo.ToSockadrIPV6( &destAddress );
}
else
{
addrSize = (socklen_t)adrTo.ToSockadr( &destAddress );
}
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_ETW
{
int cbTotal = 0;
for ( int i = 0 ; i < nChunks ; ++i )
cbTotal += (int)pChunks->iov_len;
ETW_UDPSendPacket( adrTo, cbTotal );
}
#endif
if ( g_Config_PacketTraceMaxBytes.Get() >= 0 )
{
TracePkt( true, adrTo, nChunks, pChunks );
}
#ifdef STEAMNETWORKINGSOCKETS_LOWLEVEL_TIME_SOCKET_CALLS
SteamNetworkingMicroseconds usecSendStart = SteamNetworkingSockets_GetLocalTimestamp();
#endif
#ifdef WIN32
// Confirm that iovec and WSABUF are indeed bitwise equivalent
COMPILE_TIME_ASSERT( sizeof( iovec ) == sizeof( WSABUF ) );
COMPILE_TIME_ASSERT( offsetof( iovec, iov_len ) == offsetof( WSABUF, len ) );
COMPILE_TIME_ASSERT( offsetof( iovec, iov_base ) == offsetof( WSABUF, buf ) );
DWORD numberOfBytesSent;
int r = WSASendTo(
m_socket,
(WSABUF *)pChunks,
(DWORD)nChunks,
&numberOfBytesSent,
0, // flags
(const sockaddr *)&destAddress,
addrSize,
nullptr, // lpOverlapped
nullptr // lpCompletionRoutine
);
bool bResult = ( r == 0 );
#else
msghdr msg;
msg.msg_name = (sockaddr *)&destAddress;
msg.msg_namelen = addrSize;
msg.msg_iov = const_cast<struct iovec *>( pChunks );
msg.msg_iovlen = nChunks;
msg.msg_control = nullptr;
msg.msg_controllen = 0;
msg.msg_flags = 0;
int r = ::sendmsg( m_socket, &msg, 0 );
bool bResult = ( r >= 0 ); // just check for -1 for error, since we don't want to take the time here to scan the iovec and sum up the expected total number of bytes sent
#endif
#ifdef STEAMNETWORKINGSOCKETS_LOWLEVEL_TIME_SOCKET_CALLS
SteamNetworkingMicroseconds usecSendEnd = SteamNetworkingSockets_GetLocalTimestamp();
if ( usecSendEnd > s_usecIgnoreLongLockWaitTimeUntil )
{
SteamNetworkingMicroseconds usecSendElapsed = usecSendEnd - usecSendStart;
if ( usecSendElapsed > 1000 )
{
SpewWarning( "UDP send took %.1fms\n", usecSendElapsed*1e-3 );
ETW_LongOp( "UDP send", usecSendElapsed );
}
}
#endif
return bResult;
}
void TracePkt( bool bSend, const netadr_t &adrRemote, int nChunks, const iovec *pChunks ) const
{
int cbTotal = 0;
for ( int i = 0 ; i < nChunks ; ++i )
cbTotal += pChunks[i].iov_len;
if ( bSend )
{
ReallySpewTypeFmt( k_ESteamNetworkingSocketsDebugOutputType_Msg, "[Trace Send] %s -> %s | %d bytes\n",
SteamNetworkingIPAddrRender( m_boundAddr ).c_str(), CUtlNetAdrRender( adrRemote ).String(), cbTotal );
}
else
{
ReallySpewTypeFmt( k_ESteamNetworkingSocketsDebugOutputType_Msg, "[Trace Recv] %s <- %s | %d bytes\n",
SteamNetworkingIPAddrRender( m_boundAddr ).c_str(), CUtlNetAdrRender( adrRemote ).String(), cbTotal );
}
int l = std::min( cbTotal, g_Config_PacketTraceMaxBytes.Get() );
const uint8 *p = (const uint8 *)pChunks->iov_base;
int cbChunkLeft = pChunks->iov_len;
while ( l > 0 )
{
// How many bytes to print on thie row?
int row = std::min( 16, l );
l -= row;
char buf[256], *d = buf;
do {
// Check for end of this chunk
while ( cbChunkLeft == 0 )
{
++pChunks;
p = (const uint8 *)pChunks->iov_base;
cbChunkLeft = pChunks->iov_len;
}
// print the byte
static const char hexdigit[] = "0123456789abcdef";
*(d++) = ' ';
*(d++) = hexdigit[ *p >> 4 ];
*(d++) = hexdigit[ *p & 0xf ];
// Advance to next byte
++p;
--cbChunkLeft;
} while (--row > 0 );
*d = '\0';
// Emit the row
ReallySpewTypeFmt( k_ESteamNetworkingSocketsDebugOutputType_Msg, " %s\n", buf );
}
}
private:
void InternalAddToCleanupQueue();
};
/// We don't expect to have enough sockets, and open and close them frequently
/// enough, such that an occasional linear search will kill us.
static CUtlVector<CRawUDPSocketImpl *> s_vecRawSockets;
/// List of raw sockets pending actual destruction.
static CUtlVector<CRawUDPSocketImpl *> s_vecRawSocketsPendingDeletion;
/// Track packets that have fake lag applied and are pending to be sent/received
class CPacketLagger : private IThinker
{
public:
~CPacketLagger() { Clear(); }
void LagPacket( bool bSend, CRawUDPSocketImpl *pSock, const netadr_t &adr, int msDelay, int nChunks, const iovec *pChunks )
{
SteamNetworkingGlobalLock::AssertHeldByCurrentThread( "LagPacket" );
int cbPkt = 0;
for ( int i = 0 ; i < nChunks ; ++i )
cbPkt += pChunks[i].iov_len;
if ( cbPkt > k_cbSteamNetworkingSocketsMaxUDPMsgLen )
{
AssertMsg( false, "Tried to lag a packet that w as too big!" );
return;
}
// Make sure we never queue a packet that is queued for destruction!
if ( pSock->m_socket == INVALID_SOCKET || !pSock->m_callback.m_fnCallback )
{
AssertMsg( false, "Tried to lag a packet on a socket that has already been closed and is pending destruction!" );
return;
}
if ( msDelay < 1 )
{
AssertMsg( false, "Packet lag time must be positive!" );
msDelay = 1;
}
// Limit to something sane
msDelay = std::min( msDelay, 5000 );
const SteamNetworkingMicroseconds usecTime = SteamNetworkingSockets_GetLocalTimestamp() + msDelay * 1000;
// Find the right place to insert the packet.
LaggedPacket *pkt = nullptr;
for ( CUtlLinkedList< LaggedPacket >::IndexType_t i = m_list.Head(); i != m_list.InvalidIndex(); i = m_list.Next( i ) )
{
if ( usecTime < m_list[ i ].m_usecTime )
{
pkt = &m_list[ m_list.InsertBefore( i ) ];
break;
}
}
if ( pkt == nullptr )
{
pkt = &m_list[ m_list.AddToTail() ];
}
pkt->m_bSend = bSend;
pkt->m_pSockOwner = pSock;
pkt->m_adrRemote = adr;
pkt->m_usecTime = usecTime;
pkt->m_cbPkt = cbPkt;
// Gather them into buffer
char *d = pkt->m_pkt;
for ( int i = 0 ; i < nChunks ; ++i )
{
int cbChunk = pChunks[i].iov_len;
memcpy( d, pChunks[i].iov_base, cbChunk );
d += cbChunk;
}
Schedule();
}
/// Periodic processing
virtual void Think( SteamNetworkingMicroseconds usecNow ) OVERRIDE
{
// Just always process packets in queue order. This means there could be some
// weird burst or jankiness if the delay time is changed, but that's OK.
while ( !m_list.IsEmpty() )
{
LaggedPacket &pkt = m_list[ m_list.Head() ];
if ( pkt.m_usecTime > usecNow )
break;
// Make sure socket is still in good shape.
CRawUDPSocketImpl *pSock = pkt.m_pSockOwner;
if ( pSock->m_socket == INVALID_SOCKET || !pSock->m_callback.m_fnCallback )
{
AssertMsg( false, "Lagged packet remains in queue after socket destroyed or queued for destruction!" );
}
else
{
// Sending, or receiving?
if ( pkt.m_bSend )
{
iovec temp;
temp.iov_len = pkt.m_cbPkt;
temp.iov_base = pkt.m_pkt;
pSock->BReallySendRawPacket( 1, &temp, pkt.m_adrRemote );
}
else
{
// Copy data out of queue into local variables, just in case a
// packet is queued while we're in this function. We don't want
// our list to shift in memory, and the pointer we pass to the
// caller to dangle.
char temp[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ];
memcpy( temp, pkt.m_pkt, pkt.m_cbPkt );
pSock->m_callback( RecvPktInfo_t{ temp, pkt.m_cbPkt, pkt.m_adrRemote, pSock } );
}
}
m_list.RemoveFromHead();
}
Schedule();
}
/// Nuke everything
void Clear()
{
m_list.RemoveAll();
IThinker::ClearNextThinkTime();
}
/// Called when we're about to destroy a socket
void AboutToDestroySocket( const CRawUDPSocketImpl *pSock )
{
// Just do a dumb linear search. This list should be empty in
// production situations, and socket destruction is relatively rare,
// so its not worth making this complicated.
int idx = m_list.Head();
while ( idx != m_list.InvalidIndex() )
{
int idxNext = m_list.Next( idx );
if ( m_list[idx].m_pSockOwner == pSock )
m_list.Remove( idx );
idx = idxNext;
}
Schedule();
}
private:
/// Set the next think time as appropriate
void Schedule()
{
if ( m_list.IsEmpty() )
ClearNextThinkTime();
else
SetNextThinkTime( m_list[ m_list.Head() ].m_usecTime );
}
struct LaggedPacket
{
bool m_bSend; // true for outbound, false for inbound
CRawUDPSocketImpl *m_pSockOwner;
netadr_t m_adrRemote;
SteamNetworkingMicroseconds m_usecTime; /// Time when it should be sent or received
int m_cbPkt;
char m_pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ];
};
CUtlLinkedList<LaggedPacket> m_list;
};
static CPacketLagger s_packetLagQueue;
/// Object used to wake our background thread efficiently
#if defined( _WIN32 )
static HANDLE s_hEventWakeThread = INVALID_HANDLE_VALUE;
#elif defined( NN_NINTENDO_SDK )
static int s_hEventWakeThread = INVALID_SOCKET;
#else
static SOCKET s_hSockWakeThreadRead = INVALID_SOCKET;
static SOCKET s_hSockWakeThreadWrite = INVALID_SOCKET;