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