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