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