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