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