/
steamnetworkingsockets_udp.cpp
1766 lines (1504 loc) · 58.3 KB
/
steamnetworkingsockets_udp.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//====== Copyright Valve Corporation, All rights reserved. ====================
#include "steamnetworkingsockets_udp.h"
#include "csteamnetworkingsockets.h"
#include "crypto.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
const int k_cbSteamNetworkingMinPaddedPacketSize = 512;
// Put everything in a namespace, so we don't violate the one definition rule
namespace SteamNetworkingSocketsLib {
#pragma pack( push, 1 )
/// A protobuf-encoded message that is padded to ensure a minimum length
struct UDPPaddedMessageHdr
{
uint8 m_nMsgID;
uint16 m_nMsgLength;
};
struct UDPDataMsgHdr
{
enum
{
kFlag_ProtobufBlob = 0x01, // Protobuf-encoded message is inline (CMsgSteamSockets_UDP_Stats)
};
uint8 m_unMsgFlags;
uint32 m_unToConnectionID; // Recipient's portion of the connection ID
uint16 m_unSeqNum;
// [optional, if flags&kFlag_ProtobufBlob] varint-encoded protobuf blob size, followed by blob
// Data frame(s)
// End of packet
};
#pragma pack( pop )
const int k_nMaxRecentLocalConnectionIDs = 256;
static CUtlVectorFixed<uint16,k_nMaxRecentLocalConnectionIDs> s_vecRecentLocalConnectionIDs;
/////////////////////////////////////////////////////////////////////////////
//
// Packet parsing / handling utils
//
/////////////////////////////////////////////////////////////////////////////
bool BCheckRateLimitReportBadPacket( SteamNetworkingMicroseconds usecNow )
{
static SteamNetworkingMicroseconds s_usecLastReport;
if ( s_usecLastReport + k_nMillion*2 > usecNow )
return false;
s_usecLastReport = usecNow;
return true;
}
void ReallyReportBadPacket( const netadr_t &adrFrom, const char *pszMsgType, const char *pszFmt, ... )
{
char buf[ 2048 ];
va_list ap;
va_start( ap, pszFmt );
V_vsprintf_safe( buf, pszFmt, ap );
va_end( ap );
V_StripTrailingWhitespaceASCII( buf );
if ( !pszMsgType || !pszMsgType[0] )
pszMsgType = "message";
SpewMsg( "Ignored bad %s from %s. %s\n", pszMsgType, CUtlNetAdrRender( adrFrom ).String(), buf );
}
#define ReportBadPacketFrom( adrFrom, pszMsgType, /* fmt */ ... ) \
( BCheckRateLimitReportBadPacket( usecNow ) ? ReallyReportBadPacket( adrFrom, pszMsgType, __VA_ARGS__ ) : (void)0 )
#define ReportBadPacket( pszMsgType, /* fmt */ ... ) \
ReportBadPacketFrom( adrFrom, pszMsgType, __VA_ARGS__ )
#define ParseProtobufBody( pvMsg, cbMsg, CMsgCls, msgVar ) \
CMsgCls msgVar; \
if ( !msgVar.ParseFromArray( pvMsg, cbMsg ) ) \
{ \
ReportBadPacket( # CMsgCls, "Protobuf parse failed." ); \
return; \
}
#define ParsePaddedPacket( pvPkt, cbPkt, CMsgCls, msgVar ) \
CMsgCls msgVar; \
{ \
if ( cbPkt < k_cbSteamNetworkingMinPaddedPacketSize ) \
{ \
ReportBadPacket( # CMsgCls, "Packet is %d bytes, must be padded to at least %d bytes.", cbPkt, k_cbSteamNetworkingMinPaddedPacketSize ); \
return; \
} \
const UDPPaddedMessageHdr *hdr = static_cast< const UDPPaddedMessageHdr * >( pvPkt ); \
int nMsgLength = LittleWord( hdr->m_nMsgLength ); \
if ( nMsgLength <= 0 || int(nMsgLength+sizeof(UDPPaddedMessageHdr)) > cbPkt ) \
{ \
ReportBadPacket( # CMsgCls, "Invalid encoded message length %d. Packet is %d bytes.", nMsgLength, cbPkt ); \
return; \
} \
if ( !msgVar.ParseFromArray( hdr+1, nMsgLength ) ) \
{ \
ReportBadPacket( # CMsgCls, "Protobuf parse failed." ); \
return; \
} \
}
/////////////////////////////////////////////////////////////////////////////
//
// CSteamNetworkListenSocketDirectUDP
//
/////////////////////////////////////////////////////////////////////////////
CSteamNetworkListenSocketDirectUDP::CSteamNetworkListenSocketDirectUDP( CSteamNetworkingSockets *pSteamNetworkingSocketsInterface )
: CSteamNetworkListenSocketBase( pSteamNetworkingSocketsInterface )
{
m_pSock = nullptr;
}
CSteamNetworkListenSocketDirectUDP::~CSteamNetworkListenSocketDirectUDP()
{
// Clean up socket, if any
if ( m_pSock )
{
delete m_pSock;
m_pSock = nullptr;
}
}
bool CSteamNetworkListenSocketDirectUDP::BInit( const SteamNetworkingIPAddr &localAddr, SteamDatagramErrMsg &errMsg )
{
Assert( m_pSock == nullptr );
if ( localAddr.m_port == 0 )
{
V_strcpy_safe( errMsg, "Must specify local port." );
return false;
}
m_pSock = new CSharedSocket;
if ( !m_pSock->BInit( localAddr, CRecvPacketCallback( ReceivedFromUnknownHost, this ), errMsg ) )
{
delete m_pSock;
m_pSock = nullptr;
return false;
}
CCrypto::GenerateRandomBlock( m_argbChallengeSecret, sizeof(m_argbChallengeSecret) );
return true;
}
bool CSteamNetworkListenSocketDirectUDP::APIGetAddress( SteamNetworkingIPAddr *pAddress )
{
if ( !m_pSock )
{
Assert( false );
return false;
}
const SteamNetworkingIPAddr *pBoundAddr = m_pSock->GetBoundAddr();
if ( !pBoundAddr )
return false;
if ( pAddress )
*pAddress = *pBoundAddr;
return true;
}
/////////////////////////////////////////////////////////////////////////////
//
// CSteamNetworkListenSocketUDP packet handling
//
/////////////////////////////////////////////////////////////////////////////
void CSteamNetworkListenSocketDirectUDP::ReceivedFromUnknownHost( const void *pvPkt, int cbPkt, const netadr_t &adrFrom, CSteamNetworkListenSocketDirectUDP *pSock )
{
const uint8 *pPkt = static_cast<const uint8 *>( pvPkt );
SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp();
if ( cbPkt < 5 )
{
ReportBadPacket( "packet", "%d byte packet is too small", cbPkt );
return;
}
if ( *pPkt & 0x80 )
{
if ( *(uint32*)pPkt == 0xffffffff )
{
// Source engine connectionless packet (LAN discovery, etc).
// Just ignore it, and don't even spew.
}
else
{
// A stray data packet. Just ignore it.
//
// When clients are able to actually establish a connection, after that connection
// is over we will use the FinWait state to close down the connection gracefully.
// But since we don't have that connection in our table anymore, either this guy
// never had a connection, or else we believe he knows that the connection was closed,
// or the FinWait state has timed out.
ReportBadPacket( "Data", "Stray data packet from host with no connection. Ignoring." );
}
}
else if ( *pPkt == k_ESteamNetworkingUDPMsg_ChallengeRequest )
{
ParsePaddedPacket( pvPkt, cbPkt, CMsgSteamSockets_UDP_ChallengeRequest, msg )
pSock->Received_ChallengeRequest( msg, adrFrom, usecNow );
}
else if ( *pPkt == k_ESteamNetworkingUDPMsg_ConnectRequest )
{
ParseProtobufBody( pPkt+1, cbPkt-1, CMsgSteamSockets_UDP_ConnectRequest, msg )
pSock->Received_ConnectRequest( msg, adrFrom, cbPkt, usecNow );
}
else if ( *pPkt == k_ESteamNetworkingUDPMsg_ConnectionClosed )
{
ParsePaddedPacket( pvPkt, cbPkt, CMsgSteamSockets_UDP_ConnectionClosed, msg )
pSock->Received_ConnectionClosed( msg, adrFrom, usecNow );
}
else if ( *pPkt == k_ESteamNetworkingUDPMsg_NoConnection )
{
// They don't think there's a connection on this address.
// We agree -- connection ID doesn't matter. Nothing else to do.
}
else
{
// Any other lead byte is bogus
//
// Note in particular that these packet types should be ignored:
//
// k_ESteamNetworkingUDPMsg_ChallengeReply
// k_ESteamNetworkingUDPMsg_ConnectOK
//
// We are not initiating connections, so we shouldn't ever get
// those sorts of replies.
ReportBadPacket( "packet", "Invalid lead byte 0x%02x", *pPkt );
}
}
uint64 CSteamNetworkListenSocketDirectUDP::GenerateChallenge( uint16 nTime, const netadr_t &adr ) const
{
#pragma pack(push,1)
struct
{
uint16 nTime;
uint16 nPort;
uint8 ipv6[16];
} data;
#pragma pack(pop)
data.nTime = nTime;
data.nPort = adr.GetPort();
adr.GetIPV6( data.ipv6 );
uint64 nChallenge = siphash( (const uint8_t *)&data, sizeof(data), m_argbChallengeSecret );
return ( nChallenge & 0xffffffffffff0000ull ) | nTime;
}
inline uint16 GetChallengeTime( SteamNetworkingMicroseconds usecNow )
{
return uint16( usecNow >> 20 );
}
void CSteamNetworkListenSocketDirectUDP::Received_ChallengeRequest( const CMsgSteamSockets_UDP_ChallengeRequest &msg, const netadr_t &adrFrom, SteamNetworkingMicroseconds usecNow )
{
if ( msg.connection_id() == 0 )
{
ReportBadPacket( "ChallengeRequest", "Missing connection_id." );
return;
}
//CSteamID steamIDClient( uint64( msg.client_steam_id() ) );
//if ( !steamIDClient.IsValid() )
//{
// ReportBadPacket( "ChallengeRequest", "Missing/invalid SteamID.", cbPkt );
// return;
//}
// Get time value of challenge
uint16 nTime = GetChallengeTime( usecNow );
// Generate a challenge
uint64 nChallenge = GenerateChallenge( nTime, adrFrom );
// Send them a reply
CMsgSteamSockets_UDP_ChallengeReply msgReply;
msgReply.set_connection_id( msg.connection_id() );
msgReply.set_challenge( nChallenge );
msgReply.set_your_timestamp( msg.my_timestamp() );
msgReply.set_protocol_version( k_nCurrentProtocolVersion );
SendMsg( k_ESteamNetworkingUDPMsg_ChallengeReply, msgReply, adrFrom );
}
void CSteamNetworkListenSocketDirectUDP::Received_ConnectRequest( const CMsgSteamSockets_UDP_ConnectRequest &msg, const netadr_t &adrFrom, int cbPkt, SteamNetworkingMicroseconds usecNow )
{
SteamDatagramErrMsg errMsg;
// Make sure challenge was generated relatively recently
uint16 nTimeThen = uint32( msg.challenge() );
uint16 nElapsed = GetChallengeTime( usecNow ) - nTimeThen;
if ( nElapsed > GetChallengeTime( 4*k_nMillion ) )
{
ReportBadPacket( "ConnectRequest", "Challenge too old." );
return;
}
// Assuming we sent them this time value, re-create the challenge we would have sent them.
if ( GenerateChallenge( nTimeThen, adrFrom ) != msg.challenge() )
{
ReportBadPacket( "ConnectRequest", "Incorrect challenge. Could be spoofed." );
return;
}
uint32 unClientConnectionID = msg.client_connection_id();
if ( unClientConnectionID == 0 )
{
ReportBadPacket( "ConnectRequest", "Missing connection ID" );
return;
}
// Parse out identity from the cert
SteamNetworkingIdentity identityRemote;
bool bIdentityInCert = true;
{
// !SPEED! We are deserializing the cert here,
// and then we are going to do it again below.
// Should refactor to fix this.
int r = SteamNetworkingIdentityFromSignedCert( identityRemote, msg.cert(), errMsg );
if ( r < 0 )
{
ReportBadPacket( "ConnectRequest", "Bad identity in cert. %s", errMsg );
return;
}
if ( r == 0 )
{
// No identity in the cert. Check if they put it directly in the connect message
bIdentityInCert = false;
r = SteamNetworkingIdentityFromProtobuf( identityRemote, msg, identity, legacy_client_steam_id, errMsg );
if ( r < 0 )
{
ReportBadPacket( "ConnectRequest", "Bad identity. %s", errMsg );
return;
}
if ( r == 0 )
{
// If no identity was presented, it's the same as them saying they are "localhost"
identityRemote.SetLocalHost();
}
}
}
Assert( !identityRemote.IsInvalid() );
// Check if they are using an IP address as an identity (possibly the anonymous "localhost" identity)
if ( identityRemote.m_eType == k_ESteamNetworkingIdentityType_IPAddress )
{
SteamNetworkingIPAddr addr;
adrFrom.GetIPV6( addr.m_ipv6 );
addr.m_port = adrFrom.GetPort();
if ( identityRemote.IsLocalHost() )
{
if ( m_connectionConfig.m_IP_AllowWithoutAuth.Get() == 0 )
{
// Should we send an explicit rejection here?
ReportBadPacket( "ConnectRequest", "Unauthenticated connections not allowed." );
return;
}
// Set their identity to their real address (including port)
identityRemote.SetIPAddr( addr );
}
else
{
// FIXME - Should the address be required to match?
// If we are behind NAT, it won't.
//if ( memcmp( addr.m_ipv6, identityRemote.m_ip.m_ipv6, sizeof(addr.m_ipv6) ) != 0
// || ( identityRemote.m_ip.m_port != 0 && identityRemote.m_ip.m_port != addr.m_port ) ) // Allow 0 port in the identity to mean "any port"
//{
// ReportBadPacket( "ConnectRequest", "Identity in request is %s, but packet is coming from %s." );
// return;
//}
// It's not really clear what the use case is here for
// requesting a specific IP address as your identity,
// and not using localhost. If they have a cert, assume it's
// meaningful. Remember: the cert could be unsigned! That
// is a separate issue which will be handled later, whether
// we want to allow that.
if ( !bIdentityInCert )
{
// Should we send an explicit rejection here?
ReportBadPacket( "ConnectRequest", "Cannot use specific IP address." );
return;
}
}
}
// Does this connection already exist? (At a different address?)
int h = m_mapChildConnections.Find( RemoteConnectionKey_t{ identityRemote, unClientConnectionID } );
if ( h != m_mapChildConnections.InvalidIndex() )
{
CSteamNetworkConnectionBase *pOldConn = m_mapChildConnections[ h ];
Assert( pOldConn->m_identityRemote == identityRemote );
Assert( pOldConn->GetRemoteAddr() != adrFrom ); // or else why didn't we already map it directly to them!
// NOTE: We cannot just destroy the object. The API semantics
// are that all connections, once accepted and made visible
// to the API, must be closed by the application.
ReportBadPacket( "ConnectRequest", "Rejecting connection request from %s at %s, connection ID %u. That steamID/ConnectionID pair already has a connection from %s\n",
SteamNetworkingIdentityRender( identityRemote ).c_str(), CUtlNetAdrRender( adrFrom ).String(), unClientConnectionID, CUtlNetAdrRender( pOldConn->GetRemoteAddr() ).String()
);
CMsgSteamSockets_UDP_ConnectionClosed msgReply;
msgReply.set_to_connection_id( unClientConnectionID );
msgReply.set_reason_code( k_ESteamNetConnectionEnd_Misc_Generic );
msgReply.set_debug( "A connection with that ID already exists." );
SendPaddedMsg( k_ESteamNetworkingUDPMsg_ConnectionClosed, msgReply, adrFrom );
}
CSteamNetworkConnectionUDP *pConn = new CSteamNetworkConnectionUDP( m_pSteamNetworkingSocketsInterface );
// OK, they have completed the handshake. Accept the connection.
if ( !pConn->BBeginAccept( this, adrFrom, m_pSock, identityRemote, unClientConnectionID, msg.cert(), msg.crypt(), errMsg ) )
{
SpewWarning( "Failed to accept connection from %s. %s\n", CUtlNetAdrRender( adrFrom ).String(), errMsg );
pConn->Destroy();
return;
}
pConn->m_statsEndToEnd.TrackRecvPacket( cbPkt, usecNow );
// Did they send us a ping estimate?
if ( msg.has_ping_est_ms() )
pConn->m_statsEndToEnd.m_ping.ReceivedPing( msg.ping_est_ms(), usecNow );
// Save of timestamp that we will use to reply to them when the application
// decides to accept the connection
if ( msg.has_my_timestamp() )
{
pConn->m_ulHandshakeRemoteTimestamp = msg.my_timestamp();
pConn->m_usecWhenReceivedHandshakeRemoteTimestamp = usecNow;
}
}
void CSteamNetworkListenSocketDirectUDP::Received_ConnectionClosed( const CMsgSteamSockets_UDP_ConnectionClosed &msg, const netadr_t &adrFrom, SteamNetworkingMicroseconds usecNow )
{
// Send an ack. Note that we require the inbound message to be padded
// to a minimum size, and this reply is tiny, so we are not at a risk of
// being used for reflection, even though the source address could be spoofed.
CMsgSteamSockets_UDP_NoConnection msgReply;
if ( msg.from_connection_id() )
msgReply.set_to_connection_id( msg.from_connection_id() );
if ( msg.to_connection_id() )
msgReply.set_from_connection_id( msg.to_connection_id() );
SendMsg( k_ESteamNetworkingUDPMsg_NoConnection, msgReply, adrFrom );
}
void CSteamNetworkListenSocketDirectUDP::SendMsg( uint8 nMsgID, const google::protobuf::MessageLite &msg, const netadr_t &adrTo )
{
if ( !m_pSock )
{
Assert( false );
return;
}
uint8 pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ];
pkt[0] = nMsgID;
int cbPkt = msg.ByteSize()+1;
if ( cbPkt > sizeof(pkt) )
{
AssertMsg3( false, "Msg type %d is %d bytes, larger than MTU of %d bytes", int( nMsgID ), cbPkt, (int)sizeof(pkt) );
return;
}
uint8 *pEnd = msg.SerializeWithCachedSizesToArray( pkt+1 );
Assert( cbPkt == pEnd - pkt );
// Send the reply
m_pSock->BSendRawPacket( pkt, cbPkt, adrTo );
}
void CSteamNetworkListenSocketDirectUDP::SendPaddedMsg( uint8 nMsgID, const google::protobuf::MessageLite &msg, const netadr_t adrTo )
{
uint8 pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ];
memset( pkt, 0, sizeof(pkt) ); // don't send random bits from our process memory over the wire!
UDPPaddedMessageHdr *hdr = (UDPPaddedMessageHdr *)pkt;
int nMsgLength = msg.ByteSize();
hdr->m_nMsgID = nMsgID;
hdr->m_nMsgLength = LittleWord( uint16( nMsgLength ) );
uint8 *pEnd = msg.SerializeWithCachedSizesToArray( pkt + sizeof(*hdr) );
int cbPkt = pEnd - pkt;
Assert( cbPkt == int( sizeof(*hdr) + nMsgLength ) );
cbPkt = MAX( cbPkt, k_cbSteamNetworkingMinPaddedPacketSize );
m_pSock->BSendRawPacket( pkt, cbPkt, adrTo );
}
/////////////////////////////////////////////////////////////////////////////
//
// IP connections
//
/////////////////////////////////////////////////////////////////////////////
CSteamNetworkConnectionUDP::CSteamNetworkConnectionUDP( CSteamNetworkingSockets *pSteamNetworkingSocketsInterface )
: CSteamNetworkConnectionBase( pSteamNetworkingSocketsInterface )
{
m_pSocket = nullptr;
}
CSteamNetworkConnectionUDP::~CSteamNetworkConnectionUDP()
{
AssertMsg( !m_pSocket, "Connection not destroyed properly" );
}
void CSteamNetworkConnectionUDP::GetConnectionTypeDescription( ConnectionTypeDescription_t &szDescription ) const
{
char szAddr[ 64 ];
if ( m_pSocket )
{
SteamNetworkingIPAddr adrRemote;
NetAdrToSteamNetworkingIPAddr( adrRemote, m_pSocket->GetRemoteHostAddr() );
adrRemote.ToString( szAddr, sizeof(szAddr), true );
if (
m_identityRemote.IsLocalHost()
|| ( m_identityRemote.m_eType == k_ESteamNetworkingIdentityType_IPAddress && adrRemote == m_identityRemote.m_ip )
) {
V_sprintf_safe( szDescription, "UDP %s", szAddr );
return;
}
}
else
{
V_strcpy_safe( szAddr, "???" );
}
SteamNetworkingIdentityRender sIdentity( m_identityRemote );
V_sprintf_safe( szDescription, "UDP %s@%s", sIdentity.c_str(), szAddr );
}
void CSteamNetworkConnectionUDP::FreeResources()
{
if ( m_pSocket )
{
m_pSocket->Close();
m_pSocket = nullptr;
}
// Base class cleanup
CSteamNetworkConnectionBase::FreeResources();
}
template<>
inline uint32 StatsMsgImpliedFlags<CMsgSteamSockets_UDP_Stats>( const CMsgSteamSockets_UDP_Stats &msg )
{
return msg.has_stats() ? msg.ACK_REQUEST_E2E : 0;
}
struct UDPSendPacketContext_t : SendPacketContext<CMsgSteamSockets_UDP_Stats>
{
inline explicit UDPSendPacketContext_t( SteamNetworkingMicroseconds usecNow, const char *pszReason ) : SendPacketContext<CMsgSteamSockets_UDP_Stats>( usecNow, pszReason ) {}
int m_nStatsNeed;
};
void CSteamNetworkConnectionUDP::PopulateSendPacketContext( UDPSendPacketContext_t &ctx, EStatsReplyRequest eReplyRequested )
{
SteamNetworkingMicroseconds usecNow = ctx.m_usecNow;
// What effective flags should we send
uint32 nFlags = 0;
if ( eReplyRequested == k_EStatsReplyRequest_Immediate || m_statsEndToEnd.BNeedToSendPingImmediate( usecNow ) )
nFlags |= ctx.msg.ACK_REQUEST_E2E | ctx.msg.ACK_REQUEST_IMMEDIATE;
else if ( eReplyRequested == k_EStatsReplyRequest_DelayedOK || m_statsEndToEnd.BNeedToSendKeepalive( usecNow ) || m_statsEndToEnd.BReadyToSendTracerPing( usecNow ) )
nFlags |= ctx.msg.ACK_REQUEST_E2E;
ctx.m_nFlags = nFlags;
// Need to send any connection stats stats?
if ( m_statsEndToEnd.BNeedToSendStats( usecNow ) )
{
ctx.m_nStatsNeed = 2;
m_statsEndToEnd.PopulateMessage( *ctx.msg.mutable_stats(), usecNow );
ctx.SlamFlagsAndCalcSize();
ctx.CalcMaxEncryptedPayloadSize( sizeof(UDPDataMsgHdr) );
}
else
{
// Populate flags now, based on what is implied from what we HAVE to send
ctx.SlamFlagsAndCalcSize();
ctx.CalcMaxEncryptedPayloadSize( sizeof(UDPDataMsgHdr) );
// Would we like to try to send some additional stats, if there is room?
if ( m_statsEndToEnd.BReadyToSendStats( usecNow ) )
{
m_statsEndToEnd.PopulateMessage( *ctx.msg.mutable_stats(), usecNow );
ctx.SlamFlagsAndCalcSize();
ctx.m_nStatsNeed = 1;
}
else
{
// No need to send any stats right now
ctx.m_nStatsNeed = 0;
}
}
}
void CSteamNetworkConnectionUDP::SendStatsMsg( EStatsReplyRequest eReplyRequested, SteamNetworkingMicroseconds usecNow, const char *pszReason )
{
UDPSendPacketContext_t ctx( usecNow, pszReason );
PopulateSendPacketContext( ctx, eReplyRequested );
// Send a data packet (maybe containing ordinary data), with this piggy backed on top of it
SNP_SendPacket( ctx );
}
bool CSteamNetworkConnectionUDP::SendDataPacket( SteamNetworkingMicroseconds usecNow )
{
// Populate context struct with any stats we want/need to send, and how much space we need to reserve for it
UDPSendPacketContext_t ctx( usecNow, "data" );
PopulateSendPacketContext( ctx, k_EStatsReplyRequest_NothingToSend );
// Send a packet
return SNP_SendPacket( ctx );
}
int CSteamNetworkConnectionUDP::SendEncryptedDataChunk( const void *pChunk, int cbChunk, SendPacketContext_t &ctxBase )
{
if ( !m_pSocket )
{
Assert( false );
return 0;
}
UDPSendPacketContext_t &ctx = static_cast<UDPSendPacketContext_t &>( ctxBase );
uint8 pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ];
UDPDataMsgHdr *hdr = (UDPDataMsgHdr *)pkt;
hdr->m_unMsgFlags = 0x80;
Assert( m_unConnectionIDRemote != 0 );
hdr->m_unToConnectionID = LittleDWord( m_unConnectionIDRemote );
hdr->m_unSeqNum = LittleWord( m_statsEndToEnd.ConsumeSendPacketNumberAndGetWireFmt( ctx.m_usecNow ) );
byte *p = (byte*)( hdr + 1 );
// Check how much bigger we could grow the header
// and still fit in a packet
int cbHdrOutSpaceRemaining = pkt + sizeof(pkt) - p - cbChunk;
if ( cbHdrOutSpaceRemaining < 0 )
{
AssertMsg( false, "MTU / header size problem!" );
return 0;
}
// Try to trim stuff from blob, if it won't fit
while ( ctx.m_cbTotalSize > cbHdrOutSpaceRemaining )
{
if ( ctx.msg.has_stats() )
{
AssertMsg( ctx.m_nStatsNeed == 1, "We didn't reserve enough space for stats!" );
if ( ctx.msg.stats().has_instantaneous() && ctx.msg.stats().has_lifetime() )
{
// Trying to send both - clear instantaneous
ctx.msg.mutable_stats()->clear_instantaneous();
}
else
{
// Trying to send just one or the other. Clear the whole container.
ctx.msg.clear_stats();
}
ctx.SlamFlagsAndCalcSize();
continue;
}
// Nothing left to clear!? We shouldn't get here!
AssertMsg( false, "Serialized stats message still won't fit, ever after clearing everything?" );
ctx.m_cbTotalSize = 0;
break;
}
if ( ctx.Serialize( p ) )
{
// Update bookkeeping with the stuff we are actually sending
TrackSentStats( ctx.msg, true, ctx.m_usecNow );
// Mark header with the flag
hdr->m_unMsgFlags |= hdr->kFlag_ProtobufBlob;
}
// !FIXME! Time since previous, for jitter measurement?
// Use gather-based send. This saves one memcpy of every payload
iovec gather[2];
gather[0].iov_base = pkt;
gather[0].iov_len = p - pkt;
gather[1].iov_base = const_cast<void*>( pChunk );
gather[1].iov_len = cbChunk;
int cbSend = gather[0].iov_len + gather[1].iov_len;
Assert( cbSend <= sizeof(pkt) ); // Bug in the code above. We should never "overflow" the packet. (Ignoring the fact that we using a gather-based send. The data could be tiny with a large header for piggy-backed stats.)
// !FIXME! Should we track data payload separately? Maybe we ought to track
// *messages* instead of packets.
// Send it
SendPacketGather( 2, gather, cbSend );
return cbSend;
}
bool CSteamNetworkConnectionUDP::BInitConnect( const SteamNetworkingIPAddr &addressRemote, SteamDatagramErrMsg &errMsg )
{
AssertMsg( !m_pSocket, "Trying to connect when we already have a socket?" );
// We're initiating a connection, not being accepted on a listen socket
Assert( !m_pParentListenSocket );
netadr_t netadrRemote;
SteamNetworkingIPAddrToNetAdr( netadrRemote, addressRemote );
// For now we're just assuming each connection will gets its own socket,
// on an ephemeral port. Later we could add a setting to enable
// sharing of the socket.
m_pSocket = OpenUDPSocketBoundToHost( netadrRemote, CRecvPacketCallback( PacketReceived, this ), errMsg );
if ( !m_pSocket )
return false;
// We use identity validity to denote when our connection has been accepted,
// so it's important that it be cleared. (It should already be so.)
Assert( m_identityRemote.IsInvalid() );
m_identityRemote.Clear();
// We should know our own identity, unless the app has said it's OK to go without this.
if ( m_identityLocal.IsInvalid() ) // Specific identity hasn't already been set (by derived class, etc)
{
// Use identity from the interface, if we have one
m_identityLocal = m_pSteamNetworkingSocketsInterface->InternalGetIdentity();
if ( m_identityLocal.IsInvalid())
{
// We don't know who we are. Should we attempt anonymous?
if ( m_connectionConfig.m_IP_AllowWithoutAuth.Get() == 0 )
{
V_strcpy_safe( errMsg, "Unable to determine local identity, and auth required. Not logged in?" );
return false;
}
m_identityLocal.SetLocalHost();
}
}
// Let base class do some common initialization
SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp();
if ( !CSteamNetworkConnectionBase::BInitConnection( usecNow, errMsg ) )
{
m_pSocket->Close();
m_pSocket = nullptr;
return false;
}
// Start the connection state machine, and send the first request packet.
CheckConnectionStateAndSetNextThinkTime( usecNow );
return true;
}
bool CSteamNetworkConnectionUDP::BCanSendEndToEndConnectRequest() const
{
return m_pSocket != nullptr;
}
bool CSteamNetworkConnectionUDP::BCanSendEndToEndData() const
{
return m_pSocket != nullptr;
}
void CSteamNetworkConnectionUDP::SendEndToEndConnectRequest( SteamNetworkingMicroseconds usecNow )
{
Assert( !m_pParentListenSocket );
Assert( GetState() == k_ESteamNetworkingConnectionState_Connecting ); // Why else would we be doing this?
Assert( m_unConnectionIDLocal );
CMsgSteamSockets_UDP_ChallengeRequest msg;
msg.set_connection_id( m_unConnectionIDLocal );
//msg.set_client_steam_id( m_steamIDLocal.ConvertToUint64() );
msg.set_my_timestamp( usecNow );
msg.set_protocol_version( k_nCurrentProtocolVersion );
// Send it, with padding
SendPaddedMsg( k_ESteamNetworkingUDPMsg_ChallengeRequest, msg );
// They are supposed to reply with a timestamps, from which we can estimate the ping.
// So this counts as a ping request
m_statsEndToEnd.TrackSentPingRequest( usecNow, false );
}
void CSteamNetworkConnectionUDP::SendEndToEndStatsMsg( EStatsReplyRequest eRequest, SteamNetworkingMicroseconds usecNow, const char *pszReason )
{
SendStatsMsg( eRequest, usecNow, pszReason );
}
void CSteamNetworkConnectionUDP::ThinkConnection( SteamNetworkingMicroseconds usecNow )
{
// FIXME - We should refactor this, maybe promote this to the base class.
// There's really nothing specific to plain UDP transport here.
// Check if we have stats we need to flush out
if ( BStateIsConnectedForWirePurposes() )
{
// Do we need to send something immediately, for any reason?
const char *pszReason = NeedToSendEndToEndStatsOrAcks( usecNow );
if ( pszReason )
{
SendStatsMsg( k_EStatsReplyRequest_NothingToSend, usecNow, pszReason );
// Make sure that took care of what we needed!
Assert( !NeedToSendEndToEndStatsOrAcks( usecNow ) );
}
}
}
bool CSteamNetworkConnectionUDP::BBeginAccept(
CSteamNetworkListenSocketDirectUDP *pParent,
const netadr_t &adrFrom,
CSharedSocket *pSharedSock,
const SteamNetworkingIdentity &identityRemote,
uint32 unConnectionIDRemote,
const CMsgSteamDatagramCertificateSigned &msgCert,
const CMsgSteamDatagramSessionCryptInfoSigned &msgCryptSessionInfo,
SteamDatagramErrMsg &errMsg
)
{
AssertMsg( !m_pSocket, "Trying to accept when we already have a socket?" );
// Get an interface just to talk just to this guy
m_pSocket = pSharedSock->AddRemoteHost( adrFrom, CRecvPacketCallback( PacketReceived, this ) );
if ( !m_pSocket )
{
V_strcpy_safe( errMsg, "Unable to create a bound socket on the shared socket." );
return false;
}
m_identityRemote = identityRemote;
// Caller should have ensured a valid identity
Assert( !m_identityRemote.IsInvalid() );
m_unConnectionIDRemote = unConnectionIDRemote;
m_netAdrRemote = adrFrom;
pParent->AddChildConnection( this );
// Let base class do some common initialization
SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp();
if ( !CSteamNetworkConnectionBase::BInitConnection( usecNow, errMsg ) )
{
m_pSocket->Close();
m_pSocket = nullptr;
return false;
}
// Process crypto handshake now
if ( !BRecvCryptoHandshake( msgCert, msgCryptSessionInfo, true ) )
{
m_pSocket->Close();
m_pSocket = nullptr;
Assert( GetState() == k_ESteamNetworkingConnectionState_ProblemDetectedLocally );
V_sprintf_safe( errMsg, "Failed crypto init. %s", m_szEndDebug );
return false;
}
// OK
return true;
}
EResult CSteamNetworkConnectionUDP::APIAcceptConnection()
{
SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp();
// Send the message
SendConnectOK( usecNow );
// We are fully connected
ConnectionState_Connected( usecNow );
// OK
return k_EResultOK;
}
void CSteamNetworkConnectionUDP::SendMsg( uint8 nMsgID, const google::protobuf::MessageLite &msg )
{
uint8 pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ];
pkt[0] = nMsgID;
int cbPkt = msg.ByteSize()+1;
if ( cbPkt > sizeof(pkt) )
{
AssertMsg3( false, "Msg type %d is %d bytes, larger than MTU of %d bytes", int( nMsgID ), cbPkt, (int)sizeof(pkt) );
return;
}
uint8 *pEnd = msg.SerializeWithCachedSizesToArray( pkt+1 );
Assert( cbPkt == pEnd - pkt );
SendPacket( pkt, cbPkt );
}
void CSteamNetworkConnectionUDP::SendPaddedMsg( uint8 nMsgID, const google::protobuf::MessageLite &msg )
{
uint8 pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ];
V_memset( pkt, 0, sizeof(pkt) ); // don't send random bits from our process memory over the wire!
UDPPaddedMessageHdr *hdr = (UDPPaddedMessageHdr *)pkt;
int nMsgLength = msg.ByteSize();
if ( nMsgLength + sizeof(*hdr) > k_cbSteamNetworkingSocketsMaxUDPMsgLen )
{
AssertMsg3( false, "Msg type %d is %d bytes, larger than MTU of %d bytes", int( nMsgID ), int( nMsgLength + sizeof(*hdr) ), (int)sizeof(pkt) );
return;
}
hdr->m_nMsgID = nMsgID;
hdr->m_nMsgLength = LittleWord( uint16( nMsgLength ) );
uint8 *pEnd = msg.SerializeWithCachedSizesToArray( pkt + sizeof(*hdr) );
int cbPkt = pEnd - pkt;
Assert( cbPkt == int( sizeof(*hdr) + nMsgLength ) );
cbPkt = MAX( cbPkt, k_cbSteamNetworkingMinPaddedPacketSize );
SendPacket( pkt, cbPkt );
}
void CSteamNetworkConnectionUDP::SendPacket( const void *pkt, int cbPkt )
{
iovec temp;
temp.iov_base = const_cast<void*>( pkt );
temp.iov_len = cbPkt;
SendPacketGather( 1, &temp, cbPkt );
}
void CSteamNetworkConnectionUDP::SendPacketGather( int nChunks, const iovec *pChunks, int cbSendTotal )
{
// Safety
if ( !m_pSocket )
{
AssertMsg( false, "Attemt to send packet, but socket has been closed!" );
return;
}
// Update stats
m_statsEndToEnd.TrackSentPacket( cbSendTotal );
// Hand over to operating system
m_pSocket->BSendRawPacketGather( nChunks, pChunks );
}
void CSteamNetworkConnectionUDP::ConnectionStateChanged( ESteamNetworkingConnectionState eOldState )
{
CSteamNetworkConnectionBase::ConnectionStateChanged( eOldState );
switch ( GetState() )
{
case k_ESteamNetworkingConnectionState_FindingRoute: // not used for raw UDP
default:
Assert( false );
case k_ESteamNetworkingConnectionState_None:
case k_ESteamNetworkingConnectionState_Dead:
return;
case k_ESteamNetworkingConnectionState_FinWait:
case k_ESteamNetworkingConnectionState_ProblemDetectedLocally:
SendConnectionClosedOrNoConnection();
break;
case k_ESteamNetworkingConnectionState_Linger:
break;
case k_ESteamNetworkingConnectionState_Connecting:
case k_ESteamNetworkingConnectionState_Connected:
case k_ESteamNetworkingConnectionState_ClosedByPeer:
break;
}
}
#define ReportBadPacketIPv4( pszMsgType, /* fmt */ ... ) \
ReportBadPacketFrom( m_pSocket->GetRemoteHostAddr(), pszMsgType, __VA_ARGS__ )
void CSteamNetworkConnectionUDP::PacketReceived( const void *pvPkt, int cbPkt, const netadr_t &adrFrom, CSteamNetworkConnectionUDP *pSelf )
{
const uint8 *pPkt = static_cast<const uint8 *>( pvPkt );
SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp();
if ( cbPkt < 5 )
{
ReportBadPacket( "packet", "%d byte packet is too small", cbPkt );
return;
}