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