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