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