-
Notifications
You must be signed in to change notification settings - Fork 725
Expand file tree
/
Copy pathsteamnetworkingsockets_socketthread.cpp
More file actions
4395 lines (3827 loc) · 140 KB
/
Copy pathsteamnetworkingsockets_socketthread.cpp
File metadata and controls
4395 lines (3827 loc) · 140 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. ====================
//
// Socket and service thread management for SteamNetworkingSockets.
//
// - Dealing with OS sockets, sending/receiving of UDP packets
// - Simulating network conditions such as fake lag/loss/reording/jitter
// - Managing the main service thread, polling efficiently
// - Dispatching received packets to the registered callbacks.
// - Support for wifi adapters that can send on both bands simultaneously
//
#include <thread>
#include <mutex>
#include <atomic>
#include "steamnetworkingsockets_lowlevel.h"
#include "steamnetworkingsockets_mock.h"
#include <tier0/platform_sockets.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/valve_tracelogging.h>
#if IsPosix()
#include <pthread.h>
#include <sched.h>
#include <sys/types.h>
#if !IsNintendoSwitch()
#include <sys/socket.h>
#endif
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_RESOLVEHOSTNAME
#include <netdb.h>
#endif
#endif
#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>
TRACELOGGING_DECLARE_PROVIDER( HTraceLogging_SteamNetworkingSockets );
TRACELOGGING_DEFINE_PROVIDER(
HTraceLogging_SteamNetworkingSockets,
"Valve.SteamNetworkingSockets",
/* OLD GUID: ( 0xb77d8a36, 0xef0c, 0x4976, 0x8d, 0x22, 0x08, 0xf9, 0x86, 0xf5, 0x6c, 0xfb ) */
/* NEW hash-based guid: */ ( 0xd4e956eb, 0xde52, 0x57ac, 0xdc, 0xaa, 0x1f, 0x9b, 0xa1, 0x04, 0x17, 0xc8 )
);
#if IsTraceLoggingEnabled()
// We'll put up to N of the first bytes in ETW events for the low level send/recv event
constexpr int k_cbETWEventUDPPacketDataSize = 16;
#endif
#if defined(_WIN32) && (defined(__MINGW32__) || defined(__MINGW64__))
// This one contains `_WSACMSGHDR` and friends in MinGW case (as opposed to `ws2def.h` for ordinary windows builds)
#include <mswsock.h>
#define cmsghdr WSACMSGHDR
#define CMSGHDR WSACMSGHDR
#define CMSG_FIRSTHDR WSA_CMSG_FIRSTHDR
#define CMSG_NXTHDR WSA_CMSG_NXTHDR
#endif
#ifdef _WIN32
// wincrypt.h defines CMSG_DATA as a CryptoAPI message-type constant (value 1),
// completely unrelated to sockets. Stomp it with the socket cmsg accessor so
// we can use CMSG_DATA uniformly in this file without #ifdef _WIN32 everywhere.
#undef CMSG_DATA
#define CMSG_DATA WSA_CMSG_DATA
#endif
namespace SteamNetworkingSocketsLib {
constexpr int k_msMaxPollWait = 1000;
int g_cbUDPSocketBufferSize = 256*1024;
#if PlatformCanSendECN()
int g_nSendECNAuto = -1;
#endif
std::atomic<int> s_nLowLevelSupportRefCount(0);
static volatile bool s_bManualPollMode;
int ClassifyIP( const CIPAddress &ip )
{
switch ( ip.GetType() )
{
case k_EIPTypeV4:
{
uint32 ipv4 = ip.GetIPv4(); // host order: first octet in bits 31-24
uint8 a = (uint8)( ipv4 >> 24 );
uint8 b = (uint8)( ipv4 >> 16 );
if ( TEST_mocknetwork_active )
{
// All mock IPv4 addresses are 127.0.X.x.
// Third octet == 100 is the simulated public internet; everything else is a private LAN.
if ( a == 127 )
{
if ( (ipv4 & 0xFF00) == (100 << 8) )
return k_nIPClassify_IPv4 | k_nIPClassify_Mock | k_nIPClassify_Public;
return k_nIPClassify_IPv4 | k_nIPClassify_Mock | k_nIPClassify_LAN;
}
// Not a mock address -- invalid in mock mode
return 0;
}
if ( a == 127 )
return k_nIPClassify_IPv4 | k_nIPClassify_Localhost;
if ( a == 10
|| ( a == 172 && b >= 16 && b <= 31 )
|| ( a == 192 && b == 168 )
|| ( a == 169 && b == 254 ) )
return k_nIPClassify_IPv4 | k_nIPClassify_LAN;
return k_nIPClassify_IPv4 | k_nIPClassify_Public;
}
case k_EIPTypeV6:
{
const uint8 *b = ip.GetIPV6Bytes();
if ( TEST_mocknetwork_active )
{
// All mock IPv6 addresses are fd7f:0:X::.
// Net ID 0x0100 (bytes 4-5 = {0x01, 0x00}) is the simulated public internet.
if ( b[0] == 0xfd && b[1] == 0x7f && b[2] == 0x00 && b[3] == 0x00 )
{
if ( b[4] == 0x01 && b[5] == 0x00 )
return k_nIPClassify_IPv6 | k_nIPClassify_Mock | k_nIPClassify_Public;
return k_nIPClassify_IPv6 | k_nIPClassify_Mock | k_nIPClassify_LAN;
}
// Not a mock address -- invalid in mock mode
return 0;
}
// ::1 (loopback) should never appear in non-mock mode
if ( memcmp( b, k_ipv6Bytes_Loopback, 16 ) == 0 )
return k_nIPClassify_IPv6 | k_nIPClassify_Localhost;
if ( (b[0] & 0xfe) == 0xfc ) // fc00::/7 -- ULA private space
return k_nIPClassify_IPv6 | k_nIPClassify_LAN;
if ( b[0] == 0xfe && (b[1] & 0xc0) == 0x80 ) // fe80::/10 -- link-local
return k_nIPClassify_IPv6 | k_nIPClassify_LAN;
return k_nIPClassify_IPv6 | k_nIPClassify_Public;
}
}
AssertMsg( false, "Invalid IP type %d", ip.GetType() );
return 0;
}
int ClassifyIP( const SteamNetworkingIPAddr &ip )
{
// FIXME We really should just get rid of all of our internal uses of the
// SteamNetworkingIPAddr type, and only use it for the API
netadr_t adr;
SteamNetworkingIPAddrToNetAdr( adr, ip );
return ClassifyIP( adr );
}
// 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 )
{
int nClassify = ClassifyIP( addr );
if ( nClassify & k_nIPClassify_Public )
return false; // public internet (real or mock-simulated) is never local
if ( nClassify & ( k_nIPClassify_LAN | k_nIPClassify_Localhost ) )
return true;
// ClassifyIP returned 0 (unrecognised address in mock mode, or invalid type).
// Fall through to the OS-level check for real addresses.
// 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 )
{
SpewWarning( "GetBestRoute2 failed with result %d for address '%s'\n", r, CUtlNetAdrRender( addr ).String() );
return false;
}
if ( bestRoute.Protocol == MIB_IPPROTO_LOCAL )
return true;
netadr_t nextHop;
if ( !nextHop.SetFromSockadr( &bestRoute.NextHop ) )
{
SpewWarning( "GetBestRoute2 returned invalid next hop address\n" );
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
//
/////////////////////////////////////////////////////////////////////////////
static double s_flFakeRateLimit_Send_tokens;
static double s_flFakeRateLimit_Recv_tokens;
static SteamNetworkingMicroseconds s_usecFakeRateLimitBucketUpdateTime;
static void InitFakeRateLimit()
{
s_usecFakeRateLimitBucketUpdateTime = SteamNetworkingSockets_GetLocalTimestamp();
s_flFakeRateLimit_Send_tokens = (double)INT_MAX;
s_flFakeRateLimit_Recv_tokens = (double)INT_MAX;
}
static void UpdateFakeRateLimitTokenBuckets( SteamNetworkingMicroseconds usecNow )
{
float flElapsed = ( usecNow - s_usecFakeRateLimitBucketUpdateTime ) * 1e-6;
s_usecFakeRateLimitBucketUpdateTime = usecNow;
if ( GlobalConfig::FakeRateLimit_Send_Rate.Get() <= 0 )
{
s_flFakeRateLimit_Send_tokens = (double)INT_MAX;
}
else
{
s_flFakeRateLimit_Send_tokens += flElapsed*GlobalConfig::FakeRateLimit_Send_Rate.Get();
s_flFakeRateLimit_Send_tokens = std::min( s_flFakeRateLimit_Send_tokens, (double)GlobalConfig::FakeRateLimit_Send_Burst.Get() );
}
if ( GlobalConfig::FakeRateLimit_Recv_Rate.Get() <= 0 )
{
s_flFakeRateLimit_Recv_tokens = (double)INT_MAX;
}
else
{
s_flFakeRateLimit_Recv_tokens += flElapsed*GlobalConfig::FakeRateLimit_Recv_Rate.Get();
s_flFakeRateLimit_Recv_tokens = std::min( s_flFakeRateLimit_Recv_tokens, (double)GlobalConfig::FakeRateLimit_Recv_Burst.Get() );
}
}
inline IRawUDPSocket::IRawUDPSocket() {}
inline IRawUDPSocket::~IRawUDPSocket() {}
// Perform gather-based send, on platform that doesn't have sendmsg
#ifdef PLATFORM_NO_SENDMSG
bool sendto_gather( int sockfd, int nChunks, const iovec *pChunks, sockaddr *pAddr, socklen_t addrSize )
{
COMPILE_TIME_ASSERT( k_cbSteamNetworkingSocketsMaxUDPMsgLen < 1500 );
char pkt[ 2048 ];
char *max = pkt + sizeof(pkt);
char *d = pkt;
for ( int i = 0 ; i < nChunks ; ++i )
{
const iovec &chunk = pChunks[i];
if ( d + chunk.iov_len > max )
{
AssertMsg( false, "Gather send too big!" );
return false;
}
memcpy( d, chunk.iov_base, chunk.iov_len );
d += chunk.iov_len;
}
ssize_t cbTotal = d - pkt;
ssize_t r = sendto( sockfd, pkt, cbTotal, 0, pAddr, addrSize );
return ( r == cbTotal );
}
#endif
class CRawUDPSocketImpl final : public IRawUDPSocket
{
public:
STEAMNETWORKINGSOCKETS_DECLARE_CLASS_OPERATOR_NEW
~CRawUDPSocketImpl()
{
closesocket( m_socket );
}
/// 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;
#if defined( _WIN32 ) && PlatformSupportsRecvMsg()
LPFN_WSARECVMSG m_pfnWSARecvMsg = nullptr;
#endif
#if PlatformSupportsRecvTOS()
bool m_bWarnIfNoTOSCMsg = false;
#endif
// Implements IRawUDPSocket
virtual bool BSendRawPacketGather( int nChunks, const iovec *pChunks, const netadr_t &adrTo, int ecn = -1 ) 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, int ecn ) const
{
Assert( m_socket != INVALID_SOCKET );
Assert( nChunks > 0 );
// 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 )
{
#ifdef PLATFORM_NO_IPV6
Assert( false );
return false;
#else
addrSize = sizeof(sockaddr_in6);
adrTo.ToSockadrIPV6( &destAddress );
#endif
}
else
{
addrSize = (socklen_t)adrTo.ToSockadr( &destAddress );
}
// Emit ETW event
#if IsTraceLoggingEnabled() // I should not have to use the preprocessor here, but if I don't, GCC emits warnings about variables set but not used, even though the code, trivially, is not reachable
if ( IsTraceLoggingProviderEnabled( HTraceLogging_SteamNetworkingSockets ) )
{
int cbTotal = 0;
for ( int i = 0 ; i < nChunks ; ++i )
cbTotal += (int)pChunks[i].iov_len;
char header_buf[k_cbETWEventUDPPacketDataSize];
const void *header;
int cbHeader;
if ( likely( nChunks == 1 || pChunks[0].iov_len >= k_cbETWEventUDPPacketDataSize ) )
{
header = pChunks[0].iov_base;
cbHeader = (int)std::min( (size_t)pChunks[0].iov_len, (size_t)k_cbETWEventUDPPacketDataSize );
}
else
{
cbHeader = 0;
for ( int i = 0 ; i < nChunks ; ++i )
{
int cbChunkHeader = std::min( (int)pChunks[i].iov_len, (int)k_cbETWEventUDPPacketDataSize - cbHeader );
memcpy( header_buf + cbHeader, pChunks[i].iov_base, cbChunkHeader );
cbHeader += cbChunkHeader;
}
header = header_buf;
}
TraceLoggingWrite(
HTraceLogging_SteamNetworkingSockets,
"UDPSend",
//TraceLoggingLevel( WINEVENT_LEVEL_INFO ),
TraceLoggingSocketAddress( &destAddress, addrSize, "Addr" ),
TraceLoggingUInt16( (uint16)cbTotal, "Bytes" ),
TraceLoggingBinary( header, cbHeader, "Data" )
);
}
#endif
if ( GlobalConfig::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 ) );
WSAMSG wsaMsg;
wsaMsg.name = (sockaddr *)&destAddress;
wsaMsg.namelen = addrSize;
wsaMsg.dwBufferCount = nChunks;
wsaMsg.lpBuffers = (WSABUF *)pChunks;
wsaMsg.Control.len = 0;
wsaMsg.Control.buf = nullptr;
wsaMsg.dwFlags = 0;
CHAR control[WSA_CMSG_SPACE(sizeof(INT))];
COMPILE_TIME_ASSERT( PlatformCanSendECN() );
// Check if we need to send ECN
if ( ecn < 0 )
ecn = ResolveECNSendGlobal();
if ( ecn > 0 ) // We assume that if we don't explicit specify an ECN, that zero will be used
{
wsaMsg.Control.len = sizeof(control);
wsaMsg.Control.buf = control;
memset( control, 0, sizeof(control) );
CMSGHDR *cmsg = WSA_CMSG_FIRSTHDR(&wsaMsg);
cmsg->cmsg_len = WSA_CMSG_LEN(sizeof(INT));
cmsg->cmsg_level = (destAddress.ss_family == AF_INET) ? IPPROTO_IP : IPPROTO_IPV6;
cmsg->cmsg_type = (destAddress.ss_family == AF_INET) ? IP_ECN : IPV6_ECN;
*(PINT)WSA_CMSG_DATA(cmsg) = ecn & 3;
}
DWORD numberOfBytesSent;
int r = WSASendMsg(
m_socket,
&wsaMsg,
0, // flags
&numberOfBytesSent,
nullptr, // lpOverlapped
nullptr // lpCompletionRoutine
);
bool bResult = ( r == 0 );
#if !IsXbox()
if ( !bResult )
{
const char *lpMsgBuf = nullptr;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastSocketError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
// Default language
(LPTSTR) & lpMsgBuf, 0, NULL);
if ( lpMsgBuf == nullptr )
{
SpewWarning( "WSASendTo %s failed, returned %d, last error=0x%x\n", CUtlNetAdrRender( adrTo ).String(), r, GetLastSocketError() );
}
else
{
SpewWarning( "WSASendTo %s failed, returned %d, last error=0x%x %s", CUtlNetAdrRender( adrTo ).String(), r, GetLastSocketError(), lpMsgBuf );
LocalFree( (LPVOID)lpMsgBuf );
}
}
#endif
#else
COMPILE_TIME_ASSERT( !PlatformCanSendECN() );
bool bResult;
if ( nChunks == 1 )
{
ssize_t r = sendto( m_socket, pChunks->iov_base, pChunks->iov_len, 0, (sockaddr *)&destAddress, addrSize );
bResult = ( r == (ssize_t)pChunks->iov_len );
}
else
{
#ifdef PLATFORM_NO_SENDMSG
bResult = sendto_gather( m_socket, nChunks, pChunks, (sockaddr *)&destAddress, addrSize );
#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;
ssize_t r = sendmsg( m_socket, &msg, 0 );
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
}
#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, GlobalConfig::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 );
}
}
virtual void SetCallbackRecvPacket( CRecvPacketCallback callback ) override
{
SteamNetworkingGlobalLock::AssertHeldByCurrentThread();
m_callback = callback;
}
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_DUALWIFI
CRawUDPSocketImpl *m_pDualWifiPartner = nullptr;
virtual IRawUDPSocket *GetDualWifiSecondarySocket( int nEnableSetting ) override;
#endif
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;
/// Are any sockets pending destruction?
static bool s_bRawSocketPendingDestruction;
class CPacketLagger;
struct CLaggedPacket final : public CPossibleOutOfOrderPacket
{
// Store the info about the packet using RecvPktInfo_t, even if we are
// queued to send. m_info.m_usecNow will store the time when we
// should be sent, while we are waiting
RecvPktInfo_t m_info;
// Linked list while we are in the CPacketLagger queue
CLaggedPacket *m_pPrev = nullptr;
CLaggedPacket *m_pNext = nullptr;
CPacketLagger *m_pLaggerOwner = nullptr;
// If we are really a CPossibleOutOfOrderPacket, and not just a
// lagged packet, this is our wire sequence number
int m_nWireSeqNum;
// Packet payload data
char m_pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ];
// Constructor used when lagging a packet to simulate latency
CLaggedPacket( CRawUDPSocketImpl *pSockOwner, const netadr_t &adrRemote, SteamNetworkingMicroseconds usecFlush, int cbPkt, uint8 tos )
: CPossibleOutOfOrderPacket()
, m_info{ m_pkt, cbPkt, usecFlush, adrRemote, false, tos, pSockOwner }
, m_nWireSeqNum( -1 ) // Fake lag, not out-of-order correction
{
Assert( cbPkt <= sizeof(m_pkt) );
}
// Constructor used when queuing a packet for possible out-of-order correction handling
CLaggedPacket( const RecvPktInfo_t &ctx, SteamNetworkingMicroseconds usecFlush, uint16 nWireSeqNum )
: CPossibleOutOfOrderPacket()
, m_info{ m_pkt, ctx.m_cbPkt, usecFlush, ctx.m_adrFrom, true, ctx.m_tos, ctx.m_pSock }
, m_nWireSeqNum( nWireSeqNum )
{
Assert( m_info.m_cbPkt < sizeof(m_pkt) );
memcpy( m_pkt, ctx.m_pPkt, m_info.m_cbPkt );
}
// Upcast
CRawUDPSocketImpl *SockOwner() const { return assert_cast<CRawUDPSocketImpl *>( m_info.m_pSock ); }
void Detach()
{
RemoveFromPacketLaggerList();
CPossibleOutOfOrderPacket::Detach();
}
private:
// If we're in a packet lagger list, remove us
void RemoveFromPacketLaggerList();
// CPossibleOutOfOrderPacket override to do our derived class destruction
virtual void DoDestroy() override
{
RemoveFromPacketLaggerList();
CPossibleOutOfOrderPacket::DoDestroy();
}
};
/// Track packets that have fake lag applied and are pending to be sent/received
class CPacketLagger : private IThinker
{
public:
~CPacketLagger() { Clear(); }
void LagPacket( CRawUDPSocketImpl *pSock, const netadr_t &adr, SteamNetworkingMicroseconds usecTime, int nChunks, const iovec *pChunks, uint8 tos )
{
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;
}
CLaggedPacket *pkt = new CLaggedPacket( pSock, adr, usecTime, cbPkt, tos );
// Gather the payload data data into the 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;
}
// Find the right place to insert the packet, searching backwards from the end. This is a dumb
// linear search, but in the steady state where the delay is constant, this search loop won't
// actually iterate, and we'll always be adding to the end of the queue
if ( m_pFirst )
{
CLaggedPacket *pInsertAfter = m_pLast;
for (;;)
{
if ( pInsertAfter->m_info.m_usecNow <= usecTime )
{
pkt->m_pPrev = pInsertAfter;
pkt->m_pNext = pInsertAfter->m_pNext;
pInsertAfter->m_pNext = pkt;
if ( pkt->m_pNext )
{
Assert( m_pLast != pInsertAfter );
Assert( pkt->m_pNext->m_pPrev == pInsertAfter );
pkt->m_pNext->m_pPrev = pkt;
}
else
{
Assert( m_pLast == pInsertAfter );
m_pLast = pkt;
}
break;
}
CLaggedPacket *p = pInsertAfter->m_pPrev;
if ( p == nullptr )
{
Assert( m_pFirst == pInsertAfter );
Assert( pInsertAfter->m_pPrev == nullptr );
pkt->m_pNext = pInsertAfter;
pInsertAfter->m_pPrev = pkt;
m_pFirst = pkt;
break;
}
Assert( m_pFirst != pInsertAfter );
Assert( p->m_pNext == pInsertAfter );
pInsertAfter = p;
}
}
else
{
// Empty list
m_pFirst = m_pLast = pkt;
}
pkt->m_pLaggerOwner = this;
SetNextThinkTime( m_pFirst->m_info.m_usecNow );
}
/// Implements IThinker
/// Periodic processing
virtual void Think( SteamNetworkingMicroseconds usecNow ) override
{
while ( m_pFirst )
{
// Next packet set to dispatch in the future?
if ( m_pFirst->m_info.m_usecNow > usecNow )
{
SetNextThinkTime( m_pFirst->m_info.m_usecNow );
break;
}
CLaggedPacket *p = m_pFirst;
Assert( p->m_pLaggerOwner == this );
p->Detach();
Assert( m_pFirst != p );
// Make sure socket is still in good shape.
CRawUDPSocketImpl *pSock = p->SockOwner();
if ( pSock )
{
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
{
p->m_info.m_usecNow = usecNow;
ProcessPacket( *p );
}
}
p->Destroy();
}
}
/// Nuke everything
void Clear()
{
while ( m_pFirst != nullptr )
{
CLaggedPacket *p = m_pFirst;
p->Destroy();
Assert( m_pFirst != p );
}
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 very short
// production situations, and socket destruction is relatively rare,
// so its not worth making this complicated.
CLaggedPacket *p = m_pFirst;
while ( p )
{
CLaggedPacket *x = p;
p = p->m_pNext;
if ( x->m_info.m_pSock == pSock )
{
x->Destroy();
}
}
}
// Queue a packet near the front of the queue. It will go AFTER any packets
// that have the same queue time
void QueueNearFront( CLaggedPacket *pkt )
{
Assert( pkt->m_pLaggerOwner == nullptr );
if ( m_pFirst )
{
CLaggedPacket *pInsertBefore = m_pFirst;
for (;;)
{
if ( pInsertBefore->m_info.m_usecNow > pkt->m_info.m_usecNow )
{
pkt->m_pNext = pInsertBefore;
pkt->m_pPrev = pInsertBefore->m_pPrev;
pInsertBefore->m_pPrev = pkt;
if ( pkt->m_pPrev )
{
Assert( m_pFirst != pInsertBefore );
Assert( pkt->m_pPrev->m_pNext == pInsertBefore );
pkt->m_pPrev->m_pNext = pkt;
}
else
{
Assert( m_pFirst == pInsertBefore );
m_pFirst = pkt;
}
break;
}
CLaggedPacket *n = pInsertBefore->m_pNext;
if ( n == nullptr )
{
Assert( m_pLast == pInsertBefore );
Assert( pInsertBefore->m_pNext == nullptr );
pkt->m_pPrev = pInsertBefore;
pInsertBefore->m_pNext = pkt;
m_pLast = pkt;
break;
}
Assert( m_pLast != pInsertBefore );
Assert( n->m_pPrev == pInsertBefore );
pInsertBefore = n;
}
}
else
{
// Empty list
m_pFirst = m_pLast = pkt;
}
pkt->m_pLaggerOwner = this;
SetNextThinkTime( m_pFirst->m_info.m_usecNow );
}
CLaggedPacket *m_pFirst = nullptr;
CLaggedPacket *m_pLast = nullptr;
protected:
/// Do whatever we're supposed to do with the next packet
virtual void ProcessPacket( const CLaggedPacket &pkt ) = 0;
};
void CLaggedPacket::RemoveFromPacketLaggerList()
{
if ( m_pLaggerOwner )
{
if ( m_pPrev )
{
Assert( m_pPrev->m_pNext == this );
m_pPrev->m_pNext = m_pNext;
}
else
{
Assert( m_pLaggerOwner->m_pFirst == this );
m_pLaggerOwner->m_pFirst = m_pNext;
}
if ( m_pNext )
{
Assert( m_pNext->m_pPrev == this );
m_pNext->m_pPrev = m_pPrev;
}
else
{
Assert( m_pLaggerOwner->m_pLast == this );
m_pLaggerOwner->m_pLast = m_pPrev;
}
}
else
{
Assert( m_pPrev == nullptr );
Assert( m_pNext == nullptr );
}
m_pLaggerOwner = nullptr;
m_pPrev = nullptr;
m_pNext = nullptr;
}
class CPacketLaggerSend final : public CPacketLagger
{
public:
virtual void ProcessPacket( const CLaggedPacket &pkt ) override
{
iovec temp;
temp.iov_len = pkt.m_info.m_cbPkt;
temp.iov_base = (void *)pkt.m_pkt;
int ecn = pkt.m_info.m_tos == 0xff ? -1 : pkt.m_info.m_tos;
pkt.SockOwner()->BReallySendRawPacket( 1, &temp, pkt.m_info.m_adrFrom, ecn );
}
};