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