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