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