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