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