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