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