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