-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
net_ws.cpp
3465 lines (2863 loc) · 86.9 KB
/
net_ws.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. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
// net_ws.c
// Windows IP Support layer.
#include "tier0/etwprof.h"
#include "tier0/vprof.h"
#include "net_ws_headers.h"
#include "net_ws_queued_packet_sender.h"
#include "fmtstr.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define NET_COMPRESSION_STACKBUF_SIZE 4096
static ConVar net_showudp_wire( "net_showudp_wire", "0", 0, "Show incoming packet information" );
#define UDP_SO_RCVBUF_SIZE 131072
static ConVar net_udp_rcvbuf( "net_udp_rcvbuf", NETSTRING( UDP_SO_RCVBUF_SIZE ), FCVAR_ALLOWED_IN_COMPETITIVE, "Default UDP receive buffer size", true, 8192, true, 128 * 1024 );
static ConVar net_showsplits( "net_showsplits", "0", 0, "Show info about packet splits" );
static ConVar net_splitrate( "net_splitrate", "1", 0, "Number of fragments for a splitpacket that can be sent per frame" );
static ConVar ipname ( "ip", "localhost", FCVAR_ALLOWED_IN_COMPETITIVE, "Overrides IP for multihomed hosts" );
static ConVar hostport ( "hostport", NETSTRING( PORT_SERVER ) , FCVAR_ALLOWED_IN_COMPETITIVE, "Host game server port" );
static ConVar hostip ( "hostip", "", FCVAR_ALLOWED_IN_COMPETITIVE, "Host game server ip" );
static ConVar clientport ( "clientport", NETSTRING( PORT_CLIENT ), FCVAR_ALLOWED_IN_COMPETITIVE, "Host game client port" );
static ConVar hltvport ( "tv_port", NETSTRING( PORT_HLTV ), FCVAR_ALLOWED_IN_COMPETITIVE, "Host SourceTV port" );
static ConVar matchmakingport( "matchmakingport", NETSTRING( PORT_MATCHMAKING ), FCVAR_ALLOWED_IN_COMPETITIVE, "Host Matchmaking port" );
static ConVar systemlinkport( "systemlinkport", NETSTRING( PORT_SYSTEMLINK ), FCVAR_ALLOWED_IN_COMPETITIVE, "System Link port" );
static ConVar fakelag ( "net_fakelag", "0", FCVAR_CHEAT, "Lag all incoming network data (including loopback) by this many milliseconds." );
static ConVar fakeloss ( "net_fakeloss", "0", FCVAR_CHEAT, "Simulate packet loss as a percentage (negative means drop 1/n packets)" );
static ConVar droppackets ( "net_droppackets", "0", FCVAR_CHEAT, "Drops next n packets on client" );
static ConVar fakejitter ( "net_fakejitter", "0", FCVAR_CHEAT, "Jitter fakelag packet time" );
static ConVar net_compressvoice( "net_compressvoice", "0", 0, "Attempt to compress out of band voice payloads (360 only)." );
ConVar net_usesocketsforloopback( "net_usesocketsforloopback", "0", 0, "Use network sockets layer even for listen server local player's packets (multiplayer only)." );
#ifdef _DEBUG
static ConVar fakenoise ( "net_fakenoise", "0", FCVAR_CHEAT, "Simulate corrupt network packets (changes n bits per packet randomly)" );
static ConVar fakeshuffle ( "net_fakeshuffle", "0", FCVAR_CHEAT, "Shuffles order of every nth packet (needs net_fakelag)" );
static ConVar recvpackets ( "net_recvpackets", "-1", FCVAR_CHEAT, "Receive exactly next n packets if >= 0" );
static ConVar net_savelargesplits( "net_savelargesplits", "-1", 0, "If not -1, then if a split has this many or more split parts, save the entire packet to disc for analysis." );
#endif
#ifdef _X360
static void NET_LogServerCallback( IConVar *var, const char *pOldString, float flOldValue );
static ConVar net_logserver( "net_logserver", "0", 0, "Dump server stats to a file", NET_LogServerCallback );
static ConVar net_loginterval( "net_loginterval", "1", 0, "Time in seconds between server logs" );
#endif
//-----------------------------------------------------------------------------
// Toggle Xbox 360 network security to allow cross-platform testing
//-----------------------------------------------------------------------------
#if !defined( _X360 )
#define X360SecureNetwork() false
#define IPPROTO_VDP IPPROTO_UDP
#elif defined( _RETAIL )
#define X360SecureNetwork() true
#else
bool X360SecureNetwork( void )
{
if ( CommandLine()->FindParm( "-xnet_bypass_security" ) )
{
return false;
}
return true;
}
#endif
extern ConVar net_showudp;
extern ConVar net_showtcp;
extern ConVar net_blocksize;
extern ConVar host_timescale;
extern int host_framecount;
void NET_ClearQueuedPacketsForChannel( INetChannel *chan );
#define DEF_LOOPBACK_SIZE 2048
typedef struct
{
int nPort; // UDP/TCP use same port number
bool bListening; // true if TCP port is listening
int hUDP; // handle to UDP socket from socket()
int hTCP; // handle to TCP socket from socket()
} netsocket_t;
typedef struct
{
int newsock; // handle of new socket
int netsock; // handle of listen socket
float time;
netadr_t addr;
} pendingsocket_t;
#include "tier0/memdbgoff.h"
struct loopback_t
{
char *data; // loopback buffer
int datalen; // current data length
char defbuffer[ DEF_LOOPBACK_SIZE ];
DECLARE_FIXEDSIZE_ALLOCATOR( loopback_t );
};
#include "tier0/memdbgon.h"
DEFINE_FIXEDSIZE_ALLOCATOR( loopback_t, 2, CUtlMemoryPool::GROW_SLOW );
// Split long packets. Anything over 1460 is failing on some routers
typedef struct
{
int currentSequence;
int splitCount;
int totalSize;
int nExpectedSplitSize;
char buffer[ NET_MAX_MESSAGE ]; // This has to be big enough to hold the largest message
} LONGPACKET;
// Use this to pick apart the network stream, must be packed
#pragma pack(1)
typedef struct
{
int netID;
int sequenceNumber;
int packetID : 16;
int nSplitSize : 16;
} SPLITPACKET;
#pragma pack()
#define MIN_USER_MAXROUTABLE_SIZE 576 // ( X.25 Networks )
#define MAX_USER_MAXROUTABLE_SIZE MAX_ROUTABLE_PAYLOAD
#define MAX_SPLIT_SIZE (MAX_USER_MAXROUTABLE_SIZE - sizeof( SPLITPACKET ))
#define MIN_SPLIT_SIZE (MIN_USER_MAXROUTABLE_SIZE - sizeof( SPLITPACKET ))
// For metering out splitpackets, don't do them too fast as remote UDP socket will drop some payloads causing them to always fail to be reconstituted
// This problem is largely solved by increasing the buffer sizes for UDP sockets on Windows
#define SPLITPACKET_MAX_DATA_BYTES_PER_SECOND V_STRINGIFY(DEFAULT_RATE)
static ConVar sv_maxroutable
(
"sv_maxroutable",
"1260",
0,
"Server upper bound on net_maxroutable that a client can use.",
true, MIN_USER_MAXROUTABLE_SIZE,
true, MAX_USER_MAXROUTABLE_SIZE
);
ConVar net_maxroutable
(
"net_maxroutable",
"1260",
FCVAR_ARCHIVE | FCVAR_USERINFO,
"Requested max packet size before packets are 'split'.",
true, MIN_USER_MAXROUTABLE_SIZE,
true, MAX_USER_MAXROUTABLE_SIZE
);
netadr_t net_local_adr;
double net_time = 0.0f; // current time, updated each frame
static CUtlVector<netsocket_t> net_sockets; // the 4 sockets, Server, Client, HLTV, Matchmaking
static CUtlVector<netpacket_t> net_packets;
static bool net_multiplayer = false; // if true, configured for Multiplayer
static bool net_noip = false; // Disable IP support, can't switch to MP mode
static bool net_nodns = false; // Disable DNS request to avoid long timeouts
static bool net_notcp = true; // Disable TCP support
static bool net_nohltv = false; // disable HLTV support
static bool net_dedicated = false; // true is dedicated system
static int net_error = 0; // global error code updated with NET_GetLastError()
static CUtlVectorMT< CUtlVector< CNetChan* > > s_NetChannels;
static CUtlVectorMT< CUtlVector< pendingsocket_t > > s_PendingSockets;
CTSQueue<loopback_t *> s_LoopBacks[LOOPBACK_SOCKETS];
static netpacket_t* s_pLagData[MAX_SOCKETS]; // List of lag structures, if fakelag is set.
unsigned short NET_HostToNetShort( unsigned short us_in )
{
return htons( us_in );
}
unsigned short NET_NetToHostShort( unsigned short us_in )
{
return ntohs( us_in );
}
// This macro is used to capture the return value of a function call while recording
// a VCR file. During playback, it will get the return value out of the VCR file
// instead of actually calling the function.
#if !defined( NO_VCR )
#define VCR_NONPLAYBACKFN( call, resultVar, eventName ) \
{ \
if ( VCRGetMode() != VCR_Playback ) \
resultVar = call; \
\
VCRGenericValue( eventName, &resultVar, sizeof( resultVar ) ); \
}
#else
#define VCR_NONPLAYBACKFN( call, resultVar, eventName ) \
{ \
if ( VCRGetMode() != VCR_Playback ) \
resultVar = call; \
\
}
#endif
/*
====================
NET_ErrorString
====================
*/
const char *NET_ErrorString (int code)
{
#if defined( _WIN32 )
switch (code)
{
case WSAEINTR: return "WSAEINTR";
case WSAEBADF: return "WSAEBADF";
case WSAEACCES: return "WSAEACCES";
case WSAEDISCON: return "WSAEDISCON";
case WSAEFAULT: return "WSAEFAULT";
case WSAEINVAL: return "WSAEINVAL";
case WSAEMFILE: return "WSAEMFILE";
case WSAEWOULDBLOCK: return "WSAEWOULDBLOCK";
case WSAEINPROGRESS: return "WSAEINPROGRESS";
case WSAEALREADY: return "WSAEALREADY";
case WSAENOTSOCK: return "WSAENOTSOCK";
case WSAEDESTADDRREQ: return "WSAEDESTADDRREQ";
case WSAEMSGSIZE: return "WSAEMSGSIZE";
case WSAEPROTOTYPE: return "WSAEPROTOTYPE";
case WSAENOPROTOOPT: return "WSAENOPROTOOPT";
case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT";
case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT";
case WSAEOPNOTSUPP: return "WSAEOPNOTSUPP";
case WSAEPFNOSUPPORT: return "WSAEPFNOSUPPORT";
case WSAEAFNOSUPPORT: return "WSAEAFNOSUPPORT";
case WSAEADDRINUSE: return "WSAEADDRINUSE";
case WSAEADDRNOTAVAIL: return "WSAEADDRNOTAVAIL";
case WSAENETDOWN: return "WSAENETDOWN";
case WSAENETUNREACH: return "WSAENETUNREACH";
case WSAENETRESET: return "WSAENETRESET";
case WSAECONNABORTED: return "WSWSAECONNABORTEDAEINTR";
case WSAECONNRESET: return "WSAECONNRESET";
case WSAENOBUFS: return "WSAENOBUFS";
case WSAEISCONN: return "WSAEISCONN";
case WSAENOTCONN: return "WSAENOTCONN";
case WSAESHUTDOWN: return "WSAESHUTDOWN";
case WSAETOOMANYREFS: return "WSAETOOMANYREFS";
case WSAETIMEDOUT: return "WSAETIMEDOUT";
case WSAECONNREFUSED: return "WSAECONNREFUSED";
case WSAELOOP: return "WSAELOOP";
case WSAENAMETOOLONG: return "WSAENAMETOOLONG";
case WSAEHOSTDOWN: return "WSAEHOSTDOWN";
case WSASYSNOTREADY: return "WSASYSNOTREADY";
case WSAVERNOTSUPPORTED: return "WSAVERNOTSUPPORTED";
case WSANOTINITIALISED: return "WSANOTINITIALISED";
case WSAHOST_NOT_FOUND: return "WSAHOST_NOT_FOUND";
case WSATRY_AGAIN: return "WSATRY_AGAIN";
case WSANO_RECOVERY: return "WSANO_RECOVERY";
case WSANO_DATA: return "WSANO_DATA";
default: return "UNKNOWN ERROR";
}
#else
return strerror( code );
#endif
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *s -
// *sadr -
// Output : bool NET_StringToSockaddr
//-----------------------------------------------------------------------------
bool NET_StringToSockaddr( const char *s, struct sockaddr *sadr )
{
char *colon;
char copy[128];
Q_memset (sadr, 0, sizeof(*sadr));
((struct sockaddr_in *)sadr)->sin_family = AF_INET;
((struct sockaddr_in *)sadr)->sin_port = 0;
Q_strncpy (copy, s, sizeof( copy ) );
// strip off a trailing :port if present
for (colon = copy ; *colon ; colon++)
{
if (*colon == ':')
{
*colon = 0;
((struct sockaddr_in *)sadr)->sin_port = NET_HostToNetShort((short)atoi(colon+1));
}
}
if (copy[0] >= '0' && copy[0] <= '9' && Q_strstr( copy, "." ) )
{
*(int *)&((struct sockaddr_in *)sadr)->sin_addr = inet_addr(copy);
}
else
{
if ( net_nodns )
return false; // DNS names disabled
struct hostent *h;
if ( (h = gethostbyname(copy)) == NULL )
return false;
*(int *)&((struct sockaddr_in *)sadr)->sin_addr = *(int *)h->h_addr_list[0];
}
return true;
}
void NET_ClearLastError( void )
{
net_error = 0;
}
int NET_GetLastError( void )
{
#if defined( _WIN32 )
net_error = WSAGetLastError();
#else
net_error = errno;
#endif
#if !defined( NO_VCR )
VCRGenericValue( "WSAGetLastError", &net_error, sizeof( net_error ) );
#endif
return net_error;
}
/*
==================
NET_ClearLaggedList
==================
*/
void NET_ClearLaggedList(netpacket_t **pList)
{
netpacket_t * p = (*pList);
while ( p )
{
netpacket_t * n = p->pNext;
if ( p->data )
{
delete[] p->data;
p->data = NULL;
}
delete p;
p = n;
}
(*pList) = NULL;
}
void NET_ClearLagData( int sock )
{
if ( sock < MAX_SOCKETS && s_pLagData[sock] )
{
NET_ClearLaggedList( &s_pLagData[sock] );
}
}
/*
=============
NET_StringToAdr
localhost
idnewt
idnewt:28000
192.246.40.70
192.246.40.70:28000
=============
*/
bool NET_StringToAdr ( const char *s, netadr_t *a)
{
struct sockaddr saddr;
char address[128];
Q_strncpy( address, s, sizeof(address) );
if ( !Q_strncmp( address, "localhost", 10 ) || !Q_strncmp( address, "localhost:", 10 ) )
{
// subsitute 'localhost' with '127.0.0.1", both have 9 chars
// this way we can resolve 'localhost' without DNS and still keep the port
Q_memcpy( address, "127.0.0.1", 9 );
}
if ( !NET_StringToSockaddr (address, &saddr) )
return false;
a->SetFromSockadr( &saddr );
return true;
}
CNetChan *NET_FindNetChannel(int socket, netadr_t &adr)
{
AUTO_LOCK( s_NetChannels );
int numChannels = s_NetChannels.Count();
for ( int i = 0; i < numChannels; i++ )
{
CNetChan * chan = s_NetChannels[i];
// sockets must match
if ( socket != chan->GetSocket() )
continue;
// and the IP:Port address
if ( adr.CompareAdr( chan->GetRemoteAddress() ) )
{
return chan; // found it
}
}
return NULL; // no channel found
}
void NET_CloseSocket( int hSocket, int sock = -1)
{
if ( !hSocket )
return;
// close socket handle
int ret;
VCR_NONPLAYBACKFN( closesocket( hSocket ), ret, "closesocket" );
if ( ret == -1 )
{
NET_GetLastError();
ConMsg ("WARNING! NET_CloseSocket: %s\n", NET_ErrorString(net_error));
}
// if hSocket mapped to hTCP, clear hTCP
if ( sock >= 0 )
{
if ( net_sockets[sock].hTCP == hSocket )
{
net_sockets[sock].hTCP = 0;
net_sockets[sock].bListening = false;
}
}
}
/*
====================
NET_IPSocket
====================
*/
int NET_OpenSocket ( const char *net_interface, int& port, int protocol )
{
struct sockaddr_in address;
unsigned int opt;
int newsocket = -1;
if ( protocol == IPPROTO_TCP )
{
VCR_NONPLAYBACKFN( socket (PF_INET, SOCK_STREAM, IPPROTO_TCP), newsocket, "socket()" );
}
else // as UDP or VDP
{
VCR_NONPLAYBACKFN( socket (PF_INET, SOCK_DGRAM, protocol), newsocket, "socket()" );
}
if ( newsocket == -1 )
{
NET_GetLastError();
if ( net_error != WSAEAFNOSUPPORT )
Msg ("WARNING: NET_OpenSockett: socket failed: %s", NET_ErrorString(net_error));
return 0;
}
opt = 1; // make it non-blocking
int ret;
VCR_NONPLAYBACKFN( ioctlsocket (newsocket, FIONBIO, (unsigned long*)&opt), ret, "ioctlsocket" );
if ( ret == -1 )
{
NET_GetLastError();
Msg ("WARNING: NET_OpenSocket: ioctl FIONBIO: %s\n", NET_ErrorString(net_error) );
}
if ( protocol == IPPROTO_TCP )
{
if ( !IsX360() ) // SO_KEEPALIVE unsupported on the 360
{
opt = 1; // set TCP options: keep TCP connection alive
VCR_NONPLAYBACKFN( setsockopt(newsocket, SOL_SOCKET, SO_KEEPALIVE, (char *)&opt, sizeof(opt)), ret, "setsockopt" );
if (ret == -1)
{
NET_GetLastError();
Msg ("WARNING: NET_OpenSocket: setsockopt SO_KEEPALIVE: %s\n", NET_ErrorString(net_error));
return 0;
}
}
linger optlinger; // set TCP options: Does not block close waiting for unsent data to be sent
optlinger.l_linger = 0;
optlinger.l_onoff = 0;
VCR_NONPLAYBACKFN( setsockopt(newsocket, SOL_SOCKET, SO_LINGER, (char *)&optlinger, sizeof(optlinger)), ret, "setsockopt" );
if (ret == -1)
{
NET_GetLastError();
Msg ("WARNING: NET_OpenSocket: setsockopt SO_LINGER: %s\n", NET_ErrorString(net_error));
return 0;
}
opt = 1; // set TCP options: Disables the Nagle algorithm for send coalescing.
VCR_NONPLAYBACKFN( setsockopt(newsocket, IPPROTO_TCP, TCP_NODELAY, (char *)&opt, sizeof(opt)), ret, "setsockopt" );
if (ret == -1)
{
NET_GetLastError();
Msg ("WARNING: NET_OpenSocket: setsockopt TCP_NODELAY: %s\n", NET_ErrorString(net_error));
return 0;
}
opt = NET_MAX_MESSAGE; // set TCP options: set send buffer size
VCR_NONPLAYBACKFN( setsockopt(newsocket, SOL_SOCKET, SO_SNDBUF, (char *)&opt, sizeof(opt)), ret, "setsockopt" );
if (ret == -1)
{
NET_GetLastError();
Msg ("WARNING: NET_OpenSocket: setsockopt SO_SNDBUF: %s\n", NET_ErrorString(net_error));
return 0;
}
opt = NET_MAX_MESSAGE; // set TCP options: set receive buffer size
VCR_NONPLAYBACKFN( setsockopt(newsocket, SOL_SOCKET, SO_RCVBUF, (char *)&opt, sizeof(opt)), ret, "setsockopt" );
if (ret == -1)
{
NET_GetLastError();
Msg ("WARNING: NET_OpenSocket: setsockopt SO_RCVBUF: %s\n", NET_ErrorString(net_error));
return 0;
}
return newsocket; // don't bind TCP sockets by default
}
// rest is UDP only
opt = 0;
socklen_t len = sizeof( opt );
VCR_NONPLAYBACKFN( getsockopt( newsocket, SOL_SOCKET, SO_RCVBUF, (char *)&opt, &len ), ret, "getsockopt" );
if ( ret == -1 )
{
NET_GetLastError();
Msg ("WARNING: NET_OpenSocket: getsockopt SO_RCVBUF: %s\n", NET_ErrorString(net_error));
return 0;
}
if ( net_showudp.GetBool() )
{
static bool bFirst = true;
if ( bFirst )
{
Msg( "UDP socket SO_RCVBUF size %d bytes, changing to %d\n", opt, net_udp_rcvbuf.GetInt() );
}
bFirst = false;
}
opt = net_udp_rcvbuf.GetInt(); // set UDP receive buffer size
VCR_NONPLAYBACKFN( setsockopt(newsocket, SOL_SOCKET, SO_RCVBUF, (char *)&opt, sizeof(opt)), ret, "setsockopt" );
if (ret == -1)
{
NET_GetLastError();
Msg ("WARNING: NET_OpenSocket: setsockopt SO_RCVBUF: %s\n", NET_ErrorString(net_error));
return 0;
}
opt = net_udp_rcvbuf.GetInt(); // set UDP send buffer size
VCR_NONPLAYBACKFN( setsockopt(newsocket, SOL_SOCKET, SO_SNDBUF, (char *)&opt, sizeof(opt)), ret, "setsockopt" );
if (ret == -1)
{
NET_GetLastError();
Msg ("WARNING: NET_OpenSocket: setsockopt SO_SNDBUF: %s\n", NET_ErrorString(net_error));
return 0;
}
// VDP protocol (Xbox 360 secure network) doesn't support SO_BROADCAST
if ( !X360SecureNetwork() || protocol != IPPROTO_VDP )
{
opt = 1; // set UDP options: make it broadcast capable
VCR_NONPLAYBACKFN( setsockopt(newsocket, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt)), ret, "setsockopt" );
if (ret == -1)
{
NET_GetLastError();
Msg ("WARNING: NET_OpenSocket: setsockopt SO_BROADCAST: %s\n", NET_ErrorString(net_error));
return 0;
}
}
if ( CommandLine()->FindParm( "-reuse" ) )
{
opt = 1; // make it reusable
VCR_NONPLAYBACKFN( setsockopt(newsocket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)), ret, "setsockopt" );
if (ret == -1)
{
NET_GetLastError();
Msg ("WARNING: NET_OpenSocket: setsockopt SO_REUSEADDR: %s\n", NET_ErrorString(net_error));
return 0;
}
}
if (!net_interface || !net_interface[0] || !Q_strcmp(net_interface, "localhost"))
{
address.sin_addr.s_addr = INADDR_ANY;
}
else
{
NET_StringToSockaddr (net_interface, (struct sockaddr *)&address);
}
address.sin_family = AF_INET;
int port_offset; // try binding socket to port, try next 10 is port is already used
for ( port_offset = 0; port_offset < PORT_TRY_MAX; port_offset++ )
{
if ( port == PORT_ANY )
{
address.sin_port = 0; // = INADDR_ANY
}
else
{
address.sin_port = NET_HostToNetShort((short)( port + port_offset ));
}
VCR_NONPLAYBACKFN( bind (newsocket, (struct sockaddr *)&address, sizeof(address)), ret, "bind" );
if ( ret != -1 )
{
if ( port != PORT_ANY && port_offset != 0 )
{
port += port_offset; // update port
ConDMsg( "Socket bound to non-default port %i because original port was already in use.\n", port );
}
break;
}
NET_GetLastError();
if ( port == PORT_ANY || net_error != WSAEADDRINUSE )
{
Msg ("WARNING: NNET_OpenSocket: bind: %s\n", NET_ErrorString(net_error));
NET_CloseSocket(newsocket,-1);
return 0;
}
// Try next port
}
const bool bStrictBind = CommandLine()->FindParm( "-strictportbind" );
if ( port_offset == PORT_TRY_MAX && !bStrictBind )
{
Msg( "WARNING: UDP_OpenSocket: unable to bind socket\n" );
NET_CloseSocket( newsocket,-1 );
return 0;
}
if ( port_offset > 0 )
{
if ( bStrictBind )
{
// The server op wants to exit if the desired port was not avialable.
Sys_Exit( "ERROR: Port %i was unavailable - quitting due to \"-strictportbind\" command-line flag!\n", port - port_offset );
}
else
{
Warning( "WARNING: Port %i was unavailable - bound to port %i instead\n", port - port_offset, port );
}
}
return newsocket;
}
int NET_ConnectSocket( int sock, const netadr_t &addr )
{
Assert( (sock >= 0) && (sock < net_sockets.Count()) );
netsocket_t *netsock = &net_sockets[sock];
if ( netsock->hTCP )
{
NET_CloseSocket( netsock->hTCP, sock );
}
if ( net_notcp )
return 0;
sockaddr saddr;
addr.ToSockadr( &saddr );
int anyport = PORT_ANY;
netsock->hTCP = NET_OpenSocket( ipname.GetString(), anyport, true );
if ( !netsock->hTCP )
{
Msg( "Warning! NET_ConnectSocket failed opening socket %i, port %i.\n", sock, net_sockets[sock].nPort );
return false;
}
int ret;
VCR_NONPLAYBACKFN( connect( netsock->hTCP, &saddr, sizeof(saddr) ), ret, "connect" );
if ( ret == -1 )
{
NET_GetLastError();
if ( net_error != WSAEWOULDBLOCK )
{
Msg ("NET_ConnectSocket: %s\n", NET_ErrorString( net_error ) );
return 0;
}
}
return net_sockets[sock].hTCP;
}
int NET_SendStream( int nSock, const char * buf, int len, int flags )
{
//int ret = send( nSock, buf, len, flags );
int ret = VCRHook_send( nSock, buf, len, flags );
if ( ret == -1 )
{
NET_GetLastError();
if ( net_error == WSAEWOULDBLOCK )
{
return 0; // ignore EWOULDBLOCK
}
Msg ("NET_SendStream: %s\n", NET_ErrorString( net_error ) );
}
return ret;
}
int NET_ReceiveStream( int nSock, char * buf, int len, int flags )
{
int ret = VCRHook_recv( nSock, buf, len, flags );
if ( ret == -1 )
{
NET_GetLastError();
if ( net_error == WSAEWOULDBLOCK ||
net_error == WSAENOTCONN )
{
return 0; // ignore EWOULDBLOCK
}
Msg ("NET_ReceiveStream: %s\n", NET_ErrorString( net_error ) );
}
return ret;
}
INetChannel *NET_CreateNetChannel(int socket, netadr_t *adr, const char * name, INetChannelHandler * handler, bool bForceNewChannel/*=false*/,
int nProtocolVersion/*=PROTOCOL_VERSION*/)
{
CNetChan *chan = NULL;
if ( !bForceNewChannel && adr != NULL )
{
// try to find real network channel if already existing
if ( ( chan = NET_FindNetChannel( socket, *adr ) ) != NULL )
{
// channel already known, clear any old stuff before Setup wipes all
chan->Clear();
}
}
if ( !chan )
{
// create new channel
chan = new CNetChan();
AUTO_LOCK( s_NetChannels );
s_NetChannels.AddToTail( chan );
}
NET_ClearLagData( socket );
// just reset and return
chan->Setup( socket, adr, name, handler, nProtocolVersion );
return chan;
}
void NET_RemoveNetChannel(INetChannel *netchan, bool bDeleteNetChan)
{
if ( !netchan )
{
return;
}
AUTO_LOCK( s_NetChannels );
if ( s_NetChannels.Find( static_cast<CNetChan*>(netchan) ) == s_NetChannels.InvalidIndex() )
{
DevMsg(1, "NET_CloseNetChannel: unknown channel.\n");
return;
}
s_NetChannels.FindAndRemove( static_cast<CNetChan*>(netchan) );
NET_ClearQueuedPacketsForChannel( netchan );
if ( bDeleteNetChan )
delete netchan;
}
/*
=============================================================================
LOOPBACK BUFFERS FOR LOCAL PLAYER
=============================================================================
*/
void NET_SendLoopPacket (int sock, int length, const unsigned char *data, const netadr_t &to)
{
loopback_t *loop;
if ( length > NET_MAX_PAYLOAD )
{
DevMsg( "NET_SendLoopPacket: packet too big (%i).\n", length );
return;
}
loop = new loopback_t;
if ( length <= DEF_LOOPBACK_SIZE )
{
loop->data = loop->defbuffer;
}
else
{
loop->data = new char[ length ];
}
Q_memcpy (loop->data, data, length);
loop->datalen = length;
if ( sock == NS_SERVER )
{
s_LoopBacks[NS_CLIENT].PushItem( loop );
}
else if ( sock == NS_CLIENT )
{
s_LoopBacks[NS_SERVER].PushItem( loop );
}
else
{
DevMsg( "NET_SendLoopPacket: invalid socket (%i).\n", sock );
return;
}
}
//=============================================================================
int NET_CountLaggedList( netpacket_t *pList )
{
int c = 0;
netpacket_t *p = pList;
while ( p )
{
c++;
p = p->pNext;
}
return c;
}
/*
===================
NET_AddToLagged
===================
*/
void NET_AddToLagged( netpacket_t **pList, netpacket_t *pPacket )
{
if ( pPacket->pNext )
{
Msg("NET_AddToLagged::Packet already linked\n");
return;
}
// first copy packet
netpacket_t *newPacket = new netpacket_t;
(*newPacket) = (*pPacket); // copy packet infos
newPacket->data = new unsigned char[ pPacket->size ]; // create new data buffer
Q_memcpy( newPacket->data, pPacket->data, pPacket->size ); // copy packet data
newPacket->pNext = NULL;
// if list is empty, this is our first element
if ( (*pList) == NULL )
{
(*pList) = newPacket; // put packet in top of list
}
else
{
netpacket_t *last = (*pList);
while ( last->pNext )
{
// got to end of list
last = last->pNext;
}
// add at end
last->pNext = newPacket;
}
}
// Actual lag to use in msec
static float s_FakeLag = 0.0;
float NET_GetFakeLag()
{
return s_FakeLag;
}
// How quickly we converge to a new value for fakelag
#define FAKELAG_CONVERGE 200 // ms per second
/*
==============================
NET_AdjustLag
==============================
*/
void NET_AdjustLag( void )
{
static double s_LastTime = 0;
// Bound time step
float dt = net_time - s_LastTime;
dt = clamp( dt, 0.0f, 0.2f );
s_LastTime = net_time;
// Already converged?
if ( fakelag.GetFloat() == s_FakeLag )
return;
// Figure out how far we have to go
float diff = fakelag.GetFloat() - s_FakeLag;
// How much can we converge this frame
float converge = FAKELAG_CONVERGE * dt;
// Last step, go the whole way
if ( converge > fabs( diff ) )
{
converge = fabs( diff );
}
// Converge toward fakelag.GetFloat()
if ( diff < 0.0 )
{
// Converge toward fakelag.GetFloat()
s_FakeLag -= converge;
}
else
{
s_FakeLag += converge;
}
}
bool NET_LagPacket (bool newdata, netpacket_t * packet)