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