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