]> icculus.org git repositories - divverent/darkplaces.git/blob - netconn.c
increased IP + UDP header overhead estimate from 18 bytes to 28 bytes
[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)
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)
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                         if (data->cursize)
701                                 totallen += packetLen + 28;
702                 }
703         }
704
705         // delay later packets to obey rate limit
706         if (conn->cleartime < realtime - 0.1)
707                 conn->cleartime = realtime - 0.1;
708         conn->cleartime = conn->cleartime + (double)totallen / (double)rate;
709         if (conn->cleartime < realtime)
710                 conn->cleartime = realtime;
711
712         return 0;
713 }
714
715 void NetConn_CloseClientPorts(void)
716 {
717         for (;cl_numsockets > 0;cl_numsockets--)
718                 if (cl_sockets[cl_numsockets - 1])
719                         LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
720 }
721
722 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
723 {
724         lhnetaddress_t address;
725         lhnetsocket_t *s;
726         char addressstring2[1024];
727         if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
728         {
729                 if ((s = LHNET_OpenSocket_Connectionless(&address)))
730                 {
731                         cl_sockets[cl_numsockets++] = s;
732                         LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
733                         Con_Printf("Client opened a socket on address %s\n", addressstring2);
734                 }
735                 else
736                 {
737                         LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
738                         Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
739                 }
740         }
741         else
742                 Con_Printf("Client unable to parse address %s\n", addressstring);
743 }
744
745 void NetConn_OpenClientPorts(void)
746 {
747         int port;
748         NetConn_CloseClientPorts();
749         port = bound(0, cl_netport.integer, 65535);
750         if (cl_netport.integer != port)
751                 Cvar_SetValueQuick(&cl_netport, port);
752         Con_Printf("Client using port %i\n", port);
753         NetConn_OpenClientPort("local:2", 0);
754         NetConn_OpenClientPort(net_address.string, port);
755         //NetConn_OpenClientPort(net_address_ipv6.string, port);
756 }
757
758 void NetConn_CloseServerPorts(void)
759 {
760         for (;sv_numsockets > 0;sv_numsockets--)
761                 if (sv_sockets[sv_numsockets - 1])
762                         LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
763 }
764
765 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
766 {
767         lhnetaddress_t address;
768         lhnetsocket_t *s;
769         int port;
770         char addressstring2[1024];
771
772         for (port = defaultport; port <= defaultport + 100; port++)
773         {
774                 if (LHNETADDRESS_FromString(&address, addressstring, port))
775                 {
776                         if ((s = LHNET_OpenSocket_Connectionless(&address)))
777                         {
778                                 sv_sockets[sv_numsockets++] = s;
779                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
780                                 Con_Printf("Server listening on address %s\n", addressstring2);
781                                 break;
782                         }
783                         else
784                         {
785                                 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
786                                 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
787                         }
788                 }
789                 else
790                 {
791                         Con_Printf("Server unable to parse address %s\n", addressstring);
792                         // if it cant parse one address, it wont be able to parse another for sure
793                         break;
794                 }
795         }
796 }
797
798 void NetConn_OpenServerPorts(int opennetports)
799 {
800         int port;
801         NetConn_CloseServerPorts();
802         NetConn_UpdateSockets();
803         port = bound(0, sv_netport.integer, 65535);
804         if (port == 0)
805                 port = 26000;
806         Con_Printf("Server using port %i\n", port);
807         if (sv_netport.integer != port)
808                 Cvar_SetValueQuick(&sv_netport, port);
809         if (cls.state != ca_dedicated)
810                 NetConn_OpenServerPort("local:1", 0);
811         if (opennetports)
812         {
813                 NetConn_OpenServerPort(net_address.string, port);
814                 //NetConn_OpenServerPort(net_address_ipv6.string, port);
815         }
816         if (sv_numsockets == 0)
817                 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
818 }
819
820 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
821 {
822         int i, a = LHNETADDRESS_GetAddressType(address);
823         for (i = 0;i < cl_numsockets;i++)
824                 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
825                         return cl_sockets[i];
826         return NULL;
827 }
828
829 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
830 {
831         int i, a = LHNETADDRESS_GetAddressType(address);
832         for (i = 0;i < sv_numsockets;i++)
833                 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
834                         return sv_sockets[i];
835         return NULL;
836 }
837
838 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
839 {
840         netconn_t *conn;
841         conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
842         conn->mysocket = mysocket;
843         conn->peeraddress = *peeraddress;
844         conn->lastMessageTime = realtime;
845         conn->message.data = conn->messagedata;
846         conn->message.maxsize = sizeof(conn->messagedata);
847         conn->message.cursize = 0;
848         // LordHavoc: (inspired by ProQuake) use a short connect timeout to
849         // reduce effectiveness of connection request floods
850         conn->timeout = realtime + net_connecttimeout.value;
851         LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
852         conn->next = netconn_list;
853         netconn_list = conn;
854         return conn;
855 }
856
857 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
858 void NetConn_Close(netconn_t *conn)
859 {
860         netconn_t *c;
861         // remove connection from list
862
863         // allow the client to reconnect immediately
864         NetConn_ClearConnectFlood(&(conn->peeraddress));
865
866         if (conn == netconn_list)
867                 netconn_list = conn->next;
868         else
869         {
870                 for (c = netconn_list;c;c = c->next)
871                 {
872                         if (c->next == conn)
873                         {
874                                 c->next = conn->next;
875                                 break;
876                         }
877                 }
878                 // not found in list, we'll avoid crashing here...
879                 if (!c)
880                         return;
881         }
882         // free connection
883         Mem_Free(conn);
884 }
885
886 static int clientport = -1;
887 static int clientport2 = -1;
888 static int hostport = -1;
889 void NetConn_UpdateSockets(void)
890 {
891         if (cls.state != ca_dedicated)
892         {
893                 if (clientport2 != cl_netport.integer)
894                 {
895                         clientport2 = cl_netport.integer;
896                         if (cls.state == ca_connected)
897                                 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
898                 }
899                 if (cls.state == ca_disconnected && clientport != clientport2)
900                 {
901                         clientport = clientport2;
902                         NetConn_CloseClientPorts();
903                 }
904                 if (cl_numsockets == 0)
905                         NetConn_OpenClientPorts();
906         }
907
908         if (hostport != sv_netport.integer)
909         {
910                 hostport = sv_netport.integer;
911                 if (sv.active)
912                         Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
913         }
914 }
915
916 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
917 {
918         int originallength = length;
919         if (length < 8)
920                 return 0;
921
922         // TODO: add netgraph stuff rather than just packetloss counting...
923
924         if (protocol == PROTOCOL_QUAKEWORLD)
925         {
926                 int sequence, sequence_ack;
927                 int reliable_ack, reliable_message;
928                 int count;
929                 int qport;
930
931                 sequence = LittleLong(*((int *)(data + 0)));
932                 sequence_ack = LittleLong(*((int *)(data + 4)));
933                 data += 8;
934                 length -= 8;
935
936                 if (conn != cls.netcon)
937                 {
938                         // server only
939                         if (length < 2)
940                                 return 0;
941                         // 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?)
942                         qport = LittleShort(*((int *)(data + 8)));
943                         data += 2;
944                         length -= 2;
945                 }
946
947                 packetsReceived++;
948                 reliable_message = (sequence >> 31) & 1;
949                 reliable_ack = (sequence_ack >> 31) & 1;
950                 sequence &= ~(1<<31);
951                 sequence_ack &= ~(1<<31);
952                 if (sequence <= conn->qw.incoming_sequence)
953                 {
954                         //Con_DPrint("Got a stale datagram\n");
955                         return 0;
956                 }
957                 count = sequence - (conn->qw.incoming_sequence + 1);
958                 if (count > 0)
959                 {
960                         droppedDatagrams += count;
961                         //Con_DPrintf("Dropped %u datagram(s)\n", count);
962                         while (count--)
963                         {
964                                 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
965                                 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
966                                 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
967                                 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
968                         }
969                 }
970                 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
971                 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
972                 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
973                 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
974                 if (reliable_ack == conn->qw.reliable_sequence)
975                 {
976                         // received, now we will be able to send another reliable message
977                         conn->sendMessageLength = 0;
978                         reliableMessagesReceived++;
979                 }
980                 conn->qw.incoming_sequence = sequence;
981                 if (conn == cls.netcon)
982                         cls.qw_incoming_sequence = conn->qw.incoming_sequence;
983                 conn->qw.incoming_acknowledged = sequence_ack;
984                 conn->qw.incoming_reliable_acknowledged = reliable_ack;
985                 if (reliable_message)
986                         conn->qw.incoming_reliable_sequence ^= 1;
987                 conn->lastMessageTime = realtime;
988                 conn->timeout = realtime + newtimeout;
989                 unreliableMessagesReceived++;
990                 SZ_Clear(&net_message);
991                 SZ_Write(&net_message, data, length);
992                 MSG_BeginReading();
993                 return 2;
994         }
995         else
996         {
997                 unsigned int count;
998                 unsigned int flags;
999                 unsigned int sequence;
1000                 int qlength;
1001
1002                 qlength = (unsigned int)BigLong(((int *)data)[0]);
1003                 flags = qlength & ~NETFLAG_LENGTH_MASK;
1004                 qlength &= NETFLAG_LENGTH_MASK;
1005                 // control packets were already handled
1006                 if (!(flags & NETFLAG_CTL) && qlength == length)
1007                 {
1008                         sequence = BigLong(((int *)data)[1]);
1009                         packetsReceived++;
1010                         data += 8;
1011                         length -= 8;
1012                         if (flags & NETFLAG_UNRELIABLE)
1013                         {
1014                                 if (sequence >= conn->nq.unreliableReceiveSequence)
1015                                 {
1016                                         if (sequence > conn->nq.unreliableReceiveSequence)
1017                                         {
1018                                                 count = sequence - conn->nq.unreliableReceiveSequence;
1019                                                 droppedDatagrams += count;
1020                                                 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1021                                                 while (count--)
1022                                                 {
1023                                                         conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1024                                                         conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1025                                                         conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1026                                                         conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1027                                                 }
1028                                         }
1029                                         conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1030                                         conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1031                                         conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1032                                         conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1033                                         conn->nq.unreliableReceiveSequence = sequence + 1;
1034                                         conn->lastMessageTime = realtime;
1035                                         conn->timeout = realtime + newtimeout;
1036                                         unreliableMessagesReceived++;
1037                                         if (length > 0)
1038                                         {
1039                                                 SZ_Clear(&net_message);
1040                                                 SZ_Write(&net_message, data, length);
1041                                                 MSG_BeginReading();
1042                                                 return 2;
1043                                         }
1044                                 }
1045                                 //else
1046                                 //      Con_DPrint("Got a stale datagram\n");
1047                                 return 1;
1048                         }
1049                         else if (flags & NETFLAG_ACK)
1050                         {
1051                                 conn->incoming_acksize[conn->incoming_packetcounter] += originallength;
1052                                 if (sequence == (conn->nq.sendSequence - 1))
1053                                 {
1054                                         if (sequence == conn->nq.ackSequence)
1055                                         {
1056                                                 conn->nq.ackSequence++;
1057                                                 if (conn->nq.ackSequence != conn->nq.sendSequence)
1058                                                         Con_DPrint("ack sequencing error\n");
1059                                                 conn->lastMessageTime = realtime;
1060                                                 conn->timeout = realtime + newtimeout;
1061                                                 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1062                                                 {
1063                                                         unsigned int packetLen;
1064                                                         unsigned int dataLen;
1065                                                         unsigned int eom;
1066                                                         unsigned int *header;
1067
1068                                                         conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1069                                                         memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1070
1071                                                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1072                                                         {
1073                                                                 dataLen = conn->sendMessageLength;
1074                                                                 eom = NETFLAG_EOM;
1075                                                         }
1076                                                         else
1077                                                         {
1078                                                                 dataLen = MAX_PACKETFRAGMENT;
1079                                                                 eom = 0;
1080                                                         }
1081
1082                                                         packetLen = NET_HEADERSIZE + dataLen;
1083
1084                                                         header = (unsigned int *)sendbuffer;
1085                                                         header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1086                                                         header[1] = BigLong(conn->nq.sendSequence);
1087                                                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1088
1089                                                         conn->nq.sendSequence++;
1090
1091                                                         if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1092                                                         {
1093                                                                 conn->lastSendTime = realtime;
1094                                                                 packetsSent++;
1095                                                         }
1096                                                 }
1097                                                 else
1098                                                         conn->sendMessageLength = 0;
1099                                         }
1100                                         //else
1101                                         //      Con_DPrint("Duplicate ACK received\n");
1102                                 }
1103                                 //else
1104                                 //      Con_DPrint("Stale ACK received\n");
1105                                 return 1;
1106                         }
1107                         else if (flags & NETFLAG_DATA)
1108                         {
1109                                 unsigned int temppacket[2];
1110                                 conn->incoming_reliablesize[conn->incoming_packetcounter] += originallength;
1111                                 conn->outgoing_acksize[conn->outgoing_packetcounter] += 8;
1112                                 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1113                                 temppacket[1] = BigLong(sequence);
1114                                 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1115                                 if (sequence == conn->nq.receiveSequence)
1116                                 {
1117                                         conn->lastMessageTime = realtime;
1118                                         conn->timeout = realtime + newtimeout;
1119                                         conn->nq.receiveSequence++;
1120                                         if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1121                                                 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1122                                                 conn->receiveMessageLength += length;
1123                                         } else {
1124                                                 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1125                                                                         "Dropping the message!\n", sequence );
1126                                                 conn->receiveMessageLength = 0;
1127                                                 return 1;
1128                                         }
1129                                         if (flags & NETFLAG_EOM)
1130                                         {
1131                                                 reliableMessagesReceived++;
1132                                                 length = conn->receiveMessageLength;
1133                                                 conn->receiveMessageLength = 0;
1134                                                 if (length > 0)
1135                                                 {
1136                                                         SZ_Clear(&net_message);
1137                                                         SZ_Write(&net_message, conn->receiveMessage, length);
1138                                                         MSG_BeginReading();
1139                                                         return 2;
1140                                                 }
1141                                         }
1142                                 }
1143                                 else
1144                                         receivedDuplicateCount++;
1145                                 return 1;
1146                         }
1147                 }
1148         }
1149         return 0;
1150 }
1151
1152 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1153 {
1154         cls.connect_trying = false;
1155         M_Update_Return_Reason("");
1156         // the connection request succeeded, stop current connection and set up a new connection
1157         CL_Disconnect();
1158         // if we're connecting to a remote server, shut down any local server
1159         if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1160                 Host_ShutdownServer ();
1161         // allocate a net connection to keep track of things
1162         cls.netcon = NetConn_Open(mysocket, peeraddress);
1163         Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1164         key_dest = key_game;
1165         m_state = m_none;
1166         cls.demonum = -1;                       // not in the demo loop now
1167         cls.state = ca_connected;
1168         cls.signon = 0;                         // need all the signon messages before playing
1169         cls.protocol = initialprotocol;
1170         // reset move sequence numbering on this new connection
1171         cls.movesequence = 0;
1172         cls.servermovesequence = 0;
1173         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1174                 Cmd_ForwardStringToServer("new");
1175         if (cls.protocol == PROTOCOL_QUAKE)
1176         {
1177                 // write a keepalive (clc_nop) as it seems to greatly improve the
1178                 // chances of connecting to a netquake server
1179                 sizebuf_t msg;
1180                 unsigned char buf[4];
1181                 memset(&msg, 0, sizeof(msg));
1182                 msg.data = buf;
1183                 msg.maxsize = sizeof(buf);
1184                 MSG_WriteChar(&msg, clc_nop);
1185                 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000);
1186         }
1187 }
1188
1189 int NetConn_IsLocalGame(void)
1190 {
1191         if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1192                 return true;
1193         return false;
1194 }
1195
1196 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1197 {
1198         int n;
1199         int pingtime;
1200         // search the cache for this server and update it
1201         for (n = 0;n < serverlist_cachecount;n++)
1202                 if (!strcmp(addressstring, serverlist_cache[n].info.cname))
1203                         break;
1204         if (n == serverlist_cachecount)
1205         {
1206                 // LAN search doesnt require an answer from the master server so we wont
1207                 // know the ping nor will it be initialized already...
1208
1209                 // find a slot
1210                 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1211                         return -1;
1212
1213                 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1214                 // store the data the engine cares about (address and ping)
1215                 strlcpy(serverlist_cache[serverlist_cachecount].info.cname, addressstring, sizeof(serverlist_cache[serverlist_cachecount].info.cname));
1216                 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1217                 serverlist_cache[serverlist_cachecount].querytime = realtime;
1218                 // if not in the slist menu we should print the server to console
1219                 if (serverlist_consoleoutput)
1220                         Con_Printf("querying %s\n", addressstring);
1221                 ++serverlist_cachecount;
1222         }
1223         // if this is the first reply from this server, count it as having replied
1224         if (serverlist_cache[n].info.ping == 100000)
1225                 serverreplycount++;
1226         pingtime = (int)((realtime - serverlist_cache[n].querytime) * 1000.0 + 0.5);
1227         pingtime = bound(0, pingtime, 9999);
1228         // update the ping
1229         serverlist_cache[n].info.ping = min(serverlist_cache[n].info.ping, pingtime);
1230         // other server info is updated by the caller
1231         return n;
1232 }
1233
1234 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1235 {
1236         serverlist_info_t *info = &serverlist_cache[n].info;
1237         // update description strings for engine menu and console output
1238         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);
1239         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);
1240         if (serverlist_cache[n].query == SQS_QUERIED)
1241                 ServerList_ViewList_Remove(&serverlist_cache[n]);
1242         // if not in the slist menu we should print the server to console (if wanted)
1243         else if( serverlist_consoleoutput )
1244                 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1245         // and finally, update the view set
1246         ServerList_ViewList_Insert( &serverlist_cache[n] );
1247         serverlist_cache[n].query = SQS_QUERIED;
1248 }
1249
1250 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1251 {
1252         qboolean fromserver;
1253         int ret, c, control;
1254         const char *s;
1255         char *string, addressstring2[128], ipstring[32];
1256         char stringbuf[16384];
1257
1258         // quakeworld ingame packet
1259         fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1260
1261         // convert the address to a string incase we need it
1262         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1263
1264         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1265         {
1266                 // received a command string - strip off the packaging and put it
1267                 // into our string buffer with NULL termination
1268                 data += 4;
1269                 length -= 4;
1270                 length = min(length, (int)sizeof(stringbuf) - 1);
1271                 memcpy(stringbuf, data, length);
1272                 stringbuf[length] = 0;
1273                 string = stringbuf;
1274
1275                 if (developer_networking.integer)
1276                 {
1277                         Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1278                         Com_HexDumpToConsole(data, length);
1279                 }
1280
1281                 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1282                 {
1283                         // darkplaces or quake3
1284                         char protocolnames[1400];
1285                         Protocol_Names(protocolnames, sizeof(protocolnames));
1286                         Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1287                         M_Update_Return_Reason("Got challenge response");
1288                         // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1289                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1290                         // TODO: add userinfo stuff here instead of using NQ commands?
1291                         NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1292                         return true;
1293                 }
1294                 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1295                 {
1296                         // darkplaces or quake3
1297                         M_Update_Return_Reason("Accepted");
1298                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1299                         return true;
1300                 }
1301                 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1302                 {
1303                         char rejectreason[32];
1304                         cls.connect_trying = false;
1305                         string += 7;
1306                         length = max(length - 7, (int)sizeof(rejectreason) - 1);
1307                         memcpy(rejectreason, string, length);
1308                         rejectreason[length] = 0;
1309                         M_Update_Return_Reason(rejectreason);
1310                         return true;
1311                 }
1312                 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1313                 {
1314                         serverlist_info_t *info;
1315                         int n;
1316
1317                         string += 13;
1318                         // search the cache for this server and update it
1319                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1320                         if (n < 0)
1321                                 return true;
1322
1323                         info = &serverlist_cache[n].info;
1324                         info->game[0] = 0;
1325                         info->mod[0]  = 0;
1326                         info->map[0]  = 0;
1327                         info->name[0] = 0;
1328                         info->protocol = -1;
1329                         info->numplayers = 0;
1330                         info->numbots = -1;
1331                         info->maxplayers  = 0;
1332                         info->gameversion = 0;
1333                         if ((s = SearchInfostring(string, "gamename"     )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1334                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1335                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1336                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1337                         if ((s = SearchInfostring(string, "protocol"     )) != NULL) info->protocol = atoi(s);
1338                         if ((s = SearchInfostring(string, "clients"      )) != NULL) info->numplayers = atoi(s);
1339                         if ((s = SearchInfostring(string, "bots"         )) != NULL) info->numbots = atoi(s);
1340                         if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1341                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);
1342                         info->numhumans = info->numplayers - max(0, info->numbots);
1343
1344                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1345
1346                         return true;
1347                 }
1348                 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1349                 {
1350                         // Extract the IP addresses
1351                         data += 18;
1352                         length -= 18;
1353                         masterreplycount++;
1354                         if (serverlist_consoleoutput)
1355                                 Con_Print("received DarkPlaces server list...\n");
1356                         while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1357                         {
1358                                 int n;
1359
1360                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], data[5] * 256 + data[6]);
1361                                 if (serverlist_consoleoutput && developer_networking.integer)
1362                                         Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1363                                 // ignore the rest of the message if the serverlist is full
1364                                 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1365                                         break;
1366                                 // also ignore it if we have already queried it (other master server response)
1367                                 for( n = 0 ; n < serverlist_cachecount ; n++ )
1368                                         if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1369                                                 break;
1370                                 if( n >= serverlist_cachecount )
1371                                 {
1372                                         serverquerycount++;
1373
1374                                         memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1375                                         serverlist_cache[serverlist_cachecount].protocol = PROTOCOL_DARKPLACES7;
1376                                         // store the data the engine cares about (address and ping)
1377                                         strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1378                                         serverlist_cache[serverlist_cachecount].info.ping = 100000;
1379                                         serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1380
1381                                         ++serverlist_cachecount;
1382                                 }
1383
1384                                 // move on to next address in packet
1385                                 data += 7;
1386                                 length -= 7;
1387                         }
1388                         // begin or resume serverlist queries
1389                         serverlist_querysleep = false;
1390                         serverlist_querywaittime = realtime + 3;
1391                         return true;
1392                 }
1393                 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1394                 {
1395                         // Extract the IP addresses
1396                         data += 2;
1397                         length -= 2;
1398                         masterreplycount++;
1399                         if (serverlist_consoleoutput)
1400                                 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1401                         while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1402                         {
1403                                 int n;
1404
1405                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1406                                 if (serverlist_consoleoutput && developer_networking.integer)
1407                                         Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1408                                 // ignore the rest of the message if the serverlist is full
1409                                 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1410                                         break;
1411                                 // also ignore it if we have already queried it (other master server response)
1412                                 for( n = 0 ; n < serverlist_cachecount ; n++ )
1413                                         if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1414                                                 break;
1415                                 if( n >= serverlist_cachecount )
1416                                 {
1417                                         serverquerycount++;
1418
1419                                         memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1420                                         serverlist_cache[serverlist_cachecount].protocol = PROTOCOL_QUAKEWORLD;
1421                                         // store the data the engine cares about (address and ping)
1422                                         strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1423                                         serverlist_cache[serverlist_cachecount].info.ping = 100000;
1424                                         serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1425
1426                                         ++serverlist_cachecount;
1427                                 }
1428
1429                                 // move on to next address in packet
1430                                 data += 6;
1431                                 length -= 6;
1432                         }
1433                         // begin or resume serverlist queries
1434                         serverlist_querysleep = false;
1435                         serverlist_querywaittime = realtime + 3;
1436                         return true;
1437                 }
1438                 if (!strncmp(string, "extResponse ", 12))
1439                 {
1440                         ++net_extresponse_count;
1441                         if(net_extresponse_count > NET_EXTRESPONSE_MAX)
1442                                 net_extresponse_count = NET_EXTRESPONSE_MAX;
1443                         net_extresponse_last = (net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1444                         dpsnprintf(net_extresponse[net_extresponse_last], sizeof(net_extresponse[net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
1445                         return true;
1446                 }
1447                 if (!strncmp(string, "ping", 4))
1448                 {
1449                         if (developer.integer >= 10)
1450                                 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1451                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1452                         return true;
1453                 }
1454                 if (!strncmp(string, "ack", 3))
1455                         return true;
1456                 // QuakeWorld compatibility
1457                 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1458                 {
1459                         // challenge message
1460                         Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1461                         M_Update_Return_Reason("Got QuakeWorld challenge response");
1462                         cls.qw_qport = qport.integer;
1463                         // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1464                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1465                         NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1466                         return true;
1467                 }
1468                 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1469                 {
1470                         // accept message
1471                         M_Update_Return_Reason("QuakeWorld Accepted");
1472                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1473                         return true;
1474                 }
1475                 if (length > 2 && !memcmp(string, "n\\", 2))
1476                 {
1477                         serverlist_info_t *info;
1478                         int n;
1479
1480                         // qw server status
1481                         if (serverlist_consoleoutput && developer_networking.integer >= 2)
1482                                 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1483
1484                         string += 1;
1485                         // search the cache for this server and update it
1486                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1487                         if (n < 0)
1488                                 return true;
1489
1490                         info = &serverlist_cache[n].info;
1491                         strlcpy(info->game, "QuakeWorld", sizeof(info->game));;
1492                         if ((s = SearchInfostring(string, "*gamedir"     )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0]  = 0;
1493                         if ((s = SearchInfostring(string, "map"          )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0]  = 0;
1494                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1495                         info->protocol = 0;
1496                         info->numplayers = 0; // updated below
1497                         if ((s = SearchInfostring(string, "maxclients"   )) != NULL) info->maxplayers = atoi(s);else info->maxplayers  = 0;
1498                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1499
1500                         // count active players on server
1501                         // (we could gather more info, but we're just after the number)
1502                         s = strchr(string, '\n');
1503                         if (s)
1504                         {
1505                                 s++;
1506                                 while (s < string + length)
1507                                 {
1508                                         for (;s < string + length && *s != '\n';s++)
1509                                                 ;
1510                                         if (s >= string + length)
1511                                                 break;
1512                                         info->numplayers++;
1513                                         s++;
1514                                 }
1515                         }
1516
1517                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1518
1519                         return true;
1520                 }
1521                 if (string[0] == 'n')
1522                 {
1523                         // qw print command
1524                         Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1525                 }
1526                 // we may not have liked the packet, but it was a command packet, so
1527                 // we're done processing this packet now
1528                 return true;
1529         }
1530         // quakeworld ingame packet
1531         if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1532         {
1533                 ret = 0;
1534                 CL_ParseServerMessage();
1535                 return ret;
1536         }
1537         // netquake control packets, supported for compatibility only
1538         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1539         {
1540                 int n;
1541                 serverlist_info_t *info;
1542
1543                 data += 4;
1544                 length -= 4;
1545                 SZ_Clear(&net_message);
1546                 SZ_Write(&net_message, data, length);
1547                 MSG_BeginReading();
1548                 c = MSG_ReadByte();
1549                 switch (c)
1550                 {
1551                 case CCREP_ACCEPT:
1552                         if (developer.integer >= 10)
1553                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1554                         if (cls.connect_trying)
1555                         {
1556                                 lhnetaddress_t clientportaddress;
1557                                 clientportaddress = *peeraddress;
1558                                 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1559                                 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1560                                 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1561                                 M_Update_Return_Reason("Accepted");
1562                                 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1563                         }
1564                         break;
1565                 case CCREP_REJECT:
1566                         if (developer.integer >= 10)
1567                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1568                         cls.connect_trying = false;
1569                         M_Update_Return_Reason((char *)MSG_ReadString());
1570                         break;
1571                 case CCREP_SERVER_INFO:
1572                         if (developer.integer >= 10)
1573                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1574                         // LordHavoc: because the quake server may report weird addresses
1575                         // we just ignore it and keep the real address
1576                         MSG_ReadString();
1577                         // search the cache for this server and update it
1578                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1579                         if (n < 0)
1580                                 break;
1581
1582                         info = &serverlist_cache[n].info;
1583                         strlcpy(info->game, "Quake", sizeof(info->game));
1584                         strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1585                         strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1586                         strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1587                         info->numplayers = MSG_ReadByte();
1588                         info->maxplayers = MSG_ReadByte();
1589                         info->protocol = MSG_ReadByte();
1590
1591                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1592
1593                         break;
1594                 case CCREP_PLAYER_INFO:
1595                         // we got a CCREP_PLAYER_INFO??
1596                         //if (developer.integer >= 10)
1597                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1598                         break;
1599                 case CCREP_RULE_INFO:
1600                         // we got a CCREP_RULE_INFO??
1601                         //if (developer.integer >= 10)
1602                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1603                         break;
1604                 default:
1605                         break;
1606                 }
1607                 SZ_Clear(&net_message);
1608                 // we may not have liked the packet, but it was a valid control
1609                 // packet, so we're done processing this packet now
1610                 return true;
1611         }
1612         ret = 0;
1613         if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1614                 CL_ParseServerMessage();
1615         return ret;
1616 }
1617
1618 void NetConn_QueryQueueFrame(void)
1619 {
1620         int index;
1621         int queries;
1622         int maxqueries;
1623         double timeouttime;
1624         static double querycounter = 0;
1625
1626         if (serverlist_querysleep)
1627                 return;
1628
1629         // apply a cool down time after master server replies,
1630         // to avoid messing up the ping times on the servers
1631         if (serverlist_querywaittime > realtime)
1632                 return;
1633
1634         // each time querycounter reaches 1.0 issue a query
1635         querycounter += cl.realframetime * net_slist_queriespersecond.value;
1636         maxqueries = (int)querycounter;
1637         maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1638         querycounter -= maxqueries;
1639
1640         if( maxqueries == 0 ) {
1641                 return;
1642         }
1643
1644         // scan serverlist and issue queries as needed
1645     serverlist_querysleep = true;
1646
1647         timeouttime = realtime - net_slist_timeout.value;
1648         for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1649         {
1650                 serverlist_entry_t *entry = &serverlist_cache[ index ];
1651                 if( entry->query != SQS_QUERYING )
1652                 {
1653                         continue;
1654                 }
1655
1656         serverlist_querysleep = false;
1657                 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1658                 {
1659                         continue;
1660                 }
1661
1662                 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1663                 {
1664                         lhnetaddress_t address;
1665                         int socket;
1666
1667                         LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1668                         if (entry->protocol == PROTOCOL_QUAKEWORLD)
1669                         {
1670                                 for (socket = 0; socket < cl_numsockets ; socket++)
1671                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1672                         }
1673                         else
1674                         {
1675                                 for (socket = 0; socket < cl_numsockets ; socket++)
1676                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address);
1677                         }
1678
1679                         entry->querytime = realtime;
1680                         entry->querycounter++;
1681
1682                         // if not in the slist menu we should print the server to console
1683                         if (serverlist_consoleoutput)
1684                                 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1685
1686                         queries++;
1687                 }
1688                 else
1689                 {
1690                         entry->query = SQS_TIMEDOUT;
1691                 }
1692         }
1693 }
1694
1695 void NetConn_ClientFrame(void)
1696 {
1697         int i, length;
1698         lhnetaddress_t peeraddress;
1699         NetConn_UpdateSockets();
1700         if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1701         {
1702                 if (cls.connect_remainingtries == 0)
1703                         M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1704                 cls.connect_nextsendtime = realtime + 1;
1705                 cls.connect_remainingtries--;
1706                 if (cls.connect_remainingtries <= -10)
1707                 {
1708                         cls.connect_trying = false;
1709                         M_Update_Return_Reason("Connect: Failed");
1710                         return;
1711                 }
1712                 // try challenge first (newer DP server or QW)
1713                 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1714                 // then try netquake as a fallback (old server, or netquake)
1715                 SZ_Clear(&net_message);
1716                 // save space for the header, filled in later
1717                 MSG_WriteLong(&net_message, 0);
1718                 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1719                 MSG_WriteString(&net_message, "QUAKE");
1720                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1721                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1722                 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1723                 SZ_Clear(&net_message);
1724         }
1725         for (i = 0;i < cl_numsockets;i++)
1726                 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1727                         NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1728         NetConn_QueryQueueFrame();
1729         if (cls.netcon && realtime > cls.netcon->timeout)
1730         {
1731                 Con_Print("Connection timed out\n");
1732                 CL_Disconnect();
1733                 Host_ShutdownServer ();
1734         }
1735 }
1736
1737 #define MAX_CHALLENGES 128
1738 struct challenge_s
1739 {
1740         lhnetaddress_t address;
1741         double time;
1742         char string[12];
1743 }
1744 challenge[MAX_CHALLENGES];
1745
1746 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1747 {
1748         int i;
1749         char c;
1750         for (i = 0;i < bufferlength - 1;i++)
1751         {
1752                 do
1753                 {
1754                         c = rand () % (127 - 33) + 33;
1755                 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1756                 buffer[i] = c;
1757         }
1758         buffer[i] = 0;
1759 }
1760
1761 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1762 {
1763         unsigned int nb_clients = 0, nb_bots = 0, i;
1764         int length;
1765
1766         // How many clients are there?
1767         for (i = 0;i < (unsigned int)svs.maxclients;i++)
1768         {
1769                 if (svs.clients[i].active)
1770                 {
1771                         nb_clients++;
1772                         if (!svs.clients[i].netconnection)
1773                                 nb_bots++;
1774                 }
1775         }
1776
1777         // TODO: we should add more information for the full status string
1778         length = dpsnprintf(out_msg, out_size,
1779                                                 "\377\377\377\377%s\x0A"
1780                                                 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
1781                                                 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
1782                                                 "%s%s"
1783                                                 "%s",
1784                                                 fullstatus ? "statusResponse" : "infoResponse",
1785                                                 gamename, com_modname, gameversion.integer, svs.maxclients,
1786                                                 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
1787                                                 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
1788                                                 fullstatus ? "\n" : "");
1789
1790         // Make sure it fits in the buffer
1791         if (length < 0)
1792                 return false;
1793
1794         if (fullstatus)
1795         {
1796                 char *ptr;
1797                 int left;
1798
1799                 ptr = out_msg + length;
1800                 left = (int)out_size - length;
1801
1802                 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1803                 {
1804                         client_t *cl = &svs.clients[i];
1805                         if (cl->active)
1806                         {
1807                                 int nameind, cleanind, pingvalue;
1808                                 char curchar;
1809                                 char cleanname [sizeof(cl->name)];
1810
1811                                 // Remove all characters '"' and '\' in the player name
1812                                 nameind = 0;
1813                                 cleanind = 0;
1814                                 do
1815                                 {
1816                                         curchar = cl->name[nameind++];
1817                                         if (curchar != '"' && curchar != '\\')
1818                                         {
1819                                                 cleanname[cleanind++] = curchar;
1820                                                 if (cleanind == sizeof(cleanname) - 1)
1821                                                         break;
1822                                         }
1823                                 } while (curchar != '\0');
1824
1825                                 pingvalue = (int)(cl->ping * 1000.0f);
1826                                 if(cl->netconnection)
1827                                         pingvalue = bound(1, pingvalue, 9999);
1828                                 else
1829                                         pingvalue = 0;
1830                                 length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
1831                                                                         cl->frags,
1832                                                                         pingvalue,
1833                                                                         cleanname);
1834                                 if(length < 0)
1835                                         return false;
1836                                 left -= length;
1837                                 ptr += length;
1838                         }
1839                 }
1840         }
1841
1842         return true;
1843 }
1844
1845 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
1846 {
1847         int floodslotnum, bestfloodslotnum;
1848         double bestfloodtime;
1849         lhnetaddress_t noportpeeraddress;
1850         // see if this is a connect flood
1851         noportpeeraddress = *peeraddress;
1852         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
1853         bestfloodslotnum = 0;
1854         bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
1855         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
1856         {
1857                 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
1858                 {
1859                         bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
1860                         bestfloodslotnum = floodslotnum;
1861                 }
1862                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
1863                 {
1864                         // this address matches an ongoing flood address
1865                         if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
1866                         {
1867                                 // renew the ban on this address so it does not expire
1868                                 // until the flood has subsided
1869                                 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
1870                                 //Con_Printf("Flood detected!\n");
1871                                 return true;
1872                         }
1873                         // the flood appears to have subsided, so allow this
1874                         bestfloodslotnum = floodslotnum; // reuse the same slot
1875                         break;
1876                 }
1877         }
1878         // begin a new timeout on this address
1879         sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
1880         sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
1881         //Con_Printf("Flood detection initiated!\n");
1882         return false;
1883 }
1884
1885 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
1886 {
1887         int floodslotnum;
1888         lhnetaddress_t noportpeeraddress;
1889         // see if this is a connect flood
1890         noportpeeraddress = *peeraddress;
1891         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
1892         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
1893         {
1894                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
1895                 {
1896                         // this address matches an ongoing flood address
1897                         // remove the ban
1898                         sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
1899                         sv.connectfloodaddresses[floodslotnum].lasttime = 0;
1900                         //Con_Printf("Flood cleared!\n");
1901                 }
1902         }
1903 }
1904
1905 extern void SV_SendServerinfo (client_t *client);
1906 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1907 {
1908         int i, ret, clientnum, best;
1909         double besttime;
1910         client_t *client;
1911         char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
1912         qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
1913
1914         if (!sv.active)
1915                 return false;
1916
1917         // convert the address to a string incase we need it
1918         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1919
1920         // see if we can identify the sender as a local player
1921         // (this is necessary for rcon to send a reliable reply if the client is
1922         //  actually on the server, not sending remotely)
1923         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1924                 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1925                         break;
1926         if (i == svs.maxclients)
1927                 host_client = NULL;
1928
1929         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1930         {
1931                 // received a command string - strip off the packaging and put it
1932                 // into our string buffer with NULL termination
1933                 data += 4;
1934                 length -= 4;
1935                 length = min(length, (int)sizeof(stringbuf) - 1);
1936                 memcpy(stringbuf, data, length);
1937                 stringbuf[length] = 0;
1938                 string = stringbuf;
1939
1940                 if (developer.integer >= 10)
1941                 {
1942                         Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1943                         Com_HexDumpToConsole(data, length);
1944                 }
1945
1946                 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
1947                 {
1948                         for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1949                         {
1950                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1951                                         break;
1952                                 if (besttime > challenge[i].time)
1953                                         besttime = challenge[best = i].time;
1954                         }
1955                         // if we did not find an exact match, choose the oldest and
1956                         // update address and string
1957                         if (i == MAX_CHALLENGES)
1958                         {
1959                                 i = best;
1960                                 challenge[i].address = *peeraddress;
1961                                 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1962                         }
1963                         challenge[i].time = realtime;
1964                         // send the challenge
1965                         NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1966                         return true;
1967                 }
1968                 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
1969                 {
1970                         string += 7;
1971                         length -= 7;
1972
1973                         if (!(s = SearchInfostring(string, "challenge")))
1974                                 return true;
1975                         // validate the challenge
1976                         for (i = 0;i < MAX_CHALLENGES;i++)
1977                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1978                                         break;
1979                         // if the challenge is not recognized, drop the packet
1980                         if (i == MAX_CHALLENGES)
1981                                 return true;
1982
1983                         // check engine protocol
1984                         if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1985                         {
1986                                 if (developer.integer >= 10)
1987                                         Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1988                                 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1989                                 return true;
1990                         }
1991
1992                         // see if this is a duplicate connection request or a disconnected
1993                         // client who is rejoining to the same client slot
1994                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1995                         {
1996                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1997                                 {
1998                                         // this is a known client...
1999                                         if (client->spawned)
2000                                         {
2001                                                 // client crashed and is coming back,
2002                                                 // keep their stuff intact
2003                                                 if (developer.integer >= 10)
2004                                                         Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2005                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2006                                                 SV_VM_Begin();
2007                                                 SV_SendServerinfo(client);
2008                                                 SV_VM_End();
2009                                         }
2010                                         else
2011                                         {
2012                                                 // client is still trying to connect,
2013                                                 // so we send a duplicate reply
2014                                                 if (developer.integer >= 10)
2015                                                         Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2016                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2017                                         }
2018                                         return true;
2019                                 }
2020                         }
2021
2022                         if (NetConn_PreventConnectFlood(peeraddress))
2023                                 return true;
2024
2025                         // find an empty client slot for this new client
2026                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2027                         {
2028                                 netconn_t *conn;
2029                                 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2030                                 {
2031                                         // allocated connection
2032                                         if (developer.integer >= 10)
2033                                                 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2034                                         NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2035                                         // now set up the client
2036                                         SV_VM_Begin();
2037                                         SV_ConnectClient(clientnum, conn);
2038                                         SV_VM_End();
2039                                         NetConn_Heartbeat(1);
2040                                         return true;
2041                                 }
2042                         }
2043
2044                         // no empty slots found - server is full
2045                         if (developer.integer >= 10)
2046                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2047                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2048
2049                         return true;
2050                 }
2051                 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2052                 {
2053                         const char *challenge = NULL;
2054
2055                         // If there was a challenge in the getinfo message
2056                         if (length > 8 && string[7] == ' ')
2057                                 challenge = string + 8;
2058
2059                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2060                         {
2061                                 if (developer.integer >= 10)
2062                                         Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2063                                 NetConn_WriteString(mysocket, response, peeraddress);
2064                         }
2065                         return true;
2066                 }
2067                 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2068                 {
2069                         const char *challenge = NULL;
2070
2071                         // If there was a challenge in the getinfo message
2072                         if (length > 10 && string[9] == ' ')
2073                                 challenge = string + 10;
2074
2075                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2076                         {
2077                                 if (developer.integer >= 10)
2078                                         Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2079                                 NetConn_WriteString(mysocket, response, peeraddress);
2080                         }
2081                         return true;
2082                 }
2083                 if (length >= 5 && !memcmp(string, "rcon ", 5))
2084                 {
2085                         int i;
2086                         char *s = string + 5;
2087                         char password[64];
2088                         for (i = 0;*s > ' ';s++)
2089                                 if (i < (int)sizeof(password) - 1)
2090                                         password[i++] = *s;
2091                         password[i] = 0;
2092                         if (password[0] > ' ' && !strcmp(rcon_password.string, password))
2093                         {
2094                                 // looks like a legitimate rcon command with the correct password
2095                                 Con_Printf("server received rcon command from %s:\n%s\n", host_client ? host_client->name : addressstring2, s);
2096                                 rcon_redirect = true;
2097                                 rcon_redirect_bufferpos = 0;
2098                                 Cmd_ExecuteString(s, src_command);
2099                                 rcon_redirect_buffer[rcon_redirect_bufferpos] = 0;
2100                                 rcon_redirect = false;
2101                                 // print resulting text to client
2102                                 // if client is playing, send a reliable reply instead of
2103                                 // a command packet
2104                                 if (host_client)
2105                                 {
2106                                         // if the netconnection is loop, then this is the
2107                                         // local player on a listen mode server, and it would
2108                                         // result in duplicate printing to the console
2109                                         // (not that the local player should be using rcon
2110                                         //  when they have the console)
2111                                         if (host_client->netconnection && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2112                                                 SV_ClientPrintf("%s", rcon_redirect_buffer);
2113                                 }
2114                                 else
2115                                 {
2116                                         // qw print command
2117                                         dpsnprintf(response, sizeof(response), "\377\377\377\377n%s", rcon_redirect_buffer);
2118                                         NetConn_WriteString(mysocket, response, peeraddress);
2119                                 }
2120                         }
2121                         return true;
2122                 }
2123                 if (!strncmp(string, "ping", 4))
2124                 {
2125                         if (developer.integer >= 10)
2126                                 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2127                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2128                         return true;
2129                 }
2130                 if (!strncmp(string, "ack", 3))
2131                         return true;
2132                 // we may not have liked the packet, but it was a command packet, so
2133                 // we're done processing this packet now
2134                 return true;
2135         }
2136         // netquake control packets, supported for compatibility only, and only
2137         // when running game protocols that are normally served via this connection
2138         // protocol
2139         // (this protects more modern protocols against being used for
2140         //  Quake packet flood Denial Of Service attacks)
2141         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))
2142         {
2143                 int c;
2144                 int protocolnumber;
2145                 const char *protocolname;
2146                 data += 4;
2147                 length -= 4;
2148                 SZ_Clear(&net_message);
2149                 SZ_Write(&net_message, data, length);
2150                 MSG_BeginReading();
2151                 c = MSG_ReadByte();
2152                 switch (c)
2153                 {
2154                 case CCREQ_CONNECT:
2155                         if (developer.integer >= 10)
2156                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2157                         if(!islocal && sv_public.integer <= -2)
2158                                 break;
2159
2160                         protocolname = MSG_ReadString();
2161                         protocolnumber = MSG_ReadByte();
2162                         if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2163                         {
2164                                 if (developer.integer >= 10)
2165                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2166                                 SZ_Clear(&net_message);
2167                                 // save space for the header, filled in later
2168                                 MSG_WriteLong(&net_message, 0);
2169                                 MSG_WriteByte(&net_message, CCREP_REJECT);
2170                                 MSG_WriteString(&net_message, "Incompatible version.\n");
2171                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2172                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2173                                 SZ_Clear(&net_message);
2174                                 break;
2175                         }
2176
2177                         // see if this connect request comes from a known client
2178                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2179                         {
2180                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2181                                 {
2182                                         // this is either a duplicate connection request
2183                                         // or coming back from a timeout
2184                                         // (if so, keep their stuff intact)
2185
2186                                         // send a reply
2187                                         if (developer.integer >= 10)
2188                                                 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2189                                         SZ_Clear(&net_message);
2190                                         // save space for the header, filled in later
2191                                         MSG_WriteLong(&net_message, 0);
2192                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2193                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2194                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2195                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2196                                         SZ_Clear(&net_message);
2197
2198                                         // if client is already spawned, re-send the
2199                                         // serverinfo message as they'll need it to play
2200                                         if (client->spawned)
2201                                         {
2202                                                 SV_VM_Begin();
2203                                                 SV_SendServerinfo(client);
2204                                                 SV_VM_End();
2205                                         }
2206                                         return true;
2207                                 }
2208                         }
2209
2210                         // this is a new client, check for connection flood
2211                         if (NetConn_PreventConnectFlood(peeraddress))
2212                                 break;
2213
2214                         // find a slot for the new client
2215                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2216                         {
2217                                 netconn_t *conn;
2218                                 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2219                                 {
2220                                         // connect to the client
2221                                         // everything is allocated, just fill in the details
2222                                         strlcpy (conn->address, addressstring2, sizeof (conn->address));
2223                                         if (developer.integer >= 10)
2224                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2225                                         // send back the info about the server connection
2226                                         SZ_Clear(&net_message);
2227                                         // save space for the header, filled in later
2228                                         MSG_WriteLong(&net_message, 0);
2229                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2230                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2231                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2232                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2233                                         SZ_Clear(&net_message);
2234                                         // now set up the client struct
2235                                         SV_VM_Begin();
2236                                         SV_ConnectClient(clientnum, conn);
2237                                         SV_VM_End();
2238                                         NetConn_Heartbeat(1);
2239                                         return true;
2240                                 }
2241                         }
2242
2243                         if (developer.integer >= 10)
2244                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2245                         // no room; try to let player know
2246                         SZ_Clear(&net_message);
2247                         // save space for the header, filled in later
2248                         MSG_WriteLong(&net_message, 0);
2249                         MSG_WriteByte(&net_message, CCREP_REJECT);
2250                         MSG_WriteString(&net_message, "Server is full.\n");
2251                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2252                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2253                         SZ_Clear(&net_message);
2254                         break;
2255                 case CCREQ_SERVER_INFO:
2256                         if (developer.integer >= 10)
2257                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2258                         if(!islocal && sv_public.integer <= -1)
2259                                 break;
2260                         if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2261                         {
2262                                 int numclients;
2263                                 char myaddressstring[128];
2264                                 if (developer.integer >= 10)
2265                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2266                                 SZ_Clear(&net_message);
2267                                 // save space for the header, filled in later
2268                                 MSG_WriteLong(&net_message, 0);
2269                                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2270                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2271                                 MSG_WriteString(&net_message, myaddressstring);
2272                                 MSG_WriteString(&net_message, hostname.string);
2273                                 MSG_WriteString(&net_message, sv.name);
2274                                 // How many clients are there?
2275                                 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2276                                         if (svs.clients[i].active)
2277                                                 numclients++;
2278                                 MSG_WriteByte(&net_message, numclients);
2279                                 MSG_WriteByte(&net_message, svs.maxclients);
2280                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2281                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2282                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2283                                 SZ_Clear(&net_message);
2284                         }
2285                         break;
2286                 case CCREQ_PLAYER_INFO:
2287                         if (developer.integer >= 10)
2288                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2289                         if(!islocal && sv_public.integer <= -1)
2290                                 break;
2291                         if (sv.active)
2292                         {
2293                                 int playerNumber, activeNumber, clientNumber;
2294                                 client_t *client;
2295
2296                                 playerNumber = MSG_ReadByte();
2297                                 activeNumber = -1;
2298                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2299                                         if (client->active && ++activeNumber == playerNumber)
2300                                                 break;
2301                                 if (clientNumber != svs.maxclients)
2302                                 {
2303                                         SZ_Clear(&net_message);
2304                                         // save space for the header, filled in later
2305                                         MSG_WriteLong(&net_message, 0);
2306                                         MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2307                                         MSG_WriteByte(&net_message, playerNumber);
2308                                         MSG_WriteString(&net_message, client->name);
2309                                         MSG_WriteLong(&net_message, client->colors);
2310                                         MSG_WriteLong(&net_message, client->frags);
2311                                         MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2312                                         MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2313                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2314                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2315                                         SZ_Clear(&net_message);
2316                                 }
2317                         }
2318                         break;
2319                 case CCREQ_RULE_INFO:
2320                         if (developer.integer >= 10)
2321                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2322                         if(!islocal && sv_public.integer <= -1)
2323                                 break;
2324                         if (sv.active)
2325                         {
2326                                 char *prevCvarName;
2327                                 cvar_t *var;
2328
2329                                 // find the search start location
2330                                 prevCvarName = MSG_ReadString();
2331                                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2332
2333                                 // send the response
2334                                 SZ_Clear(&net_message);
2335                                 // save space for the header, filled in later
2336                                 MSG_WriteLong(&net_message, 0);
2337                                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2338                                 if (var)
2339                                 {
2340                                         MSG_WriteString(&net_message, var->name);
2341                                         MSG_WriteString(&net_message, var->string);
2342                                 }
2343                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2344                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2345                                 SZ_Clear(&net_message);
2346                         }
2347                         break;
2348                 default:
2349                         break;
2350                 }
2351                 SZ_Clear(&net_message);
2352                 // we may not have liked the packet, but it was a valid control
2353                 // packet, so we're done processing this packet now
2354                 return true;
2355         }
2356         if (host_client)
2357         {
2358                 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2359                 {
2360                         SV_VM_Begin();
2361                         SV_ReadClientMessage();
2362                         SV_VM_End();
2363                         return ret;
2364                 }
2365         }
2366         return 0;
2367 }
2368
2369 void NetConn_ServerFrame(void)
2370 {
2371         int i, length;
2372         lhnetaddress_t peeraddress;
2373         for (i = 0;i < sv_numsockets;i++)
2374                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2375                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2376         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2377         {
2378                 // never timeout loopback connections
2379                 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2380                 {
2381                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2382                         SV_VM_Begin();
2383                         SV_DropClient(false);
2384                         SV_VM_End();
2385                 }
2386         }
2387 }
2388
2389 void NetConn_SleepMicroseconds(int microseconds)
2390 {
2391         LHNET_SleepUntilPacket_Microseconds(microseconds);
2392 }
2393
2394 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2395 {
2396         int i;
2397         int masternum;
2398         lhnetaddress_t masteraddress;
2399         lhnetaddress_t broadcastaddress;
2400         char request[256];
2401
2402         if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2403                 return;
2404
2405         // 26000 is the default quake server port, servers on other ports will not
2406         // be found
2407         // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2408         LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2409
2410         if (querydp)
2411         {
2412                 for (i = 0;i < cl_numsockets;i++)
2413                 {
2414                         if (cl_sockets[i])
2415                         {
2416                                 // search LAN for Quake servers
2417                                 SZ_Clear(&net_message);
2418                                 // save space for the header, filled in later
2419                                 MSG_WriteLong(&net_message, 0);
2420                                 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2421                                 MSG_WriteString(&net_message, "QUAKE");
2422                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2423                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2424                                 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2425                                 SZ_Clear(&net_message);
2426
2427                                 // search LAN for DarkPlaces servers
2428                                 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
2429
2430                                 // build the getservers message to send to the dpmaster master servers
2431                                 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
2432
2433                                 // search internet
2434                                 for (masternum = 0;sv_masters[masternum].name;masternum++)
2435                                 {
2436                                         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])))
2437                                         {
2438                                                 masterquerycount++;
2439                                                 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2440                                         }
2441                                 }
2442                         }
2443                 }
2444         }
2445
2446         // only query QuakeWorld servers when the user wants to
2447         if (queryqw)
2448         {
2449                 for (i = 0;i < cl_numsockets;i++)
2450                 {
2451                         if (cl_sockets[i])
2452                         {
2453                                 // search LAN for QuakeWorld servers
2454                                 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2455
2456                                 // build the getservers message to send to the qwmaster master servers
2457                                 // note this has no -1 prefix, and the trailing nul byte is sent
2458                                 dpsnprintf(request, sizeof(request), "c\n");
2459
2460                                 // search internet
2461                                 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2462                                 {
2463                                         if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2464                                         {
2465                                                 if (m_state != m_slist)
2466                                                 {
2467                                                         char lookupstring[128];
2468                                                         LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2469                                                         Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2470                                                 }
2471                                                 masterquerycount++;
2472                                                 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2473                                         }
2474                                 }
2475                         }
2476                 }
2477         }
2478         if (!masterquerycount)
2479         {
2480                 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2481                 M_Update_Return_Reason("No network");
2482         }
2483 }
2484
2485 void NetConn_Heartbeat(int priority)
2486 {
2487         lhnetaddress_t masteraddress;
2488         int masternum;
2489         lhnetsocket_t *mysocket;
2490
2491         // if it's a state change (client connected), limit next heartbeat to no
2492         // more than 30 sec in the future
2493         if (priority == 1 && nextheartbeattime > realtime + 30.0)
2494                 nextheartbeattime = realtime + 30.0;
2495
2496         // limit heartbeatperiod to 30 to 270 second range,
2497         // lower limit is to avoid abusing master servers with excess traffic,
2498         // upper limit is to avoid timing out on the master server (which uses
2499         // 300 sec timeout)
2500         if (sv_heartbeatperiod.value < 30)
2501                 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
2502         if (sv_heartbeatperiod.value > 270)
2503                 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
2504
2505         // make advertising optional and don't advertise singleplayer games, and
2506         // only send a heartbeat as often as the admin wants
2507         if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
2508         {
2509                 nextheartbeattime = realtime + sv_heartbeatperiod.value;
2510                 for (masternum = 0;sv_masters[masternum].name;masternum++)
2511                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
2512                                 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
2513         }
2514 }
2515
2516 static void Net_Heartbeat_f(void)
2517 {
2518         if (sv.active)
2519                 NetConn_Heartbeat(2);
2520         else
2521                 Con_Print("No server running, can not heartbeat to master server.\n");
2522 }
2523
2524 void PrintStats(netconn_t *conn)
2525 {
2526         if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
2527                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->qw.outgoing_sequence, conn->qw.incoming_sequence);
2528         else
2529                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
2530 }
2531
2532 void Net_Stats_f(void)
2533 {
2534         netconn_t *conn;
2535         Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
2536         Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
2537         Con_Printf("reliable messages sent     = %i\n", reliableMessagesSent);
2538         Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
2539         Con_Printf("packetsSent                = %i\n", packetsSent);
2540         Con_Printf("packetsReSent              = %i\n", packetsReSent);
2541         Con_Printf("packetsReceived            = %i\n", packetsReceived);
2542         Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
2543         Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
2544         Con_Print("connections                =\n");
2545         for (conn = netconn_list;conn;conn = conn->next)
2546                 PrintStats(conn);
2547 }
2548
2549 void Net_Slist_f(void)
2550 {
2551         ServerList_ResetMasks();
2552         serverlist_sortbyfield = SLIF_PING;
2553         serverlist_sortdescending = false;
2554     if (m_state != m_slist) {
2555                 Con_Print("Sending requests to master servers\n");
2556                 ServerList_QueryList(true, false);
2557                 serverlist_consoleoutput = true;
2558                 Con_Print("Listening for replies...\n");
2559         } else
2560                 ServerList_QueryList(true, false);
2561 }
2562
2563 void Net_SlistQW_f(void)
2564 {
2565         ServerList_ResetMasks();
2566         serverlist_sortbyfield = SLIF_PING;
2567         serverlist_sortdescending = false;
2568     if (m_state != m_slist) {
2569                 Con_Print("Sending requests to master servers\n");
2570                 ServerList_QueryList(false, true);
2571                 serverlist_consoleoutput = true;
2572                 Con_Print("Listening for replies...\n");
2573         } else
2574                 ServerList_QueryList(false, true);
2575 }
2576
2577 void NetConn_Init(void)
2578 {
2579         int i;
2580         lhnetaddress_t tempaddress;
2581         netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
2582         Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
2583         Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
2584         Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
2585         Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
2586         Cvar_RegisterVariable(&net_slist_queriespersecond);
2587         Cvar_RegisterVariable(&net_slist_queriesperframe);
2588         Cvar_RegisterVariable(&net_slist_timeout);
2589         Cvar_RegisterVariable(&net_slist_maxtries);
2590         Cvar_RegisterVariable(&net_messagetimeout);
2591         Cvar_RegisterVariable(&net_connecttimeout);
2592         Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
2593         Cvar_RegisterVariable(&cl_netlocalping);
2594         Cvar_RegisterVariable(&cl_netpacketloss_send);
2595         Cvar_RegisterVariable(&cl_netpacketloss_receive);
2596         Cvar_RegisterVariable(&hostname);
2597         Cvar_RegisterVariable(&developer_networking);
2598         Cvar_RegisterVariable(&cl_netport);
2599         Cvar_RegisterVariable(&sv_netport);
2600         Cvar_RegisterVariable(&net_address);
2601         //Cvar_RegisterVariable(&net_address_ipv6);
2602         Cvar_RegisterVariable(&sv_public);
2603         Cvar_RegisterVariable(&sv_heartbeatperiod);
2604         for (i = 0;sv_masters[i].name;i++)
2605                 Cvar_RegisterVariable(&sv_masters[i]);
2606         Cvar_RegisterVariable(&gameversion);
2607 // 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.
2608         if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
2609         {
2610                 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
2611                 {
2612                         Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
2613                         Cvar_SetQuick(&net_address, com_argv[i + 1]);
2614                 }
2615                 else
2616                         Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
2617         }
2618 // 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
2619         if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
2620         {
2621                 i = atoi(com_argv[i + 1]);
2622                 if (i >= 0 && i < 65536)
2623                 {
2624                         Con_Printf("-port option used, setting port cvar to %i\n", i);
2625                         Cvar_SetValueQuick(&sv_netport, i);
2626                 }
2627                 else
2628                         Con_Printf("-port option used, but %i is not a valid port number\n", i);
2629         }
2630         cl_numsockets = 0;
2631         sv_numsockets = 0;
2632         net_message.data = net_message_buf;
2633         net_message.maxsize = sizeof(net_message_buf);
2634         net_message.cursize = 0;
2635         LHNET_Init();
2636 }
2637
2638 void NetConn_Shutdown(void)
2639 {
2640         NetConn_CloseClientPorts();
2641         NetConn_CloseServerPorts();
2642         LHNET_Shutdown();
2643 }
2644