]> icculus.org git repositories - divverent/darkplaces.git/blob - netconn.c
add a "freeslots" field to the host cache
[divverent/darkplaces.git] / netconn.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
5
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
15 See the GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20
21 */
22
23 #include "quakedef.h"
24 #include "lhnet.h"
25
26 #define QWMASTER_PORT 27000
27 #define DPMASTER_PORT 27950
28
29 // note this defaults on for dedicated servers, off for listen servers
30 cvar_t sv_public = {0, "sv_public", "0", "1: advertises this server on the master server (so that players can find it in the server browser); 0: allow direct queries only; -1: do not respond to direct queries; -2: do not allow anyone to connect"};
31 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120", "how often to send heartbeat in seconds (only used if sv_public is 1)"};
32
33 static cvar_t sv_masters [] =
34 {
35         {CVAR_SAVE, "sv_master1", "", "user-chosen master server 1"},
36         {CVAR_SAVE, "sv_master2", "", "user-chosen master server 2"},
37         {CVAR_SAVE, "sv_master3", "", "user-chosen master server 3"},
38         {CVAR_SAVE, "sv_master4", "", "user-chosen master server 4"},
39         {0, "sv_masterextra1", "ghdigital.com", "default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
40         {0, "sv_masterextra2", "dpmaster.deathmask.net", "default master server 2 (admin: Willis)"}, // admin: Willis
41         {0, "sv_masterextra3", "excalibur.nvg.ntnu.no", "default master server 3 (admin: tChr)"}, // admin: tChr
42         {0, NULL, NULL, NULL}
43 };
44
45 static cvar_t sv_qwmasters [] =
46 {
47         {CVAR_SAVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"},
48         {CVAR_SAVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"},
49         {CVAR_SAVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"},
50         {CVAR_SAVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"},
51         {0, "sv_qwmasterextra1", "192.246.40.37:27000", "id Limbo (admin: id Software)"},
52         {0, "sv_qwmasterextra2", "192.246.40.37:27002", "id CTF (admin: id Software)"},
53         {0, "sv_qwmasterextra3", "192.246.40.37:27003", "id TeamFortress (admin: id Software)"},
54         {0, "sv_qwmasterextra4", "192.246.40.37:27004", "id Miscilaneous (admin: id Software)"},
55         {0, "sv_qwmasterextra5", "192.246.40.37:27006", "id Deathmatch Only (admin: id Software)"},
56         {0, "sv_qwmasterextra6", "150.254.66.120:27000", "Poland's master server. (admin: unknown)"},
57         {0, "sv_qwmasterextra7", "62.112.145.129:27000", "Ocrana master server. (admin: unknown)"},
58         {0, "sv_qwmasterextra8", "master.edome.net", "edome master server. (admin: unknown)"},
59         {0, "sv_qwmasterextra9", "qwmaster.barrysworld.com", "barrysworld master server. (admin: unknown)"},
60         {0, "sv_qwmasterextra10", "qwmaster.ocrana.de:27000", "Ocrana2 master server. (admin: unknown)"},
61         {0, "sv_qwmasterextra11", "213.221.174.165:27000", "unknown1 master server. (admin: unknown)"},
62         {0, "sv_qwmasterextra12", "195.74.0.8", "unknown2 master server. (admin: unknown)"},
63         {0, "sv_qwmasterextra13", "204.182.161.2", "unknown3 master server. (admin: unknown)"},
64         {0, NULL, NULL, NULL}
65 };
66
67 static double nextheartbeattime = 0;
68
69 sizebuf_t net_message;
70 static unsigned char net_message_buf[NET_MAXMESSAGE];
71
72 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
73 cvar_t net_connecttimeout = {0, "net_connecttimeout","10", "after requesting a connection, the client must reply within this many seconds or be dropped (cuts down on connect floods)"};
74 cvar_t net_connectfloodblockingtimeout = {0, "net_connectfloodblockingtimeout", "5", "when a connection packet is received, it will block all future connect packets from that IP address for this many seconds (cuts down on connect floods)"};
75 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
76 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
77
78 cvar_t cl_netlocalping = {0, "cl_netlocalping","0", "lags local loopback connection by this much ping time (useful to play more fairly on your own server with people with higher pings)"};
79 static cvar_t cl_netpacketloss_send = {0, "cl_netpacketloss_send","0", "drops this percentage of outgoing packets, useful for testing network protocol robustness (jerky movement, prediction errors, etc)"};
80 static cvar_t cl_netpacketloss_receive = {0, "cl_netpacketloss_receive","0", "drops this percentage of incoming packets, useful for testing network protocol robustness (jerky movement, effects failing to start, sounds failing to play, etc)"};
81 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
82 static cvar_t net_slist_queriesperframe = {0, "net_slist_queriesperframe", "4", "maximum number of server information requests to send each rendered frame (guards against low framerates causing problems)"};
83 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
84 static cvar_t net_slist_maxtries = {0, "net_slist_maxtries", "3", "how many times to ask the same server for information (more times gives better ping reports but takes longer)"};
85
86 static cvar_t gameversion = {0, "gameversion", "0", "version of game data (mod-specific), when client and server gameversion mismatch in the server browser the server is shown as incompatible"};
87
88 /* statistic counters */
89 static int packetsSent = 0;
90 static int packetsReSent = 0;
91 static int packetsReceived = 0;
92 static int receivedDuplicateCount = 0;
93 static int droppedDatagrams = 0;
94
95 static int unreliableMessagesSent = 0;
96 static int unreliableMessagesReceived = 0;
97 static int reliableMessagesSent = 0;
98 static int reliableMessagesReceived = 0;
99
100 double masterquerytime = -1000;
101 int masterquerycount = 0;
102 int masterreplycount = 0;
103 int serverquerycount = 0;
104 int serverreplycount = 0;
105
106 // this is only false if there are still servers left to query
107 static qboolean serverlist_querysleep = true;
108 // this is pushed a second or two ahead of realtime whenever a master server
109 // reply is received, to avoid issuing queries while master replies are still
110 // flooding in (which would make a mess of the ping times)
111 static double serverlist_querywaittime = 0;
112
113 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
114 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
115
116 static int cl_numsockets;
117 static lhnetsocket_t *cl_sockets[16];
118 static int sv_numsockets;
119 static lhnetsocket_t *sv_sockets[16];
120
121 netconn_t *netconn_list = NULL;
122 mempool_t *netconn_mempool = NULL;
123
124 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
125 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
126 cvar_t net_address = {0, "net_address", "0.0.0.0", "network address to open ports on"};
127 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]", "network address to open ipv6 ports on"};
128
129 char net_extresponse[NET_EXTRESPONSE_MAX][1400];
130 int net_extresponse_count = 0;
131 int net_extresponse_last = 0;
132
133 // ServerList interface
134 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
135 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
136
137 serverlist_infofield_t serverlist_sortbyfield;
138 qboolean serverlist_sortdescending;
139
140 int serverlist_viewcount = 0;
141 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
142
143 int serverlist_cachecount;
144 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
145
146 qboolean serverlist_consoleoutput;
147
148 // helper function to insert a value into the viewset
149 // spare entries will be removed
150 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
151 {
152     int i;
153         if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
154                 i = serverlist_viewcount++;
155         } else {
156                 i = SERVERLIST_VIEWLISTSIZE - 1;
157         }
158
159         for( ; i > index ; i-- )
160                 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
161
162         serverlist_viewlist[index] = entry;
163 }
164
165 // we suppose serverlist_viewcount to be valid, ie > 0
166 static void _ServerList_ViewList_Helper_Remove( int index )
167 {
168         serverlist_viewcount--;
169         for( ; index < serverlist_viewcount ; index++ )
170                 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
171 }
172
173 // returns true if A should be inserted before B
174 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
175 {
176         int result = 0; // > 0 if for numbers A > B and for text if A < B
177
178         switch( serverlist_sortbyfield ) {
179                 case SLIF_PING:
180                         result = A->info.ping - B->info.ping;
181                         break;
182                 case SLIF_MAXPLAYERS:
183                         result = A->info.maxplayers - B->info.maxplayers;
184                         break;
185                 case SLIF_NUMPLAYERS:
186                         result = A->info.numplayers - B->info.numplayers;
187                         break;
188                 case SLIF_NUMBOTS:
189                         result = A->info.numbots - B->info.numbots;
190                         break;
191                 case SLIF_NUMHUMANS:
192                         result = A->info.numhumans - B->info.numhumans;
193                         break;
194                 case SLIF_FREESLOTS:
195                         result = A->info.freeslots - B->info.freeslots;
196                         break;
197                 case SLIF_PROTOCOL:
198                         result = A->info.protocol - B->info.protocol;
199                         break;
200                 case SLIF_CNAME:
201                         result = strcmp( B->info.cname, A->info.cname );
202                         break;
203                 case SLIF_GAME:
204                         result = strcmp( B->info.game, A->info.game );
205                         break;
206                 case SLIF_MAP:
207                         result = strcmp( B->info.map, A->info.map );
208                         break;
209                 case SLIF_MOD:
210                         result = strcmp( B->info.mod, A->info.mod );
211                         break;
212                 case SLIF_NAME:
213                         result = strcmp( B->info.name, A->info.name );
214                         break;
215                 default:
216                         Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
217                         break;
218         }
219
220         if( serverlist_sortdescending )
221                 return result > 0;
222         if (result != 0)
223                 return result < 0;
224         // if the chosen sort key is identical, sort by index
225         // (makes this a stable sort, so that later replies from servers won't
226         //  shuffle the servers around when they have the same ping)
227         return A < B;
228 }
229
230 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
231 {
232         // This should actually be done with some intermediate and end-of-function return
233         switch( op ) {
234                 case SLMO_LESS:
235                         return A < B;
236                 case SLMO_LESSEQUAL:
237                         return A <= B;
238                 case SLMO_EQUAL:
239                         return A == B;
240                 case SLMO_GREATER:
241                         return A > B;
242                 case SLMO_NOTEQUAL:
243                         return A != B;
244                 case SLMO_GREATEREQUAL:
245                 case SLMO_CONTAINS:
246                 case SLMO_NOTCONTAIN:
247                         return A >= B;
248                 default:
249                         Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
250                         return false;
251         }
252 }
253
254 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
255 {
256         int i;
257         char bufferA[ 256 ], bufferB[ 256 ]; // should be more than enough
258         for (i = 0;i < (int)sizeof(bufferA)-1 && A[i];i++)
259                 bufferA[i] = (A[i] >= 'A' && A[i] <= 'Z') ? (A[i] + 'a' - 'A') : A[i];
260         bufferA[i] = 0;
261         for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
262                 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
263         bufferB[i] = 0;
264
265         // Same here, also using an intermediate & final return would be more appropriate
266         // A info B mask
267         switch( op ) {
268                 case SLMO_CONTAINS:
269                         return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
270                 case SLMO_NOTCONTAIN:
271                         return !*bufferB || !strstr( bufferA, bufferB );
272                 case SLMO_LESS:
273                         return strcmp( bufferA, bufferB ) < 0;
274                 case SLMO_LESSEQUAL:
275                         return strcmp( bufferA, bufferB ) <= 0;
276                 case SLMO_EQUAL:
277                         return strcmp( bufferA, bufferB ) == 0;
278                 case SLMO_GREATER:
279                         return strcmp( bufferA, bufferB ) > 0;
280                 case SLMO_NOTEQUAL:
281                         return strcmp( bufferA, bufferB ) != 0;
282                 case SLMO_GREATEREQUAL:
283                         return strcmp( bufferA, bufferB ) >= 0;
284                 default:
285                         Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
286                         return false;
287         }
288 }
289
290 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
291 {
292         if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
293                 return false;
294         if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
295                 return false;
296         if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
297                 return false;
298         if( !_ServerList_CompareInt( info->numbots, mask->tests[SLIF_NUMBOTS], mask->info.numbots ) )
299                 return false;
300         if( !_ServerList_CompareInt( info->numhumans, mask->tests[SLIF_NUMHUMANS], mask->info.numhumans ) )
301                 return false;
302         if( !_ServerList_CompareInt( info->freeslots, mask->tests[SLIF_FREESLOTS], mask->info.freeslots ) )
303                 return false;
304         if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
305                 return false;
306         if( *mask->info.cname
307                 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
308                 return false;
309         if( *mask->info.game
310                 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
311                 return false;
312         if( *mask->info.mod
313                 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
314                 return false;
315         if( *mask->info.map
316                 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
317                 return false;
318         if( *mask->info.name
319                 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
320                 return false;
321         return true;
322 }
323
324 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
325 {
326         int start, end, mid;
327
328         // reject incompatible servers
329         if (entry->info.gameversion != gameversion.integer)
330                 return;
331
332         // FIXME: change this to be more readable (...)
333         // now check whether it passes through the masks
334         for( start = 0 ; serverlist_andmasks[start].active && start < SERVERLIST_ANDMASKCOUNT ; start++ )
335                 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
336                         return;
337
338         for( start = 0 ; serverlist_ormasks[start].active && start < SERVERLIST_ORMASKCOUNT ; start++ )
339                 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
340                         break;
341         if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
342                 return;
343
344         if( !serverlist_viewcount ) {
345                 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
346                 return;
347         }
348         // ok, insert it, we just need to find out where exactly:
349
350         // two special cases
351         // check whether to insert it as new first item
352         if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
353                 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
354                 return;
355         } // check whether to insert it as new last item
356         else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
357                 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
358                 return;
359         }
360         start = 0;
361         end = serverlist_viewcount - 1;
362         while( end > start + 1 )
363         {
364                 mid = (start + end) / 2;
365                 // test the item that lies in the middle between start and end
366                 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
367                         // the item has to be in the upper half
368                         end = mid;
369                 else
370                         // the item has to be in the lower half
371                         start = mid;
372         }
373         _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
374 }
375
376 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
377 {
378         int i;
379         for( i = 0; i < serverlist_viewcount; i++ )
380         {
381                 if (serverlist_viewlist[i] == entry)
382                 {
383                         _ServerList_ViewList_Helper_Remove(i);
384                         break;
385                 }
386         }
387 }
388
389 void ServerList_RebuildViewList(void)
390 {
391         int i;
392
393         serverlist_viewcount = 0;
394         for( i = 0 ; i < serverlist_cachecount ; i++ )
395                 if( serverlist_cache[i].query == SQS_QUERIED )
396                         ServerList_ViewList_Insert( &serverlist_cache[i] );
397 }
398
399 void ServerList_ResetMasks(void)
400 {
401         int i;
402
403         memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
404         memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
405         // numbots needs to be compared to -1 to always succeed
406         for(i = 0; i < SERVERLIST_ANDMASKCOUNT; ++i)
407                 serverlist_andmasks[i].info.numbots = -1;
408         for(i = 0; i < SERVERLIST_ORMASKCOUNT; ++i)
409                 serverlist_ormasks[i].info.numbots = -1;
410 }
411
412 #if 0
413 static void _ServerList_Test(void)
414 {
415         int i;
416         for( i = 0 ; i < 1024 ; i++ ) {
417                 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
418                 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
419                 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
420                 serverlist_cache[serverlist_cachecount].finished = true;
421                 sprintf( serverlist_cache[serverlist_cachecount].line1, "%i %s", serverlist_cache[serverlist_cachecount].info.ping, serverlist_cache[serverlist_cachecount].info.name );
422                 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
423                 serverlist_cachecount++;
424         }
425 }
426 #endif
427
428 void ServerList_QueryList(qboolean querydp, qboolean queryqw)
429 {
430         masterquerytime = realtime;
431         masterquerycount = 0;
432         masterreplycount = 0;
433         serverquerycount = 0;
434         serverreplycount = 0;
435         serverlist_cachecount = 0;
436         serverlist_viewcount = 0;
437         serverlist_consoleoutput = false;
438
439         //_ServerList_Test();
440
441         NetConn_QueryMasters(querydp, queryqw);
442 }
443
444 // rest
445
446 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
447 {
448         int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
449         int i;
450         if (length == 0)
451                 return 0;
452         if (cl_netpacketloss_receive.integer)
453                 for (i = 0;i < cl_numsockets;i++)
454                         if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_receive.integer)
455                                 return 0;
456         if (developer_networking.integer)
457         {
458                 char addressstring[128], addressstring2[128];
459                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
460                 if (length > 0)
461                 {
462                         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
463                         Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
464                         Com_HexDumpToConsole((unsigned char *)data, length);
465                 }
466                 else
467                         Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
468         }
469         return length;
470 }
471
472 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
473 {
474         int ret;
475         int i;
476         if (cl_netpacketloss_send.integer)
477                 for (i = 0;i < cl_numsockets;i++)
478                         if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_send.integer)
479                                 return length;
480         ret = LHNET_Write(mysocket, data, length, peeraddress);
481         if (developer_networking.integer)
482         {
483                 char addressstring[128], addressstring2[128];
484                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
485                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
486                 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
487                 Com_HexDumpToConsole((unsigned char *)data, length);
488         }
489         return ret;
490 }
491
492 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
493 {
494         // note this does not include the trailing NULL because we add that in the parser
495         return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
496 }
497
498 qboolean NetConn_CanSend(netconn_t *conn)
499 {
500         conn->outgoing_packetcounter = (conn->outgoing_packetcounter + 1) % NETGRAPH_PACKETS;
501         conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
502         conn->outgoing_reliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
503         conn->outgoing_acksize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
504         if (realtime > conn->cleartime)
505                 return true;
506         else
507         {
508                 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_CHOKEDPACKET;
509                 return false;
510         }
511 }
512
513 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate, qboolean quakesignon_suppressreliables)
514 {
515         int totallen = 0;
516
517         // if this packet was supposedly choked, but we find ourselves sending one
518         // anyway, make sure the size counting starts at zero
519         // (this mostly happens on level changes and disconnects and such)
520         if (conn->outgoing_unreliablesize[conn->outgoing_packetcounter] == NETGRAPH_CHOKEDPACKET)
521                 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
522
523         if (protocol == PROTOCOL_QUAKEWORLD)
524         {
525                 int packetLen;
526                 qboolean sendreliable;
527
528                 // note that it is ok to send empty messages to the qw server,
529                 // otherwise it won't respond to us at all
530
531                 sendreliable = false;
532                 // if the remote side dropped the last reliable message, resend it
533                 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
534                         sendreliable = true;
535                 // if the reliable transmit buffer is empty, copy the current message out
536                 if (!conn->sendMessageLength && conn->message.cursize)
537                 {
538                         memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
539                         conn->sendMessageLength = conn->message.cursize;
540                         SZ_Clear(&conn->message); // clear the message buffer
541                         conn->qw.reliable_sequence ^= 1;
542                         sendreliable = true;
543                 }
544                 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
545                 *((int *)(sendbuffer + 0)) = LittleLong((unsigned int)conn->qw.outgoing_sequence | ((unsigned int)sendreliable<<31));
546                 // last received unreliable packet number, and last received reliable packet number (0 or 1)
547                 *((int *)(sendbuffer + 4)) = LittleLong((unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
548                 packetLen = 8;
549                 conn->qw.outgoing_sequence++;
550                 // client sends qport in every packet
551                 if (conn == cls.netcon)
552                 {
553                         *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
554                         packetLen += 2;
555                         // also update cls.qw_outgoing_sequence
556                         cls.qw_outgoing_sequence = conn->qw.outgoing_sequence;
557                 }
558                 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
559                 {
560                         Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
561                         return -1;
562                 }
563
564                 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
565
566                 // add the reliable message if there is one
567                 if (sendreliable)
568                 {
569                         conn->outgoing_reliablesize[conn->outgoing_packetcounter] += conn->sendMessageLength;
570                         memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
571                         packetLen += conn->sendMessageLength;
572                         conn->qw.last_reliable_sequence = conn->qw.outgoing_sequence;
573                 }
574
575                 // add the unreliable message if possible
576                 if (packetLen + data->cursize <= 1400)
577                 {
578                         conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += data->cursize;
579                         memcpy(sendbuffer + packetLen, data->data, data->cursize);
580                         packetLen += data->cursize;
581                 }
582
583                 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
584
585                 packetsSent++;
586                 unreliableMessagesSent++;
587
588                 totallen += packetLen + 28;
589         }
590         else
591         {
592                 unsigned int packetLen;
593                 unsigned int dataLen;
594                 unsigned int eom;
595                 unsigned int *header;
596
597                 // if a reliable message fragment has been lost, send it again
598                 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
599                 {
600                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
601                         {
602                                 dataLen = conn->sendMessageLength;
603                                 eom = NETFLAG_EOM;
604                         }
605                         else
606                         {
607                                 dataLen = MAX_PACKETFRAGMENT;
608                                 eom = 0;
609                         }
610
611                         packetLen = NET_HEADERSIZE + dataLen;
612
613                         header = (unsigned int *)sendbuffer;
614                         header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
615                         header[1] = BigLong(conn->nq.sendSequence - 1);
616                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
617
618                         conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
619
620                         if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
621                         {
622                                 conn->lastSendTime = realtime;
623                                 packetsReSent++;
624                         }
625
626                         totallen += packetLen + 28;
627                 }
628
629                 // if we have a new reliable message to send, do so
630                 if (!conn->sendMessageLength && conn->message.cursize && !quakesignon_suppressreliables)
631                 {
632                         if (conn->message.cursize > (int)sizeof(conn->sendMessage))
633                         {
634                                 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, (int)sizeof(conn->sendMessage));
635                                 conn->message.overflowed = true;
636                                 return -1;
637                         }
638
639                         if (developer_networking.integer && conn == cls.netcon)
640                         {
641                                 Con_Print("client sending reliable message to server:\n");
642                                 SZ_HexDumpToConsole(&conn->message);
643                         }
644
645                         memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
646                         conn->sendMessageLength = conn->message.cursize;
647                         SZ_Clear(&conn->message);
648
649                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
650                         {
651                                 dataLen = conn->sendMessageLength;
652                                 eom = NETFLAG_EOM;
653                         }
654                         else
655                         {
656                                 dataLen = MAX_PACKETFRAGMENT;
657                                 eom = 0;
658                         }
659
660                         packetLen = NET_HEADERSIZE + dataLen;
661
662                         header = (unsigned int *)sendbuffer;
663                         header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
664                         header[1] = BigLong(conn->nq.sendSequence);
665                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
666
667                         conn->nq.sendSequence++;
668
669                         conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
670
671                         NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
672
673                         conn->lastSendTime = realtime;
674                         packetsSent++;
675                         reliableMessagesSent++;
676
677                         totallen += packetLen + 28;
678                 }
679
680                 // if we have an unreliable message to send, do so
681                 if (data->cursize)
682                 {
683                         packetLen = NET_HEADERSIZE + data->cursize;
684
685                         if (packetLen > (int)sizeof(sendbuffer))
686                         {
687                                 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
688                                 return -1;
689                         }
690
691                         header = (unsigned int *)sendbuffer;
692                         header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
693                         header[1] = BigLong(conn->nq.unreliableSendSequence);
694                         memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
695
696                         conn->nq.unreliableSendSequence++;
697
698                         conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
699
700                         NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
701
702                         packetsSent++;
703                         unreliableMessagesSent++;
704
705                         totallen += packetLen + 28;
706                 }
707         }
708
709         // delay later packets to obey rate limit
710         if (conn->cleartime < realtime - 0.1)
711                 conn->cleartime = realtime - 0.1;
712         conn->cleartime = conn->cleartime + (double)totallen / (double)rate;
713         if (conn->cleartime < realtime)
714                 conn->cleartime = realtime;
715
716         return 0;
717 }
718
719 qboolean NetConn_HaveClientPorts(void)
720 {
721         return !!cl_numsockets;
722 }
723
724 qboolean NetConn_HaveServerPorts(void)
725 {
726         return !!sv_numsockets;
727 }
728
729 void NetConn_CloseClientPorts(void)
730 {
731         for (;cl_numsockets > 0;cl_numsockets--)
732                 if (cl_sockets[cl_numsockets - 1])
733                         LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
734 }
735
736 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
737 {
738         lhnetaddress_t address;
739         lhnetsocket_t *s;
740         char addressstring2[1024];
741         if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
742         {
743                 if ((s = LHNET_OpenSocket_Connectionless(&address)))
744                 {
745                         cl_sockets[cl_numsockets++] = s;
746                         LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
747                         Con_Printf("Client opened a socket on address %s\n", addressstring2);
748                 }
749                 else
750                 {
751                         LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
752                         Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
753                 }
754         }
755         else
756                 Con_Printf("Client unable to parse address %s\n", addressstring);
757 }
758
759 void NetConn_OpenClientPorts(void)
760 {
761         int port;
762         NetConn_CloseClientPorts();
763         port = bound(0, cl_netport.integer, 65535);
764         if (cl_netport.integer != port)
765                 Cvar_SetValueQuick(&cl_netport, port);
766         Con_Printf("Client using port %i\n", port);
767         NetConn_OpenClientPort("local:2", 0);
768         NetConn_OpenClientPort(net_address.string, port);
769         //NetConn_OpenClientPort(net_address_ipv6.string, port);
770 }
771
772 void NetConn_CloseServerPorts(void)
773 {
774         for (;sv_numsockets > 0;sv_numsockets--)
775                 if (sv_sockets[sv_numsockets - 1])
776                         LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
777 }
778
779 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
780 {
781         lhnetaddress_t address;
782         lhnetsocket_t *s;
783         int port;
784         char addressstring2[1024];
785
786         for (port = defaultport; port <= defaultport + 100; port++)
787         {
788                 if (LHNETADDRESS_FromString(&address, addressstring, port))
789                 {
790                         if ((s = LHNET_OpenSocket_Connectionless(&address)))
791                         {
792                                 sv_sockets[sv_numsockets++] = s;
793                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
794                                 Con_Printf("Server listening on address %s\n", addressstring2);
795                                 break;
796                         }
797                         else
798                         {
799                                 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
800                                 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
801                         }
802                 }
803                 else
804                 {
805                         Con_Printf("Server unable to parse address %s\n", addressstring);
806                         // if it cant parse one address, it wont be able to parse another for sure
807                         break;
808                 }
809         }
810 }
811
812 void NetConn_OpenServerPorts(int opennetports)
813 {
814         int port;
815         NetConn_CloseServerPorts();
816         NetConn_UpdateSockets();
817         port = bound(0, sv_netport.integer, 65535);
818         if (port == 0)
819                 port = 26000;
820         Con_Printf("Server using port %i\n", port);
821         if (sv_netport.integer != port)
822                 Cvar_SetValueQuick(&sv_netport, port);
823         if (cls.state != ca_dedicated)
824                 NetConn_OpenServerPort("local:1", 0);
825         if (opennetports)
826         {
827                 NetConn_OpenServerPort(net_address.string, port);
828                 //NetConn_OpenServerPort(net_address_ipv6.string, port);
829         }
830         if (sv_numsockets == 0)
831                 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
832 }
833
834 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
835 {
836         int i, a = LHNETADDRESS_GetAddressType(address);
837         for (i = 0;i < cl_numsockets;i++)
838                 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
839                         return cl_sockets[i];
840         return NULL;
841 }
842
843 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
844 {
845         int i, a = LHNETADDRESS_GetAddressType(address);
846         for (i = 0;i < sv_numsockets;i++)
847                 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
848                         return sv_sockets[i];
849         return NULL;
850 }
851
852 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
853 {
854         netconn_t *conn;
855         conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
856         conn->mysocket = mysocket;
857         conn->peeraddress = *peeraddress;
858         conn->lastMessageTime = realtime;
859         conn->message.data = conn->messagedata;
860         conn->message.maxsize = sizeof(conn->messagedata);
861         conn->message.cursize = 0;
862         // LordHavoc: (inspired by ProQuake) use a short connect timeout to
863         // reduce effectiveness of connection request floods
864         conn->timeout = realtime + net_connecttimeout.value;
865         LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
866         conn->next = netconn_list;
867         netconn_list = conn;
868         return conn;
869 }
870
871 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
872 void NetConn_Close(netconn_t *conn)
873 {
874         netconn_t *c;
875         // remove connection from list
876
877         // allow the client to reconnect immediately
878         NetConn_ClearConnectFlood(&(conn->peeraddress));
879
880         if (conn == netconn_list)
881                 netconn_list = conn->next;
882         else
883         {
884                 for (c = netconn_list;c;c = c->next)
885                 {
886                         if (c->next == conn)
887                         {
888                                 c->next = conn->next;
889                                 break;
890                         }
891                 }
892                 // not found in list, we'll avoid crashing here...
893                 if (!c)
894                         return;
895         }
896         // free connection
897         Mem_Free(conn);
898 }
899
900 static int clientport = -1;
901 static int clientport2 = -1;
902 static int hostport = -1;
903 void NetConn_UpdateSockets(void)
904 {
905         if (cls.state != ca_dedicated)
906         {
907                 if (clientport2 != cl_netport.integer)
908                 {
909                         clientport2 = cl_netport.integer;
910                         if (cls.state == ca_connected)
911                                 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
912                 }
913                 if (cls.state == ca_disconnected && clientport != clientport2)
914                 {
915                         clientport = clientport2;
916                         NetConn_CloseClientPorts();
917                 }
918                 if (cl_numsockets == 0)
919                         NetConn_OpenClientPorts();
920         }
921
922         if (hostport != sv_netport.integer)
923         {
924                 hostport = sv_netport.integer;
925                 if (sv.active)
926                         Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
927         }
928 }
929
930 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
931 {
932         int originallength = length;
933         if (length < 8)
934                 return 0;
935
936         if (protocol == PROTOCOL_QUAKEWORLD)
937         {
938                 int sequence, sequence_ack;
939                 int reliable_ack, reliable_message;
940                 int count;
941                 int qport;
942
943                 sequence = LittleLong(*((int *)(data + 0)));
944                 sequence_ack = LittleLong(*((int *)(data + 4)));
945                 data += 8;
946                 length -= 8;
947
948                 if (conn != cls.netcon)
949                 {
950                         // server only
951                         if (length < 2)
952                                 return 0;
953                         // TODO: use qport to identify that this client really is who they say they are?  (and elsewhere in the code to identify the connection without a port match?)
954                         qport = LittleShort(*((int *)(data + 8)));
955                         data += 2;
956                         length -= 2;
957                 }
958
959                 packetsReceived++;
960                 reliable_message = (sequence >> 31) & 1;
961                 reliable_ack = (sequence_ack >> 31) & 1;
962                 sequence &= ~(1<<31);
963                 sequence_ack &= ~(1<<31);
964                 if (sequence <= conn->qw.incoming_sequence)
965                 {
966                         //Con_DPrint("Got a stale datagram\n");
967                         return 0;
968                 }
969                 count = sequence - (conn->qw.incoming_sequence + 1);
970                 if (count > 0)
971                 {
972                         droppedDatagrams += count;
973                         //Con_DPrintf("Dropped %u datagram(s)\n", count);
974                         while (count--)
975                         {
976                                 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
977                                 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
978                                 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
979                                 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
980                         }
981                 }
982                 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
983                 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
984                 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
985                 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
986                 if (reliable_ack == conn->qw.reliable_sequence)
987                 {
988                         // received, now we will be able to send another reliable message
989                         conn->sendMessageLength = 0;
990                         reliableMessagesReceived++;
991                 }
992                 conn->qw.incoming_sequence = sequence;
993                 if (conn == cls.netcon)
994                         cls.qw_incoming_sequence = conn->qw.incoming_sequence;
995                 conn->qw.incoming_acknowledged = sequence_ack;
996                 conn->qw.incoming_reliable_acknowledged = reliable_ack;
997                 if (reliable_message)
998                         conn->qw.incoming_reliable_sequence ^= 1;
999                 conn->lastMessageTime = realtime;
1000                 conn->timeout = realtime + newtimeout;
1001                 unreliableMessagesReceived++;
1002                 SZ_Clear(&net_message);
1003                 SZ_Write(&net_message, data, length);
1004                 MSG_BeginReading();
1005                 return 2;
1006         }
1007         else
1008         {
1009                 unsigned int count;
1010                 unsigned int flags;
1011                 unsigned int sequence;
1012                 int qlength;
1013
1014                 qlength = (unsigned int)BigLong(((int *)data)[0]);
1015                 flags = qlength & ~NETFLAG_LENGTH_MASK;
1016                 qlength &= NETFLAG_LENGTH_MASK;
1017                 // control packets were already handled
1018                 if (!(flags & NETFLAG_CTL) && qlength == length)
1019                 {
1020                         sequence = BigLong(((int *)data)[1]);
1021                         packetsReceived++;
1022                         data += 8;
1023                         length -= 8;
1024                         if (flags & NETFLAG_UNRELIABLE)
1025                         {
1026                                 if (sequence >= conn->nq.unreliableReceiveSequence)
1027                                 {
1028                                         if (sequence > conn->nq.unreliableReceiveSequence)
1029                                         {
1030                                                 count = sequence - conn->nq.unreliableReceiveSequence;
1031                                                 droppedDatagrams += count;
1032                                                 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1033                                                 while (count--)
1034                                                 {
1035                                                         conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1036                                                         conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1037                                                         conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1038                                                         conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1039                                                 }
1040                                         }
1041                                         conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1042                                         conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1043                                         conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1044                                         conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1045                                         conn->nq.unreliableReceiveSequence = sequence + 1;
1046                                         conn->lastMessageTime = realtime;
1047                                         conn->timeout = realtime + newtimeout;
1048                                         unreliableMessagesReceived++;
1049                                         if (length > 0)
1050                                         {
1051                                                 SZ_Clear(&net_message);
1052                                                 SZ_Write(&net_message, data, length);
1053                                                 MSG_BeginReading();
1054                                                 return 2;
1055                                         }
1056                                 }
1057                                 //else
1058                                 //      Con_DPrint("Got a stale datagram\n");
1059                                 return 1;
1060                         }
1061                         else if (flags & NETFLAG_ACK)
1062                         {
1063                                 conn->incoming_acksize[conn->incoming_packetcounter] += originallength;
1064                                 if (sequence == (conn->nq.sendSequence - 1))
1065                                 {
1066                                         if (sequence == conn->nq.ackSequence)
1067                                         {
1068                                                 conn->nq.ackSequence++;
1069                                                 if (conn->nq.ackSequence != conn->nq.sendSequence)
1070                                                         Con_DPrint("ack sequencing error\n");
1071                                                 conn->lastMessageTime = realtime;
1072                                                 conn->timeout = realtime + newtimeout;
1073                                                 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1074                                                 {
1075                                                         unsigned int packetLen;
1076                                                         unsigned int dataLen;
1077                                                         unsigned int eom;
1078                                                         unsigned int *header;
1079
1080                                                         conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1081                                                         memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1082
1083                                                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1084                                                         {
1085                                                                 dataLen = conn->sendMessageLength;
1086                                                                 eom = NETFLAG_EOM;
1087                                                         }
1088                                                         else
1089                                                         {
1090                                                                 dataLen = MAX_PACKETFRAGMENT;
1091                                                                 eom = 0;
1092                                                         }
1093
1094                                                         packetLen = NET_HEADERSIZE + dataLen;
1095
1096                                                         header = (unsigned int *)sendbuffer;
1097                                                         header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1098                                                         header[1] = BigLong(conn->nq.sendSequence);
1099                                                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1100
1101                                                         conn->nq.sendSequence++;
1102
1103                                                         if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1104                                                         {
1105                                                                 conn->lastSendTime = realtime;
1106                                                                 packetsSent++;
1107                                                         }
1108                                                 }
1109                                                 else
1110                                                         conn->sendMessageLength = 0;
1111                                         }
1112                                         //else
1113                                         //      Con_DPrint("Duplicate ACK received\n");
1114                                 }
1115                                 //else
1116                                 //      Con_DPrint("Stale ACK received\n");
1117                                 return 1;
1118                         }
1119                         else if (flags & NETFLAG_DATA)
1120                         {
1121                                 unsigned int temppacket[2];
1122                                 conn->incoming_reliablesize[conn->incoming_packetcounter] += originallength;
1123                                 conn->outgoing_acksize[conn->outgoing_packetcounter] += 8;
1124                                 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1125                                 temppacket[1] = BigLong(sequence);
1126                                 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1127                                 if (sequence == conn->nq.receiveSequence)
1128                                 {
1129                                         conn->lastMessageTime = realtime;
1130                                         conn->timeout = realtime + newtimeout;
1131                                         conn->nq.receiveSequence++;
1132                                         if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1133                                                 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1134                                                 conn->receiveMessageLength += length;
1135                                         } else {
1136                                                 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1137                                                                         "Dropping the message!\n", sequence );
1138                                                 conn->receiveMessageLength = 0;
1139                                                 return 1;
1140                                         }
1141                                         if (flags & NETFLAG_EOM)
1142                                         {
1143                                                 reliableMessagesReceived++;
1144                                                 length = conn->receiveMessageLength;
1145                                                 conn->receiveMessageLength = 0;
1146                                                 if (length > 0)
1147                                                 {
1148                                                         SZ_Clear(&net_message);
1149                                                         SZ_Write(&net_message, conn->receiveMessage, length);
1150                                                         MSG_BeginReading();
1151                                                         return 2;
1152                                                 }
1153                                         }
1154                                 }
1155                                 else
1156                                         receivedDuplicateCount++;
1157                                 return 1;
1158                         }
1159                 }
1160         }
1161         return 0;
1162 }
1163
1164 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1165 {
1166         cls.connect_trying = false;
1167         M_Update_Return_Reason("");
1168         // the connection request succeeded, stop current connection and set up a new connection
1169         CL_Disconnect();
1170         // if we're connecting to a remote server, shut down any local server
1171         if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1172                 Host_ShutdownServer ();
1173         // allocate a net connection to keep track of things
1174         cls.netcon = NetConn_Open(mysocket, peeraddress);
1175         Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1176         key_dest = key_game;
1177         m_state = m_none;
1178         cls.demonum = -1;                       // not in the demo loop now
1179         cls.state = ca_connected;
1180         cls.signon = 0;                         // need all the signon messages before playing
1181         cls.protocol = initialprotocol;
1182         // reset move sequence numbering on this new connection
1183         cls.movesequence = 1;
1184         cls.servermovesequence = 0;
1185         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1186                 Cmd_ForwardStringToServer("new");
1187         if (cls.protocol == PROTOCOL_QUAKE)
1188         {
1189                 // write a keepalive (clc_nop) as it seems to greatly improve the
1190                 // chances of connecting to a netquake server
1191                 sizebuf_t msg;
1192                 unsigned char buf[4];
1193                 memset(&msg, 0, sizeof(msg));
1194                 msg.data = buf;
1195                 msg.maxsize = sizeof(buf);
1196                 MSG_WriteChar(&msg, clc_nop);
1197                 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1198         }
1199 }
1200
1201 int NetConn_IsLocalGame(void)
1202 {
1203         if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1204                 return true;
1205         return false;
1206 }
1207
1208 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1209 {
1210         int n;
1211         int pingtime;
1212         // search the cache for this server and update it
1213         for (n = 0;n < serverlist_cachecount;n++)
1214                 if (!strcmp(addressstring, serverlist_cache[n].info.cname))
1215                         break;
1216         if (n == serverlist_cachecount)
1217         {
1218                 // LAN search doesnt require an answer from the master server so we wont
1219                 // know the ping nor will it be initialized already...
1220
1221                 // find a slot
1222                 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1223                         return -1;
1224
1225                 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1226                 // store the data the engine cares about (address and ping)
1227                 strlcpy(serverlist_cache[serverlist_cachecount].info.cname, addressstring, sizeof(serverlist_cache[serverlist_cachecount].info.cname));
1228                 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1229                 serverlist_cache[serverlist_cachecount].querytime = realtime;
1230                 // if not in the slist menu we should print the server to console
1231                 if (serverlist_consoleoutput)
1232                         Con_Printf("querying %s\n", addressstring);
1233                 ++serverlist_cachecount;
1234         }
1235         // if this is the first reply from this server, count it as having replied
1236         if (serverlist_cache[n].info.ping == 100000)
1237                 serverreplycount++;
1238         pingtime = (int)((realtime - serverlist_cache[n].querytime) * 1000.0 + 0.5);
1239         pingtime = bound(0, pingtime, 9999);
1240         // update the ping
1241         serverlist_cache[n].info.ping = min(serverlist_cache[n].info.ping, pingtime);
1242         // other server info is updated by the caller
1243         return n;
1244 }
1245
1246 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1247 {
1248         serverlist_info_t *info = &serverlist_cache[n].info;
1249         // update description strings for engine menu and console output
1250         dpsnprintf(serverlist_cache[n].line1, sizeof(serverlist_cache[n].line1), "^%c%5d^7 ^%c%3u^7/%3u %-65.65s", info->ping >= 300 ? '1' : (info->ping >= 200 ? '3' : '7'), (int)info->ping, ((info->numhumans > 0 && info->numhumans < info->maxplayers) ? (info->numhumans >= 4 ? '7' : '3') : '1'), info->numplayers, info->maxplayers, info->name);
1251         dpsnprintf(serverlist_cache[n].line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game, (info->gameversion != gameversion.integer) ? '1' : '4', info->mod, info->map);
1252         if (serverlist_cache[n].query == SQS_QUERIED)
1253                 ServerList_ViewList_Remove(&serverlist_cache[n]);
1254         // if not in the slist menu we should print the server to console (if wanted)
1255         else if( serverlist_consoleoutput )
1256                 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1257         // and finally, update the view set
1258         ServerList_ViewList_Insert( &serverlist_cache[n] );
1259         serverlist_cache[n].query = SQS_QUERIED;
1260 }
1261
1262 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1263 {
1264         qboolean fromserver;
1265         int ret, c, control;
1266         const char *s;
1267         char *string, addressstring2[128], ipstring[32];
1268         char stringbuf[16384];
1269
1270         // quakeworld ingame packet
1271         fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1272
1273         // convert the address to a string incase we need it
1274         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1275
1276         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1277         {
1278                 // received a command string - strip off the packaging and put it
1279                 // into our string buffer with NULL termination
1280                 data += 4;
1281                 length -= 4;
1282                 length = min(length, (int)sizeof(stringbuf) - 1);
1283                 memcpy(stringbuf, data, length);
1284                 stringbuf[length] = 0;
1285                 string = stringbuf;
1286
1287                 if (developer_networking.integer)
1288                 {
1289                         Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1290                         Com_HexDumpToConsole(data, length);
1291                 }
1292
1293                 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1294                 {
1295                         // darkplaces or quake3
1296                         char protocolnames[1400];
1297                         Protocol_Names(protocolnames, sizeof(protocolnames));
1298                         Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1299                         M_Update_Return_Reason("Got challenge response");
1300                         // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1301                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1302                         // TODO: add userinfo stuff here instead of using NQ commands?
1303                         NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1304                         return true;
1305                 }
1306                 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1307                 {
1308                         // darkplaces or quake3
1309                         M_Update_Return_Reason("Accepted");
1310                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1311                         return true;
1312                 }
1313                 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1314                 {
1315                         char rejectreason[32];
1316                         cls.connect_trying = false;
1317                         string += 7;
1318                         length = max(length - 7, (int)sizeof(rejectreason) - 1);
1319                         memcpy(rejectreason, string, length);
1320                         rejectreason[length] = 0;
1321                         M_Update_Return_Reason(rejectreason);
1322                         return true;
1323                 }
1324                 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1325                 {
1326                         serverlist_info_t *info;
1327                         int n;
1328
1329                         string += 13;
1330                         // search the cache for this server and update it
1331                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1332                         if (n < 0)
1333                                 return true;
1334
1335                         info = &serverlist_cache[n].info;
1336                         info->game[0] = 0;
1337                         info->mod[0]  = 0;
1338                         info->map[0]  = 0;
1339                         info->name[0] = 0;
1340                         info->protocol = -1;
1341                         info->numplayers = 0;
1342                         info->numbots = -1;
1343                         info->maxplayers  = 0;
1344                         info->gameversion = 0;
1345                         if ((s = SearchInfostring(string, "gamename"     )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1346                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1347                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1348                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1349                         if ((s = SearchInfostring(string, "protocol"     )) != NULL) info->protocol = atoi(s);
1350                         if ((s = SearchInfostring(string, "clients"      )) != NULL) info->numplayers = atoi(s);
1351                         if ((s = SearchInfostring(string, "bots"         )) != NULL) info->numbots = atoi(s);
1352                         if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1353                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);
1354                         info->numhumans = info->numplayers - max(0, info->numbots);
1355                         info->freeslots = info->maxplayers - info->numplayers;
1356
1357                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1358
1359                         return true;
1360                 }
1361                 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1362                 {
1363                         // Extract the IP addresses
1364                         data += 18;
1365                         length -= 18;
1366                         masterreplycount++;
1367                         if (serverlist_consoleoutput)
1368                                 Con_Print("received DarkPlaces server list...\n");
1369                         while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1370                         {
1371                                 int n;
1372
1373                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], data[5] * 256 + data[6]);
1374                                 if (serverlist_consoleoutput && developer_networking.integer)
1375                                         Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1376                                 // ignore the rest of the message if the serverlist is full
1377                                 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1378                                         break;
1379                                 // also ignore it if we have already queried it (other master server response)
1380                                 for( n = 0 ; n < serverlist_cachecount ; n++ )
1381                                         if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1382                                                 break;
1383                                 if( n >= serverlist_cachecount )
1384                                 {
1385                                         serverquerycount++;
1386
1387                                         memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1388                                         serverlist_cache[serverlist_cachecount].protocol = PROTOCOL_DARKPLACES7;
1389                                         // store the data the engine cares about (address and ping)
1390                                         strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1391                                         serverlist_cache[serverlist_cachecount].info.ping = 100000;
1392                                         serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1393
1394                                         ++serverlist_cachecount;
1395                                 }
1396
1397                                 // move on to next address in packet
1398                                 data += 7;
1399                                 length -= 7;
1400                         }
1401                         // begin or resume serverlist queries
1402                         serverlist_querysleep = false;
1403                         serverlist_querywaittime = realtime + 3;
1404                         return true;
1405                 }
1406                 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1407                 {
1408                         // Extract the IP addresses
1409                         data += 2;
1410                         length -= 2;
1411                         masterreplycount++;
1412                         if (serverlist_consoleoutput)
1413                                 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1414                         while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1415                         {
1416                                 int n;
1417
1418                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1419                                 if (serverlist_consoleoutput && developer_networking.integer)
1420                                         Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1421                                 // ignore the rest of the message if the serverlist is full
1422                                 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1423                                         break;
1424                                 // also ignore it if we have already queried it (other master server response)
1425                                 for( n = 0 ; n < serverlist_cachecount ; n++ )
1426                                         if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1427                                                 break;
1428                                 if( n >= serverlist_cachecount )
1429                                 {
1430                                         serverquerycount++;
1431
1432                                         memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1433                                         serverlist_cache[serverlist_cachecount].protocol = PROTOCOL_QUAKEWORLD;
1434                                         // store the data the engine cares about (address and ping)
1435                                         strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1436                                         serverlist_cache[serverlist_cachecount].info.ping = 100000;
1437                                         serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1438
1439                                         ++serverlist_cachecount;
1440                                 }
1441
1442                                 // move on to next address in packet
1443                                 data += 6;
1444                                 length -= 6;
1445                         }
1446                         // begin or resume serverlist queries
1447                         serverlist_querysleep = false;
1448                         serverlist_querywaittime = realtime + 3;
1449                         return true;
1450                 }
1451                 if (!strncmp(string, "extResponse ", 12))
1452                 {
1453                         ++net_extresponse_count;
1454                         if(net_extresponse_count > NET_EXTRESPONSE_MAX)
1455                                 net_extresponse_count = NET_EXTRESPONSE_MAX;
1456                         net_extresponse_last = (net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1457                         dpsnprintf(net_extresponse[net_extresponse_last], sizeof(net_extresponse[net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
1458                         return true;
1459                 }
1460                 if (!strncmp(string, "ping", 4))
1461                 {
1462                         if (developer.integer >= 10)
1463                                 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1464                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1465                         return true;
1466                 }
1467                 if (!strncmp(string, "ack", 3))
1468                         return true;
1469                 // QuakeWorld compatibility
1470                 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1471                 {
1472                         // challenge message
1473                         Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1474                         M_Update_Return_Reason("Got QuakeWorld challenge response");
1475                         cls.qw_qport = qport.integer;
1476                         // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1477                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1478                         NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1479                         return true;
1480                 }
1481                 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1482                 {
1483                         // accept message
1484                         M_Update_Return_Reason("QuakeWorld Accepted");
1485                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1486                         return true;
1487                 }
1488                 if (length > 2 && !memcmp(string, "n\\", 2))
1489                 {
1490                         serverlist_info_t *info;
1491                         int n;
1492
1493                         // qw server status
1494                         if (serverlist_consoleoutput && developer_networking.integer >= 2)
1495                                 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1496
1497                         string += 1;
1498                         // search the cache for this server and update it
1499                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1500                         if (n < 0)
1501                                 return true;
1502
1503                         info = &serverlist_cache[n].info;
1504                         strlcpy(info->game, "QuakeWorld", sizeof(info->game));;
1505                         if ((s = SearchInfostring(string, "*gamedir"     )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0]  = 0;
1506                         if ((s = SearchInfostring(string, "map"          )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0]  = 0;
1507                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1508                         info->protocol = 0;
1509                         info->numplayers = 0; // updated below
1510                         if ((s = SearchInfostring(string, "maxclients"   )) != NULL) info->maxplayers = atoi(s);else info->maxplayers  = 0;
1511                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1512
1513                         // count active players on server
1514                         // (we could gather more info, but we're just after the number)
1515                         s = strchr(string, '\n');
1516                         if (s)
1517                         {
1518                                 s++;
1519                                 while (s < string + length)
1520                                 {
1521                                         for (;s < string + length && *s != '\n';s++)
1522                                                 ;
1523                                         if (s >= string + length)
1524                                                 break;
1525                                         info->numplayers++;
1526                                         s++;
1527                                 }
1528                         }
1529
1530                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1531
1532                         return true;
1533                 }
1534                 if (string[0] == 'n')
1535                 {
1536                         // qw print command
1537                         Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1538                 }
1539                 // we may not have liked the packet, but it was a command packet, so
1540                 // we're done processing this packet now
1541                 return true;
1542         }
1543         // quakeworld ingame packet
1544         if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1545         {
1546                 ret = 0;
1547                 CL_ParseServerMessage();
1548                 return ret;
1549         }
1550         // netquake control packets, supported for compatibility only
1551         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1552         {
1553                 int n;
1554                 serverlist_info_t *info;
1555
1556                 data += 4;
1557                 length -= 4;
1558                 SZ_Clear(&net_message);
1559                 SZ_Write(&net_message, data, length);
1560                 MSG_BeginReading();
1561                 c = MSG_ReadByte();
1562                 switch (c)
1563                 {
1564                 case CCREP_ACCEPT:
1565                         if (developer.integer >= 10)
1566                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1567                         if (cls.connect_trying)
1568                         {
1569                                 lhnetaddress_t clientportaddress;
1570                                 clientportaddress = *peeraddress;
1571                                 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1572                                 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1573                                 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1574                                 M_Update_Return_Reason("Accepted");
1575                                 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1576                         }
1577                         break;
1578                 case CCREP_REJECT:
1579                         if (developer.integer >= 10)
1580                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1581                         cls.connect_trying = false;
1582                         M_Update_Return_Reason((char *)MSG_ReadString());
1583                         break;
1584                 case CCREP_SERVER_INFO:
1585                         if (developer.integer >= 10)
1586                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1587                         // LordHavoc: because the quake server may report weird addresses
1588                         // we just ignore it and keep the real address
1589                         MSG_ReadString();
1590                         // search the cache for this server and update it
1591                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1592                         if (n < 0)
1593                                 break;
1594
1595                         info = &serverlist_cache[n].info;
1596                         strlcpy(info->game, "Quake", sizeof(info->game));
1597                         strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1598                         strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1599                         strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1600                         info->numplayers = MSG_ReadByte();
1601                         info->maxplayers = MSG_ReadByte();
1602                         info->protocol = MSG_ReadByte();
1603
1604                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1605
1606                         break;
1607                 case CCREP_PLAYER_INFO:
1608                         // we got a CCREP_PLAYER_INFO??
1609                         //if (developer.integer >= 10)
1610                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1611                         break;
1612                 case CCREP_RULE_INFO:
1613                         // we got a CCREP_RULE_INFO??
1614                         //if (developer.integer >= 10)
1615                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1616                         break;
1617                 default:
1618                         break;
1619                 }
1620                 SZ_Clear(&net_message);
1621                 // we may not have liked the packet, but it was a valid control
1622                 // packet, so we're done processing this packet now
1623                 return true;
1624         }
1625         ret = 0;
1626         if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1627                 CL_ParseServerMessage();
1628         return ret;
1629 }
1630
1631 void NetConn_QueryQueueFrame(void)
1632 {
1633         int index;
1634         int queries;
1635         int maxqueries;
1636         double timeouttime;
1637         static double querycounter = 0;
1638
1639         if (serverlist_querysleep)
1640                 return;
1641
1642         // apply a cool down time after master server replies,
1643         // to avoid messing up the ping times on the servers
1644         if (serverlist_querywaittime > realtime)
1645                 return;
1646
1647         // each time querycounter reaches 1.0 issue a query
1648         querycounter += cl.realframetime * net_slist_queriespersecond.value;
1649         maxqueries = (int)querycounter;
1650         maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1651         querycounter -= maxqueries;
1652
1653         if( maxqueries == 0 ) {
1654                 return;
1655         }
1656
1657         // scan serverlist and issue queries as needed
1658     serverlist_querysleep = true;
1659
1660         timeouttime = realtime - net_slist_timeout.value;
1661         for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1662         {
1663                 serverlist_entry_t *entry = &serverlist_cache[ index ];
1664                 if( entry->query != SQS_QUERYING )
1665                 {
1666                         continue;
1667                 }
1668
1669         serverlist_querysleep = false;
1670                 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1671                 {
1672                         continue;
1673                 }
1674
1675                 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1676                 {
1677                         lhnetaddress_t address;
1678                         int socket;
1679
1680                         LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1681                         if (entry->protocol == PROTOCOL_QUAKEWORLD)
1682                         {
1683                                 for (socket = 0; socket < cl_numsockets ; socket++)
1684                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1685                         }
1686                         else
1687                         {
1688                                 for (socket = 0; socket < cl_numsockets ; socket++)
1689                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address);
1690                         }
1691
1692                         entry->querytime = realtime;
1693                         entry->querycounter++;
1694
1695                         // if not in the slist menu we should print the server to console
1696                         if (serverlist_consoleoutput)
1697                                 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1698
1699                         queries++;
1700                 }
1701                 else
1702                 {
1703                         entry->query = SQS_TIMEDOUT;
1704                 }
1705         }
1706 }
1707
1708 void NetConn_ClientFrame(void)
1709 {
1710         int i, length;
1711         lhnetaddress_t peeraddress;
1712         NetConn_UpdateSockets();
1713         if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1714         {
1715                 if (cls.connect_remainingtries == 0)
1716                         M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1717                 cls.connect_nextsendtime = realtime + 1;
1718                 cls.connect_remainingtries--;
1719                 if (cls.connect_remainingtries <= -10)
1720                 {
1721                         cls.connect_trying = false;
1722                         M_Update_Return_Reason("Connect: Failed");
1723                         return;
1724                 }
1725                 // try challenge first (newer DP server or QW)
1726                 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1727                 // then try netquake as a fallback (old server, or netquake)
1728                 SZ_Clear(&net_message);
1729                 // save space for the header, filled in later
1730                 MSG_WriteLong(&net_message, 0);
1731                 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1732                 MSG_WriteString(&net_message, "QUAKE");
1733                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1734                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1735                 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1736                 SZ_Clear(&net_message);
1737         }
1738         for (i = 0;i < cl_numsockets;i++)
1739                 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1740                         NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1741         NetConn_QueryQueueFrame();
1742         if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
1743         {
1744                 Con_Print("Connection timed out\n");
1745                 CL_Disconnect();
1746                 Host_ShutdownServer ();
1747         }
1748 }
1749
1750 #define MAX_CHALLENGES 128
1751 struct challenge_s
1752 {
1753         lhnetaddress_t address;
1754         double time;
1755         char string[12];
1756 }
1757 challenge[MAX_CHALLENGES];
1758
1759 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1760 {
1761         int i;
1762         char c;
1763         for (i = 0;i < bufferlength - 1;i++)
1764         {
1765                 do
1766                 {
1767                         c = rand () % (127 - 33) + 33;
1768                 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1769                 buffer[i] = c;
1770         }
1771         buffer[i] = 0;
1772 }
1773
1774 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1775 {
1776         unsigned int nb_clients = 0, nb_bots = 0, i;
1777         int length;
1778
1779         // How many clients are there?
1780         for (i = 0;i < (unsigned int)svs.maxclients;i++)
1781         {
1782                 if (svs.clients[i].active)
1783                 {
1784                         nb_clients++;
1785                         if (!svs.clients[i].netconnection)
1786                                 nb_bots++;
1787                 }
1788         }
1789
1790         // TODO: we should add more information for the full status string
1791         length = dpsnprintf(out_msg, out_size,
1792                                                 "\377\377\377\377%s\x0A"
1793                                                 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
1794                                                 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
1795                                                 "%s%s"
1796                                                 "%s",
1797                                                 fullstatus ? "statusResponse" : "infoResponse",
1798                                                 gamename, com_modname, gameversion.integer, svs.maxclients,
1799                                                 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
1800                                                 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
1801                                                 fullstatus ? "\n" : "");
1802
1803         // Make sure it fits in the buffer
1804         if (length < 0)
1805                 return false;
1806
1807         if (fullstatus)
1808         {
1809                 char *ptr;
1810                 int left;
1811
1812                 ptr = out_msg + length;
1813                 left = (int)out_size - length;
1814
1815                 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1816                 {
1817                         client_t *cl = &svs.clients[i];
1818                         if (cl->active)
1819                         {
1820                                 int nameind, cleanind, pingvalue;
1821                                 char curchar;
1822                                 char cleanname [sizeof(cl->name)];
1823
1824                                 // Remove all characters '"' and '\' in the player name
1825                                 nameind = 0;
1826                                 cleanind = 0;
1827                                 do
1828                                 {
1829                                         curchar = cl->name[nameind++];
1830                                         if (curchar != '"' && curchar != '\\')
1831                                         {
1832                                                 cleanname[cleanind++] = curchar;
1833                                                 if (cleanind == sizeof(cleanname) - 1)
1834                                                         break;
1835                                         }
1836                                 } while (curchar != '\0');
1837
1838                                 pingvalue = (int)(cl->ping * 1000.0f);
1839                                 if(cl->netconnection)
1840                                         pingvalue = bound(1, pingvalue, 9999);
1841                                 else
1842                                         pingvalue = 0;
1843                                 length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
1844                                                                         cl->frags,
1845                                                                         pingvalue,
1846                                                                         cleanname);
1847                                 if(length < 0)
1848                                         return false;
1849                                 left -= length;
1850                                 ptr += length;
1851                         }
1852                 }
1853         }
1854
1855         return true;
1856 }
1857
1858 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
1859 {
1860         int floodslotnum, bestfloodslotnum;
1861         double bestfloodtime;
1862         lhnetaddress_t noportpeeraddress;
1863         // see if this is a connect flood
1864         noportpeeraddress = *peeraddress;
1865         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
1866         bestfloodslotnum = 0;
1867         bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
1868         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
1869         {
1870                 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
1871                 {
1872                         bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
1873                         bestfloodslotnum = floodslotnum;
1874                 }
1875                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
1876                 {
1877                         // this address matches an ongoing flood address
1878                         if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
1879                         {
1880                                 // renew the ban on this address so it does not expire
1881                                 // until the flood has subsided
1882                                 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
1883                                 //Con_Printf("Flood detected!\n");
1884                                 return true;
1885                         }
1886                         // the flood appears to have subsided, so allow this
1887                         bestfloodslotnum = floodslotnum; // reuse the same slot
1888                         break;
1889                 }
1890         }
1891         // begin a new timeout on this address
1892         sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
1893         sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
1894         //Con_Printf("Flood detection initiated!\n");
1895         return false;
1896 }
1897
1898 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
1899 {
1900         int floodslotnum;
1901         lhnetaddress_t noportpeeraddress;
1902         // see if this is a connect flood
1903         noportpeeraddress = *peeraddress;
1904         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
1905         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
1906         {
1907                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
1908                 {
1909                         // this address matches an ongoing flood address
1910                         // remove the ban
1911                         sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
1912                         sv.connectfloodaddresses[floodslotnum].lasttime = 0;
1913                         //Con_Printf("Flood cleared!\n");
1914                 }
1915         }
1916 }
1917
1918 extern void SV_SendServerinfo (client_t *client);
1919 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1920 {
1921         int i, ret, clientnum, best;
1922         double besttime;
1923         client_t *client;
1924         char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
1925         qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
1926
1927         if (!sv.active)
1928                 return false;
1929
1930         // convert the address to a string incase we need it
1931         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1932
1933         // see if we can identify the sender as a local player
1934         // (this is necessary for rcon to send a reliable reply if the client is
1935         //  actually on the server, not sending remotely)
1936         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1937                 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1938                         break;
1939         if (i == svs.maxclients)
1940                 host_client = NULL;
1941
1942         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1943         {
1944                 // received a command string - strip off the packaging and put it
1945                 // into our string buffer with NULL termination
1946                 data += 4;
1947                 length -= 4;
1948                 length = min(length, (int)sizeof(stringbuf) - 1);
1949                 memcpy(stringbuf, data, length);
1950                 stringbuf[length] = 0;
1951                 string = stringbuf;
1952
1953                 if (developer.integer >= 10)
1954                 {
1955                         Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1956                         Com_HexDumpToConsole(data, length);
1957                 }
1958
1959                 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
1960                 {
1961                         for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1962                         {
1963                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1964                                         break;
1965                                 if (besttime > challenge[i].time)
1966                                         besttime = challenge[best = i].time;
1967                         }
1968                         // if we did not find an exact match, choose the oldest and
1969                         // update address and string
1970                         if (i == MAX_CHALLENGES)
1971                         {
1972                                 i = best;
1973                                 challenge[i].address = *peeraddress;
1974                                 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1975                         }
1976                         challenge[i].time = realtime;
1977                         // send the challenge
1978                         NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1979                         return true;
1980                 }
1981                 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
1982                 {
1983                         string += 7;
1984                         length -= 7;
1985
1986                         if (!(s = SearchInfostring(string, "challenge")))
1987                                 return true;
1988                         // validate the challenge
1989                         for (i = 0;i < MAX_CHALLENGES;i++)
1990                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1991                                         break;
1992                         // if the challenge is not recognized, drop the packet
1993                         if (i == MAX_CHALLENGES)
1994                                 return true;
1995
1996                         // check engine protocol
1997                         if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1998                         {
1999                                 if (developer.integer >= 10)
2000                                         Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2001                                 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2002                                 return true;
2003                         }
2004
2005                         // see if this is a duplicate connection request or a disconnected
2006                         // client who is rejoining to the same client slot
2007                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2008                         {
2009                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2010                                 {
2011                                         // this is a known client...
2012                                         if (client->spawned)
2013                                         {
2014                                                 // client crashed and is coming back,
2015                                                 // keep their stuff intact
2016                                                 if (developer.integer >= 10)
2017                                                         Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2018                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2019                                                 SV_VM_Begin();
2020                                                 SV_SendServerinfo(client);
2021                                                 SV_VM_End();
2022                                         }
2023                                         else
2024                                         {
2025                                                 // client is still trying to connect,
2026                                                 // so we send a duplicate reply
2027                                                 if (developer.integer >= 10)
2028                                                         Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2029                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2030                                         }
2031                                         return true;
2032                                 }
2033                         }
2034
2035                         if (NetConn_PreventConnectFlood(peeraddress))
2036                                 return true;
2037
2038                         // find an empty client slot for this new client
2039                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2040                         {
2041                                 netconn_t *conn;
2042                                 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2043                                 {
2044                                         // allocated connection
2045                                         if (developer.integer >= 10)
2046                                                 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2047                                         NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2048                                         // now set up the client
2049                                         SV_VM_Begin();
2050                                         SV_ConnectClient(clientnum, conn);
2051                                         SV_VM_End();
2052                                         NetConn_Heartbeat(1);
2053                                         return true;
2054                                 }
2055                         }
2056
2057                         // no empty slots found - server is full
2058                         if (developer.integer >= 10)
2059                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2060                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2061
2062                         return true;
2063                 }
2064                 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2065                 {
2066                         const char *challenge = NULL;
2067
2068                         // If there was a challenge in the getinfo message
2069                         if (length > 8 && string[7] == ' ')
2070                                 challenge = string + 8;
2071
2072                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2073                         {
2074                                 if (developer.integer >= 10)
2075                                         Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2076                                 NetConn_WriteString(mysocket, response, peeraddress);
2077                         }
2078                         return true;
2079                 }
2080                 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2081                 {
2082                         const char *challenge = NULL;
2083
2084                         // If there was a challenge in the getinfo message
2085                         if (length > 10 && string[9] == ' ')
2086                                 challenge = string + 10;
2087
2088                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2089                         {
2090                                 if (developer.integer >= 10)
2091                                         Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2092                                 NetConn_WriteString(mysocket, response, peeraddress);
2093                         }
2094                         return true;
2095                 }
2096                 if (length >= 5 && !memcmp(string, "rcon ", 5))
2097                 {
2098                         int i;
2099                         char *s = string + 5;
2100                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2101                         char password[64];
2102                         for (i = 0;*s > ' ';s++)
2103                                 if (i < (int)sizeof(password) - 1)
2104                                         password[i++] = *s;
2105                         if(*s <= ' ' && s != endpos) // skip leading ugly space
2106                                 ++s;
2107                         password[i] = 0;
2108                         if (password[0] > ' ' && !strcmp(rcon_password.string, password))
2109                         {
2110                                 // looks like a legitimate rcon command with the correct password
2111                                 char *s_ptr = s;
2112                                 Con_Printf("server received rcon command from %s:\n", host_client ? host_client->name : addressstring2);
2113                                 while(s_ptr != endpos)
2114                                 {
2115                                         size_t l = strlen(s_ptr);
2116                                         if(l)
2117                                                 Con_Printf(" %s;", s_ptr);
2118                                         s_ptr += l + 1;
2119                                 }
2120                                 Con_Printf("\n");
2121                                 rcon_redirect = true;
2122                                 rcon_redirect_bufferpos = 0;
2123                                 while(s != endpos)
2124                                 {
2125                                         size_t l = strlen(s);
2126                                         if(l)
2127                                                 Cmd_ExecuteString(s, src_command);
2128                                         s += l + 1;
2129                                 }
2130                                 rcon_redirect_buffer[rcon_redirect_bufferpos] = 0;
2131                                 rcon_redirect = false;
2132                                 // print resulting text to client
2133                                 // if client is playing, send a reliable reply instead of
2134                                 // a command packet
2135                                 if (host_client)
2136                                 {
2137                                         // if the netconnection is loop, then this is the
2138                                         // local player on a listen mode server, and it would
2139                                         // result in duplicate printing to the console
2140                                         // (not that the local player should be using rcon
2141                                         //  when they have the console)
2142                                         if (host_client->netconnection && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2143                                                 SV_ClientPrintf("%s", rcon_redirect_buffer);
2144                                 }
2145                                 else
2146                                 {
2147                                         // qw print command
2148                                         dpsnprintf(response, sizeof(response), "\377\377\377\377n%s", rcon_redirect_buffer);
2149                                         NetConn_WriteString(mysocket, response, peeraddress);
2150                                 }
2151                         }
2152                         return true;
2153                 }
2154                 if (!strncmp(string, "ping", 4))
2155                 {
2156                         if (developer.integer >= 10)
2157                                 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2158                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2159                         return true;
2160                 }
2161                 if (!strncmp(string, "ack", 3))
2162                         return true;
2163                 // we may not have liked the packet, but it was a command packet, so
2164                 // we're done processing this packet now
2165                 return true;
2166         }
2167         // netquake control packets, supported for compatibility only, and only
2168         // when running game protocols that are normally served via this connection
2169         // protocol
2170         // (this protects more modern protocols against being used for
2171         //  Quake packet flood Denial Of Service attacks)
2172         if (length >= 5 && (i = BigLong(*((int *)data))) && (i & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (i & NETFLAG_LENGTH_MASK) == length && (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3))
2173         {
2174                 int c;
2175                 int protocolnumber;
2176                 const char *protocolname;
2177                 data += 4;
2178                 length -= 4;
2179                 SZ_Clear(&net_message);
2180                 SZ_Write(&net_message, data, length);
2181                 MSG_BeginReading();
2182                 c = MSG_ReadByte();
2183                 switch (c)
2184                 {
2185                 case CCREQ_CONNECT:
2186                         if (developer.integer >= 10)
2187                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2188                         if(!islocal && sv_public.integer <= -2)
2189                                 break;
2190
2191                         protocolname = MSG_ReadString();
2192                         protocolnumber = MSG_ReadByte();
2193                         if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2194                         {
2195                                 if (developer.integer >= 10)
2196                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2197                                 SZ_Clear(&net_message);
2198                                 // save space for the header, filled in later
2199                                 MSG_WriteLong(&net_message, 0);
2200                                 MSG_WriteByte(&net_message, CCREP_REJECT);
2201                                 MSG_WriteString(&net_message, "Incompatible version.\n");
2202                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2203                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2204                                 SZ_Clear(&net_message);
2205                                 break;
2206                         }
2207
2208                         // see if this connect request comes from a known client
2209                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2210                         {
2211                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2212                                 {
2213                                         // this is either a duplicate connection request
2214                                         // or coming back from a timeout
2215                                         // (if so, keep their stuff intact)
2216
2217                                         // send a reply
2218                                         if (developer.integer >= 10)
2219                                                 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2220                                         SZ_Clear(&net_message);
2221                                         // save space for the header, filled in later
2222                                         MSG_WriteLong(&net_message, 0);
2223                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2224                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2225                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2226                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2227                                         SZ_Clear(&net_message);
2228
2229                                         // if client is already spawned, re-send the
2230                                         // serverinfo message as they'll need it to play
2231                                         if (client->spawned)
2232                                         {
2233                                                 SV_VM_Begin();
2234                                                 SV_SendServerinfo(client);
2235                                                 SV_VM_End();
2236                                         }
2237                                         return true;
2238                                 }
2239                         }
2240
2241                         // this is a new client, check for connection flood
2242                         if (NetConn_PreventConnectFlood(peeraddress))
2243                                 break;
2244
2245                         // find a slot for the new client
2246                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2247                         {
2248                                 netconn_t *conn;
2249                                 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2250                                 {
2251                                         // connect to the client
2252                                         // everything is allocated, just fill in the details
2253                                         strlcpy (conn->address, addressstring2, sizeof (conn->address));
2254                                         if (developer.integer >= 10)
2255                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2256                                         // send back the info about the server connection
2257                                         SZ_Clear(&net_message);
2258                                         // save space for the header, filled in later
2259                                         MSG_WriteLong(&net_message, 0);
2260                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2261                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2262                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2263                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2264                                         SZ_Clear(&net_message);
2265                                         // now set up the client struct
2266                                         SV_VM_Begin();
2267                                         SV_ConnectClient(clientnum, conn);
2268                                         SV_VM_End();
2269                                         NetConn_Heartbeat(1);
2270                                         return true;
2271                                 }
2272                         }
2273
2274                         if (developer.integer >= 10)
2275                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2276                         // no room; try to let player know
2277                         SZ_Clear(&net_message);
2278                         // save space for the header, filled in later
2279                         MSG_WriteLong(&net_message, 0);
2280                         MSG_WriteByte(&net_message, CCREP_REJECT);
2281                         MSG_WriteString(&net_message, "Server is full.\n");
2282                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2283                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2284                         SZ_Clear(&net_message);
2285                         break;
2286                 case CCREQ_SERVER_INFO:
2287                         if (developer.integer >= 10)
2288                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2289                         if(!islocal && sv_public.integer <= -1)
2290                                 break;
2291                         if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2292                         {
2293                                 int numclients;
2294                                 char myaddressstring[128];
2295                                 if (developer.integer >= 10)
2296                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2297                                 SZ_Clear(&net_message);
2298                                 // save space for the header, filled in later
2299                                 MSG_WriteLong(&net_message, 0);
2300                                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2301                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2302                                 MSG_WriteString(&net_message, myaddressstring);
2303                                 MSG_WriteString(&net_message, hostname.string);
2304                                 MSG_WriteString(&net_message, sv.name);
2305                                 // How many clients are there?
2306                                 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2307                                         if (svs.clients[i].active)
2308                                                 numclients++;
2309                                 MSG_WriteByte(&net_message, numclients);
2310                                 MSG_WriteByte(&net_message, svs.maxclients);
2311                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2312                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2313                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2314                                 SZ_Clear(&net_message);
2315                         }
2316                         break;
2317                 case CCREQ_PLAYER_INFO:
2318                         if (developer.integer >= 10)
2319                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2320                         if(!islocal && sv_public.integer <= -1)
2321                                 break;
2322                         if (sv.active)
2323                         {
2324                                 int playerNumber, activeNumber, clientNumber;
2325                                 client_t *client;
2326
2327                                 playerNumber = MSG_ReadByte();
2328                                 activeNumber = -1;
2329                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2330                                         if (client->active && ++activeNumber == playerNumber)
2331                                                 break;
2332                                 if (clientNumber != svs.maxclients)
2333                                 {
2334                                         SZ_Clear(&net_message);
2335                                         // save space for the header, filled in later
2336                                         MSG_WriteLong(&net_message, 0);
2337                                         MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2338                                         MSG_WriteByte(&net_message, playerNumber);
2339                                         MSG_WriteString(&net_message, client->name);
2340                                         MSG_WriteLong(&net_message, client->colors);
2341                                         MSG_WriteLong(&net_message, client->frags);
2342                                         MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2343                                         MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2344                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2345                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2346                                         SZ_Clear(&net_message);
2347                                 }
2348                         }
2349                         break;
2350                 case CCREQ_RULE_INFO:
2351                         if (developer.integer >= 10)
2352                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2353                         if(!islocal && sv_public.integer <= -1)
2354                                 break;
2355                         if (sv.active)
2356                         {
2357                                 char *prevCvarName;
2358                                 cvar_t *var;
2359
2360                                 // find the search start location
2361                                 prevCvarName = MSG_ReadString();
2362                                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2363
2364                                 // send the response
2365                                 SZ_Clear(&net_message);
2366                                 // save space for the header, filled in later
2367                                 MSG_WriteLong(&net_message, 0);
2368                                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2369                                 if (var)
2370                                 {
2371                                         MSG_WriteString(&net_message, var->name);
2372                                         MSG_WriteString(&net_message, var->string);
2373                                 }
2374                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2375                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2376                                 SZ_Clear(&net_message);
2377                         }
2378                         break;
2379                 default:
2380                         break;
2381                 }
2382                 SZ_Clear(&net_message);
2383                 // we may not have liked the packet, but it was a valid control
2384                 // packet, so we're done processing this packet now
2385                 return true;
2386         }
2387         if (host_client)
2388         {
2389                 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2390                 {
2391                         SV_VM_Begin();
2392                         SV_ReadClientMessage();
2393                         SV_VM_End();
2394                         return ret;
2395                 }
2396         }
2397         return 0;
2398 }
2399
2400 void NetConn_ServerFrame(void)
2401 {
2402         int i, length;
2403         lhnetaddress_t peeraddress;
2404         for (i = 0;i < sv_numsockets;i++)
2405                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2406                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2407         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2408         {
2409                 // never timeout loopback connections
2410                 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2411                 {
2412                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2413                         SV_VM_Begin();
2414                         SV_DropClient(false);
2415                         SV_VM_End();
2416                 }
2417         }
2418 }
2419
2420 void NetConn_SleepMicroseconds(int microseconds)
2421 {
2422         LHNET_SleepUntilPacket_Microseconds(microseconds);
2423 }
2424
2425 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2426 {
2427         int i;
2428         int masternum;
2429         lhnetaddress_t masteraddress;
2430         lhnetaddress_t broadcastaddress;
2431         char request[256];
2432
2433         if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2434                 return;
2435
2436         // 26000 is the default quake server port, servers on other ports will not
2437         // be found
2438         // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2439         LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2440
2441         if (querydp)
2442         {
2443                 for (i = 0;i < cl_numsockets;i++)
2444                 {
2445                         if (cl_sockets[i])
2446                         {
2447                                 // search LAN for Quake servers
2448                                 SZ_Clear(&net_message);
2449                                 // save space for the header, filled in later
2450                                 MSG_WriteLong(&net_message, 0);
2451                                 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2452                                 MSG_WriteString(&net_message, "QUAKE");
2453                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2454                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2455                                 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2456                                 SZ_Clear(&net_message);
2457
2458                                 // search LAN for DarkPlaces servers
2459                                 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
2460
2461                                 // build the getservers message to send to the dpmaster master servers
2462                                 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
2463
2464                                 // search internet
2465                                 for (masternum = 0;sv_masters[masternum].name;masternum++)
2466                                 {
2467                                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2468                                         {
2469                                                 masterquerycount++;
2470                                                 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2471                                         }
2472                                 }
2473                         }
2474                 }
2475         }
2476
2477         // only query QuakeWorld servers when the user wants to
2478         if (queryqw)
2479         {
2480                 for (i = 0;i < cl_numsockets;i++)
2481                 {
2482                         if (cl_sockets[i])
2483                         {
2484                                 // search LAN for QuakeWorld servers
2485                                 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2486
2487                                 // build the getservers message to send to the qwmaster master servers
2488                                 // note this has no -1 prefix, and the trailing nul byte is sent
2489                                 dpsnprintf(request, sizeof(request), "c\n");
2490
2491                                 // search internet
2492                                 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2493                                 {
2494                                         if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2495                                         {
2496                                                 if (m_state != m_slist)
2497                                                 {
2498                                                         char lookupstring[128];
2499                                                         LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2500                                                         Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2501                                                 }
2502                                                 masterquerycount++;
2503                                                 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2504                                         }
2505                                 }
2506                         }
2507                 }
2508         }
2509         if (!masterquerycount)
2510         {
2511                 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2512                 M_Update_Return_Reason("No network");
2513         }
2514 }
2515
2516 void NetConn_Heartbeat(int priority)
2517 {
2518         lhnetaddress_t masteraddress;
2519         int masternum;
2520         lhnetsocket_t *mysocket;
2521
2522         // if it's a state change (client connected), limit next heartbeat to no
2523         // more than 30 sec in the future
2524         if (priority == 1 && nextheartbeattime > realtime + 30.0)
2525                 nextheartbeattime = realtime + 30.0;
2526
2527         // limit heartbeatperiod to 30 to 270 second range,
2528         // lower limit is to avoid abusing master servers with excess traffic,
2529         // upper limit is to avoid timing out on the master server (which uses
2530         // 300 sec timeout)
2531         if (sv_heartbeatperiod.value < 30)
2532                 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
2533         if (sv_heartbeatperiod.value > 270)
2534                 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
2535
2536         // make advertising optional and don't advertise singleplayer games, and
2537         // only send a heartbeat as often as the admin wants
2538         if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
2539         {
2540                 nextheartbeattime = realtime + sv_heartbeatperiod.value;
2541                 for (masternum = 0;sv_masters[masternum].name;masternum++)
2542                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
2543                                 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
2544         }
2545 }
2546
2547 static void Net_Heartbeat_f(void)
2548 {
2549         if (sv.active)
2550                 NetConn_Heartbeat(2);
2551         else
2552                 Con_Print("No server running, can not heartbeat to master server.\n");
2553 }
2554
2555 void PrintStats(netconn_t *conn)
2556 {
2557         if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
2558                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->qw.outgoing_sequence, conn->qw.incoming_sequence);
2559         else
2560                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
2561 }
2562
2563 void Net_Stats_f(void)
2564 {
2565         netconn_t *conn;
2566         Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
2567         Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
2568         Con_Printf("reliable messages sent     = %i\n", reliableMessagesSent);
2569         Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
2570         Con_Printf("packetsSent                = %i\n", packetsSent);
2571         Con_Printf("packetsReSent              = %i\n", packetsReSent);
2572         Con_Printf("packetsReceived            = %i\n", packetsReceived);
2573         Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
2574         Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
2575         Con_Print("connections                =\n");
2576         for (conn = netconn_list;conn;conn = conn->next)
2577                 PrintStats(conn);
2578 }
2579
2580 void Net_Slist_f(void)
2581 {
2582         ServerList_ResetMasks();
2583         serverlist_sortbyfield = SLIF_PING;
2584         serverlist_sortdescending = false;
2585     if (m_state != m_slist) {
2586                 Con_Print("Sending requests to master servers\n");
2587                 ServerList_QueryList(true, false);
2588                 serverlist_consoleoutput = true;
2589                 Con_Print("Listening for replies...\n");
2590         } else
2591                 ServerList_QueryList(true, false);
2592 }
2593
2594 void Net_SlistQW_f(void)
2595 {
2596         ServerList_ResetMasks();
2597         serverlist_sortbyfield = SLIF_PING;
2598         serverlist_sortdescending = false;
2599     if (m_state != m_slist) {
2600                 Con_Print("Sending requests to master servers\n");
2601                 ServerList_QueryList(false, true);
2602                 serverlist_consoleoutput = true;
2603                 Con_Print("Listening for replies...\n");
2604         } else
2605                 ServerList_QueryList(false, true);
2606 }
2607
2608 void NetConn_Init(void)
2609 {
2610         int i;
2611         lhnetaddress_t tempaddress;
2612         netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
2613         Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
2614         Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
2615         Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
2616         Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
2617         Cvar_RegisterVariable(&net_slist_queriespersecond);
2618         Cvar_RegisterVariable(&net_slist_queriesperframe);
2619         Cvar_RegisterVariable(&net_slist_timeout);
2620         Cvar_RegisterVariable(&net_slist_maxtries);
2621         Cvar_RegisterVariable(&net_messagetimeout);
2622         Cvar_RegisterVariable(&net_connecttimeout);
2623         Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
2624         Cvar_RegisterVariable(&cl_netlocalping);
2625         Cvar_RegisterVariable(&cl_netpacketloss_send);
2626         Cvar_RegisterVariable(&cl_netpacketloss_receive);
2627         Cvar_RegisterVariable(&hostname);
2628         Cvar_RegisterVariable(&developer_networking);
2629         Cvar_RegisterVariable(&cl_netport);
2630         Cvar_RegisterVariable(&sv_netport);
2631         Cvar_RegisterVariable(&net_address);
2632         //Cvar_RegisterVariable(&net_address_ipv6);
2633         Cvar_RegisterVariable(&sv_public);
2634         Cvar_RegisterVariable(&sv_heartbeatperiod);
2635         for (i = 0;sv_masters[i].name;i++)
2636                 Cvar_RegisterVariable(&sv_masters[i]);
2637         Cvar_RegisterVariable(&gameversion);
2638 // COMMANDLINEOPTION: Server: -ip <ipaddress> sets the ip address of this machine for purposes of networking (default 0.0.0.0 also known as INADDR_ANY), use only if you have multiple network adapters and need to choose one specifically.
2639         if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
2640         {
2641                 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
2642                 {
2643                         Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
2644                         Cvar_SetQuick(&net_address, com_argv[i + 1]);
2645                 }
2646                 else
2647                         Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
2648         }
2649 // COMMANDLINEOPTION: Server: -port <portnumber> sets the port to use for a server (default 26000, the same port as QUAKE itself), useful if you host multiple servers on your machine
2650         if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
2651         {
2652                 i = atoi(com_argv[i + 1]);
2653                 if (i >= 0 && i < 65536)
2654                 {
2655                         Con_Printf("-port option used, setting port cvar to %i\n", i);
2656                         Cvar_SetValueQuick(&sv_netport, i);
2657                 }
2658                 else
2659                         Con_Printf("-port option used, but %i is not a valid port number\n", i);
2660         }
2661         cl_numsockets = 0;
2662         sv_numsockets = 0;
2663         net_message.data = net_message_buf;
2664         net_message.maxsize = sizeof(net_message_buf);
2665         net_message.cursize = 0;
2666         LHNET_Init();
2667 }
2668
2669 void NetConn_Shutdown(void)
2670 {
2671         NetConn_CloseClientPorts();
2672         NetConn_CloseServerPorts();
2673         LHNET_Shutdown();
2674 }
2675