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