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