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