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