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