]> icculus.org git repositories - divverent/darkplaces.git/blob - netconn.c
Fixed a bug in the r_shadow light entity parser which caused it to not read in
[divverent/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 < (int)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 < (int)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, (int)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                                 break;
677                         }
678                         else
679                         {
680                                 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
681                                 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
682                         }
683                 }
684                 else
685                 {
686                         Con_Printf("Server unable to parse address %s\n", addressstring);
687                         // if it cant parse one address, it wont be able to parse another for sure
688                         break;
689                 }
690         }
691 }
692
693 void NetConn_OpenServerPorts(int opennetports)
694 {
695         int port;
696         NetConn_CloseServerPorts();
697         port = bound(0, sv_netport.integer, 65535);
698         if (port == 0)
699                 port = 26000;
700         Con_Printf("Server using port %i\n", port);
701         if (sv_netport.integer != port)
702                 Cvar_SetValueQuick(&sv_netport, port);
703         if (cls.state != ca_dedicated)
704                 NetConn_OpenServerPort("local:1", 0);
705         if (opennetports)
706         {
707                 NetConn_OpenServerPort(net_address.string, port);
708                 //NetConn_OpenServerPort(net_address_ipv6.string, port);
709         }
710         if (sv_numsockets == 0)
711                 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
712 }
713
714 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
715 {
716         int i, a = LHNETADDRESS_GetAddressType(address);
717         for (i = 0;i < cl_numsockets;i++)
718                 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
719                         return cl_sockets[i];
720         return NULL;
721 }
722
723 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
724 {
725         int i, a = LHNETADDRESS_GetAddressType(address);
726         for (i = 0;i < sv_numsockets;i++)
727                 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
728                         return sv_sockets[i];
729         return NULL;
730 }
731
732 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
733 {
734         netconn_t *conn;
735         conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
736         conn->mysocket = mysocket;
737         conn->peeraddress = *peeraddress;
738         conn->canSend = true;
739         conn->lastMessageTime = realtime;
740         // LordHavoc: (inspired by ProQuake) use a short connect timeout to
741         // reduce effectiveness of connection request floods
742         conn->timeout = realtime + net_connecttimeout.value;
743         LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
744         conn->next = netconn_list;
745         netconn_list = conn;
746         return conn;
747 }
748
749 void NetConn_Close(netconn_t *conn)
750 {
751         netconn_t *c;
752         // remove connection from list
753         if (conn == netconn_list)
754                 netconn_list = conn->next;
755         else
756         {
757                 for (c = netconn_list;c;c = c->next)
758                 {
759                         if (c->next == conn)
760                         {
761                                 c->next = conn->next;
762                                 break;
763                         }
764                 }
765                 // not found in list, we'll avoid crashing here...
766                 if (!c)
767                         return;
768         }
769         // free connection
770         Mem_Free(conn);
771 }
772
773 static int clientport = -1;
774 static int clientport2 = -1;
775 static int hostport = -1;
776 static void NetConn_UpdateServerStuff(void)
777 {
778         if (cls.state != ca_dedicated)
779         {
780                 if (clientport2 != cl_netport.integer)
781                 {
782                         clientport2 = cl_netport.integer;
783                         if (cls.state == ca_connected)
784                                 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
785                 }
786                 if (cls.state == ca_disconnected && clientport != clientport2)
787                 {
788                         clientport = clientport2;
789                         NetConn_CloseClientPorts();
790                 }
791                 if (cl_numsockets == 0)
792                         NetConn_OpenClientPorts();
793         }
794
795         if (hostport != sv_netport.integer)
796         {
797                 hostport = sv_netport.integer;
798                 if (sv.active)
799                         Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
800         }
801 }
802
803 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
804 {
805         unsigned int count;
806         unsigned int flags;
807         unsigned int sequence;
808         int qlength;
809
810         if (length >= 8)
811         {
812                 qlength = (unsigned int)BigLong(((int *)data)[0]);
813                 flags = qlength & ~NETFLAG_LENGTH_MASK;
814                 qlength &= NETFLAG_LENGTH_MASK;
815                 // control packets were already handled
816                 if (!(flags & NETFLAG_CTL) && qlength == length)
817                 {
818                         sequence = BigLong(((int *)data)[1]);
819                         packetsReceived++;
820                         data += 8;
821                         length -= 8;
822                         if (flags & NETFLAG_UNRELIABLE)
823                         {
824                                 if (sequence >= conn->unreliableReceiveSequence)
825                                 {
826                                         if (sequence > conn->unreliableReceiveSequence)
827                                         {
828                                                 count = sequence - conn->unreliableReceiveSequence;
829                                                 droppedDatagrams += count;
830                                                 Con_DPrintf("Dropped %u datagram(s)\n", count);
831                                         }
832                                         conn->unreliableReceiveSequence = sequence + 1;
833                                         conn->lastMessageTime = realtime;
834                                         conn->timeout = realtime + net_messagetimeout.value;
835                                         unreliableMessagesReceived++;
836                                         if (length > 0)
837                                         {
838                                                 SZ_Clear(&net_message);
839                                                 SZ_Write(&net_message, data, length);
840                                                 MSG_BeginReading();
841                                                 return 2;
842                                         }
843                                 }
844                                 else
845                                         Con_DPrint("Got a stale datagram\n");
846                                 return 1;
847                         }
848                         else if (flags & NETFLAG_ACK)
849                         {
850                                 if (sequence == (conn->sendSequence - 1))
851                                 {
852                                         if (sequence == conn->ackSequence)
853                                         {
854                                                 conn->ackSequence++;
855                                                 if (conn->ackSequence != conn->sendSequence)
856                                                         Con_DPrint("ack sequencing error\n");
857                                                 conn->lastMessageTime = realtime;
858                                                 conn->timeout = realtime + net_messagetimeout.value;
859                                                 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
860                                                 if (conn->sendMessageLength > 0)
861                                                 {
862                                                         memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
863                                                         conn->sendNext = true;
864                                                         NetConn_SendMessageNext(conn);
865                                                 }
866                                                 else
867                                                 {
868                                                         conn->sendMessageLength = 0;
869                                                         conn->canSend = true;
870                                                 }
871                                         }
872                                         else
873                                                 Con_DPrint("Duplicate ACK received\n");
874                                 }
875                                 else
876                                         Con_DPrint("Stale ACK received\n");
877                                 return 1;
878                         }
879                         else if (flags & NETFLAG_DATA)
880                         {
881                                 unsigned int temppacket[2];
882                                 temppacket[0] = BigLong(8 | NETFLAG_ACK);
883                                 temppacket[1] = BigLong(sequence);
884                                 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
885                                 if (sequence == conn->receiveSequence)
886                                 {
887                                         conn->lastMessageTime = realtime;
888                                         conn->timeout = realtime + net_messagetimeout.value;
889                                         conn->receiveSequence++;
890                                         if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
891                                                 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
892                                                 conn->receiveMessageLength += length;
893                                         } else {
894                                                 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
895                                                                         "Dropping the message!\n", sequence );
896                                                 conn->receiveMessageLength = 0;
897                                                 return 1;
898                                         }
899                                         if (flags & NETFLAG_EOM)
900                                         {
901                                                 reliableMessagesReceived++;
902                                                 length = conn->receiveMessageLength;
903                                                 conn->receiveMessageLength = 0;
904                                                 if (length > 0)
905                                                 {
906                                                         SZ_Clear(&net_message);
907                                                         SZ_Write(&net_message, conn->receiveMessage, length);
908                                                         MSG_BeginReading();
909                                                         return 2;
910                                                 }
911                                         }
912                                 }
913                                 else
914                                         receivedDuplicateCount++;
915                                 return 1;
916                         }
917                 }
918         }
919         return 0;
920 }
921
922 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
923 {
924         cls.connect_trying = false;
925         M_Update_Return_Reason("");
926         // the connection request succeeded, stop current connection and set up a new connection
927         CL_Disconnect();
928         // if we're connecting to a remote server, shut down any local server
929         if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
930                 Host_ShutdownServer (false);
931         // allocate a net connection to keep track of things
932         cls.netcon = NetConn_Open(mysocket, peeraddress);
933         Con_Printf("Connection accepted to %s\n", cls.netcon->address);
934         key_dest = key_game;
935         m_state = m_none;
936         cls.demonum = -1;                       // not in the demo loop now
937         cls.state = ca_connected;
938         cls.signon = 0;                         // need all the signon messages before playing
939 }
940
941 int NetConn_IsLocalGame(void)
942 {
943         if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
944                 return true;
945         return false;
946 }
947
948 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
949 {
950         int ret, c, control;
951         const char *s;
952         char *string, addressstring2[128], cname[128], ipstring[32];
953         char stringbuf[16384];
954
955         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
956         {
957                 // received a command string - strip off the packaging and put it
958                 // into our string buffer with NULL termination
959                 data += 4;
960                 length -= 4;
961                 length = min(length, (int)sizeof(stringbuf) - 1);
962                 memcpy(stringbuf, data, length);
963                 stringbuf[length] = 0;
964                 string = stringbuf;
965
966                 if (developer.integer)
967                 {
968                         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
969                         Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
970                         Com_HexDumpToConsole(data, length);
971                 }
972
973                 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
974                 {
975                         char protocolnames[1400];
976                         Protocol_Names(protocolnames, sizeof(protocolnames));
977                         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
978                         Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
979                         M_Update_Return_Reason("Got challenge response");
980                         NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
981                         return true;
982                 }
983                 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
984                 {
985                         M_Update_Return_Reason("Accepted");
986                         NetConn_ConnectionEstablished(mysocket, peeraddress);
987                         return true;
988                 }
989                 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
990                 {
991                         char rejectreason[32];
992                         cls.connect_trying = false;
993                         string += 7;
994                         length = max(length - 7, (int)sizeof(rejectreason) - 1);
995                         memcpy(rejectreason, string, length);
996                         rejectreason[length] = 0;
997                         M_Update_Return_Reason(rejectreason);
998                         return true;
999                 }
1000                 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1001                 {
1002                         serverlist_info_t *info;
1003                         int i, n;
1004                         double pingtime;
1005
1006                         string += 13;
1007                         // serverlist only uses text addresses
1008                         LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
1009                         // search the cache for this server and update it
1010                         for( n = 0; n < serverlist_cachecount; n++ )
1011                                 if( !strcmp( cname, serverlist_cache[n].info.cname ) )
1012                                         break;
1013                         if( n == serverlist_cachecount ) {
1014                                 // LAN search doesnt require an answer from the master server so we wont
1015                                 // know the ping nor will it be initialized already...
1016
1017                                 // find a slot
1018                                 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1019                                         return true;
1020
1021                                 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1022                                 // store the data the engine cares about (address and ping)
1023                                 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, cname, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1024                                 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1025                                 serverlist_cache[serverlist_cachecount].querytime = realtime;
1026                                 // if not in the slist menu we should print the server to console
1027                                 if (serverlist_consoleoutput) {
1028                                         Con_Printf("querying %s\n", ipstring);
1029                                 }
1030
1031                                 ++serverlist_cachecount;
1032                         }
1033
1034                         info = &serverlist_cache[n].info;
1035                         if ((s = SearchInfostring(string, "gamename"     )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
1036                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0]  = 0;
1037                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0]  = 0;
1038                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1039                         if ((s = SearchInfostring(string, "protocol"     )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
1040                         if ((s = SearchInfostring(string, "clients"      )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
1041                         if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers  = 0;
1042
1043                         if (info->ping == 100000)
1044                                         serverreplycount++;
1045
1046                         pingtime = (int)((realtime - serverlist_cache[n].querytime) * 1000.0);
1047                         pingtime = bound(0, pingtime, 9999);
1048                         // update the ping
1049                         info->ping = pingtime;
1050
1051                         // legacy/old stuff move it to the menu ASAP
1052
1053                         // build description strings for the things users care about
1054                         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);
1055                         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);
1056                         // if ping is especially high, display it as such
1057                         if (pingtime >= 300)
1058                         {
1059                                 // orange numbers (lower block)
1060                                 for (i = 0;i < 5;i++)
1061                                         if (serverlist_cache[n].line1[i] != ' ')
1062                                                 serverlist_cache[n].line1[i] += 128;
1063                         }
1064                         else if (pingtime >= 200)
1065                         {
1066                                 // yellow numbers (in upper block)
1067                                 for (i = 0;i < 5;i++)
1068                                         if (serverlist_cache[n].line1[i] != ' ')
1069                                                 serverlist_cache[n].line1[i] -= 30;
1070                         }
1071                         if( serverlist_cache[n].query == SQS_QUERIED ) {
1072                                 ServerList_ViewList_Remove( &serverlist_cache[n] );
1073                         }
1074                         // if not in the slist menu we should print the server to console (if wanted)
1075                         else if( serverlist_consoleoutput )
1076                                 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1077                         // and finally, update the view set
1078                         ServerList_ViewList_Insert( &serverlist_cache[n] );
1079                         serverlist_cache[n].query = SQS_QUERIED;
1080
1081                         return true;
1082                 }
1083                 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1084                 {
1085                         // Extract the IP addresses
1086                         data += 18;
1087                         length -= 18;
1088                         masterreplycount++;
1089                         if (serverlist_consoleoutput)
1090                                 Con_Print("received server list...\n");
1091                         while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1092                         {
1093                                 int n;
1094
1095                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
1096                                 if (developer.integer)
1097                                         Con_Printf("Requesting info from server %s\n", ipstring);
1098                                 // ignore the rest of the message if the serverlist is full
1099                                 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1100                                         break;
1101                                 // also ignore it if we have already queried it (other master server response)
1102                                 for( n = 0 ; n < serverlist_cachecount ; n++ )
1103                                         if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1104                                                 break;
1105                                 if( n >= serverlist_cachecount )
1106                                 {
1107                                         serverquerycount++;
1108
1109                                         memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1110                                         // store the data the engine cares about (address and ping)
1111                                         strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1112                                         serverlist_cache[serverlist_cachecount].info.ping = 100000;
1113                                         serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1114
1115                                         ++serverlist_cachecount;
1116                                 }
1117
1118                                 // move on to next address in packet
1119                                 data += 7;
1120                                 length -= 7;
1121                         }
1122                         // begin or resume serverlist queries
1123                         serverlist_querysleep = false;
1124                         return true;
1125                 }
1126                 /*
1127                 if (!strncmp(string, "ping", 4))
1128                 {
1129                         if (developer.integer)
1130                                 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1131                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1132                         return true;
1133                 }
1134                 if (!strncmp(string, "ack", 3))
1135                         return true;
1136                 */
1137                 // we may not have liked the packet, but it was a command packet, so
1138                 // we're done processing this packet now
1139                 return true;
1140         }
1141         // netquake control packets, supported for compatibility only
1142         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1143         {
1144                 c = data[4];
1145                 data += 5;
1146                 length -= 5;
1147                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1148                 switch (c)
1149                 {
1150                 case CCREP_ACCEPT:
1151                         if (developer.integer)
1152                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1153                         if (cls.connect_trying)
1154                         {
1155                                 lhnetaddress_t clientportaddress;
1156                                 clientportaddress = *peeraddress;
1157                                 if (length >= 4)
1158                                 {
1159                                         unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1160                                         data += 4;
1161                                         length -= 4;
1162                                         LHNETADDRESS_SetPort(&clientportaddress, port);
1163                                 }
1164                                 M_Update_Return_Reason("Accepted");
1165                                 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
1166                         }
1167                         break;
1168                 case CCREP_REJECT:
1169                         if (developer.integer)
1170                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1171                         cls.connect_trying = false;
1172                         M_Update_Return_Reason(data);
1173                         break;
1174 #if 0
1175                 case CCREP_SERVER_INFO:
1176                         if (developer.integer)
1177                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1178                         if (cls.state != ca_dedicated)
1179                         {
1180                                 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
1181                                 // string we just ignore it and keep the real address
1182                                 MSG_ReadString();
1183                                 // serverlist only uses text addresses
1184                                 cname = UDP_AddrToString(readaddr);
1185                                 // search the cache for this server
1186                                 for (n = 0; n < hostCacheCount; n++)
1187                                         if (!strcmp(cname, serverlist[n].cname))
1188                                                 break;
1189                                 // add it
1190                                 if (n == hostCacheCount && hostCacheCount < SERVERLISTSIZE)
1191                                 {
1192                                         hostCacheCount++;
1193                                         memset(&serverlist[n], 0, sizeof(serverlist[n]));
1194                                         strlcpy (serverlist[n].name, MSG_ReadString(), sizeof (serverlist[n].name));
1195                                         strlcpy (serverlist[n].map, MSG_ReadString(), sizeof (serverlist[n].map));
1196                                         serverlist[n].users = MSG_ReadByte();
1197                                         serverlist[n].maxusers = MSG_ReadByte();
1198                                         c = MSG_ReadByte();
1199                                         if (c != NET_PROTOCOL_VERSION)
1200                                         {
1201                                                 strlcpy (serverlist[n].cname, serverlist[n].name, sizeof (serverlist[n].cname));
1202                                                 strcpy(serverlist[n].name, "*");
1203                                                 strlcat (serverlist[n].name, serverlist[n].cname, sizeof(serverlist[n].name));
1204                                         }
1205                                         strlcpy (serverlist[n].cname, cname, sizeof (serverlist[n].cname));
1206                                 }
1207                         }
1208                         break;
1209                 case CCREP_PLAYER_INFO:
1210                         // we got a CCREP_PLAYER_INFO??
1211                         //if (developer.integer)
1212                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1213                         break;
1214                 case CCREP_RULE_INFO:
1215                         // we got a CCREP_RULE_INFO??
1216                         //if (developer.integer)
1217                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1218                         break;
1219 #endif
1220                 default:
1221                         break;
1222                 }
1223                 // we may not have liked the packet, but it was a valid control
1224                 // packet, so we're done processing this packet now
1225                 return true;
1226         }
1227         ret = 0;
1228         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)
1229                 CL_ParseServerMessage();
1230         return ret;
1231 }
1232
1233 void NetConn_QueryQueueFrame(void)
1234 {
1235         int index;
1236         int queries;
1237         int maxqueries;
1238         double timeouttime;
1239         static double querycounter = 0;
1240
1241         if (serverlist_querysleep)
1242                 return;
1243
1244         // each time querycounter reaches 1.0 issue a query
1245         querycounter += host_realframetime * net_slist_queriespersecond.value;
1246         maxqueries = (int)querycounter;
1247         maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1248         querycounter -= maxqueries;
1249
1250         if( maxqueries == 0 ) {
1251                 return;
1252         }
1253
1254         // scan serverlist and issue queries as needed
1255     serverlist_querysleep = true;
1256
1257         timeouttime = realtime - net_slist_timeout.value;
1258         for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1259         {
1260                 serverlist_entry_t *entry = &serverlist_cache[ index ];
1261                 if( entry->query != SQS_QUERYING )
1262                 {
1263                         continue;
1264                 }
1265
1266         serverlist_querysleep = false;
1267                 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1268                 {
1269                         continue;
1270                 }
1271
1272                 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1273                 {
1274                         lhnetaddress_t address;
1275                         int socket;
1276
1277                         LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1278                         for (socket = 0; socket < cl_numsockets ; socket++) {
1279                                 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address);
1280                         }
1281
1282                         entry->querytime = realtime;
1283                         entry->querycounter++;
1284
1285                         // if not in the slist menu we should print the server to console
1286                         if (serverlist_consoleoutput)
1287                                 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1288
1289                         queries++;
1290                 }
1291                 else
1292                 {
1293                         entry->query = SQS_TIMEDOUT;
1294                 }
1295         }
1296 }
1297
1298 void NetConn_ClientFrame(void)
1299 {
1300         int i, length;
1301         lhnetaddress_t peeraddress;
1302         netconn_t *conn;
1303         NetConn_UpdateServerStuff();
1304         if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1305         {
1306                 if (cls.connect_remainingtries == 0)
1307                         M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1308                 cls.connect_nextsendtime = realtime + 1;
1309                 cls.connect_remainingtries--;
1310                 if (cls.connect_remainingtries <= -10)
1311                 {
1312                         cls.connect_trying = false;
1313                         M_Update_Return_Reason("Connect: Failed");
1314                         return;
1315                 }
1316                 // try challenge first (newer server)
1317                 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1318                 // then try netquake as a fallback (old server, or netquake)
1319                 SZ_Clear(&net_message);
1320                 // save space for the header, filled in later
1321                 MSG_WriteLong(&net_message, 0);
1322                 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1323                 MSG_WriteString(&net_message, "QUAKE");
1324                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1325                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1326                 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1327                 SZ_Clear(&net_message);
1328         }
1329         for (i = 0;i < cl_numsockets;i++) {
1330                 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0) {
1331                         NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1332                 }
1333         }
1334         NetConn_QueryQueueFrame();
1335         if (cls.netcon && realtime > cls.netcon->timeout)
1336         {
1337                 Con_Print("Connection timed out\n");
1338                 CL_Disconnect();
1339                 Host_ShutdownServer (false);
1340         }
1341         for (conn = netconn_list;conn;conn = conn->next)
1342                 NetConn_ReSendMessage(conn);
1343 }
1344
1345 #define MAX_CHALLENGES 128
1346 struct
1347 {
1348         lhnetaddress_t address;
1349         double time;
1350         char string[12];
1351 }
1352 challenge[MAX_CHALLENGES];
1353
1354 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1355 {
1356         int i;
1357         char c;
1358         for (i = 0;i < bufferlength - 1;i++)
1359         {
1360                 do
1361                 {
1362                         c = rand () % (127 - 33) + 33;
1363                 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1364                 buffer[i] = c;
1365         }
1366         buffer[i] = 0;
1367 }
1368
1369 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1370 {
1371         unsigned int nb_clients = 0, i;
1372         int length;
1373
1374         // How many clients are there?
1375         for (i = 0;i < (unsigned int)svs.maxclients;i++)
1376                 if (svs.clients[i].active)
1377                         nb_clients++;
1378
1379         // TODO: we should add more information for the full status string
1380         length = dpsnprintf(out_msg, out_size,
1381                                                 "\377\377\377\377%s\x0A"
1382                                                 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1383                                                 "\\clients\\%d\\mapname\\%s\\hostname\\%s""\\protocol\\%d"
1384                                                 "%s%s"
1385                                                 "%s",
1386                                                 fullstatus ? "statusResponse" : "infoResponse",
1387                                                 gamename, com_modname, svs.maxclients,
1388                                                 nb_clients, sv.name, hostname.string, NET_PROTOCOL_VERSION,
1389                                                 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
1390                                                 fullstatus ? "\n" : "");
1391
1392         // Make sure it fits in the buffer
1393         if (length < 0)
1394                 return false;
1395
1396         if (fullstatus)
1397         {
1398                 char *ptr;
1399                 int left;
1400
1401                 ptr = out_msg + length;
1402                 left = (int)out_size - length;
1403
1404                 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1405                 {
1406                         client_t *cl = &svs.clients[i];
1407                         if (cl->active)
1408                         {
1409                                 int nameind, cleanind;
1410                                 char curchar;
1411                                 char cleanname [sizeof(cl->name)];
1412
1413                                 // Remove all characters '"' and '\' in the player name
1414                                 nameind = 0;
1415                                 cleanind = 0;
1416                                 do
1417                                 {
1418                                         curchar = cl->name[nameind++];
1419                                         if (curchar != '"' && curchar != '\\')
1420                                         {
1421                                                 cleanname[cleanind++] = curchar;
1422                                                 if (cleanind == sizeof(cleanname) - 1)
1423                                                         break;
1424                                         }
1425                                 } while (curchar != '\0');
1426
1427                                 length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
1428                                                                         cl->frags,
1429                                                                         (int)(cl->ping * 1000.0f),
1430                                                                         cleanname);
1431                                 if(length < 0)
1432                                         return false;
1433                                 left -= length;
1434                                 ptr += length;
1435                         }
1436                 }
1437         }
1438
1439         return true;
1440 }
1441
1442 extern void SV_SendServerinfo (client_t *client);
1443 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1444 {
1445         int i, ret, clientnum, best;
1446         double besttime;
1447         client_t *client;
1448         netconn_t *conn;
1449         char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1450
1451         if (sv.active)
1452         {
1453                 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1454                 {
1455                         // received a command string - strip off the packaging and put it
1456                         // into our string buffer with NULL termination
1457                         data += 4;
1458                         length -= 4;
1459                         length = min(length, (int)sizeof(stringbuf) - 1);
1460                         memcpy(stringbuf, data, length);
1461                         stringbuf[length] = 0;
1462                         string = stringbuf;
1463
1464                         if (developer.integer)
1465                         {
1466                                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1467                                 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1468                                 Com_HexDumpToConsole(data, length);
1469                         }
1470
1471                         if (length >= 12 && !memcmp(string, "getchallenge", 12))
1472                         {
1473                                 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1474                                 {
1475                                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1476                                                 break;
1477                                         if (besttime > challenge[i].time)
1478                                                 besttime = challenge[best = i].time;
1479                                 }
1480                                 // if we did not find an exact match, choose the oldest and
1481                                 // update address and string
1482                                 if (i == MAX_CHALLENGES)
1483                                 {
1484                                         i = best;
1485                                         challenge[i].address = *peeraddress;
1486                                         NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1487                                 }
1488                                 challenge[i].time = realtime;
1489                                 // send the challenge
1490                                 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1491                                 return true;
1492                         }
1493                         if (length > 8 && !memcmp(string, "connect\\", 8))
1494                         {
1495                                 string += 7;
1496                                 length -= 7;
1497                                 if ((s = SearchInfostring(string, "challenge")))
1498                                 {
1499                                         // validate the challenge
1500                                         for (i = 0;i < MAX_CHALLENGES;i++)
1501                                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1502                                                         break;
1503                                         if (i < MAX_CHALLENGES)
1504                                         {
1505                                                 // check engine protocol
1506                                                 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1507                                                 {
1508                                                         if (developer.integer)
1509                                                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1510                                                         NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1511                                                 }
1512                                                 else
1513                                                 {
1514                                                         // see if this is a duplicate connection request
1515                                                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1516                                                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1517                                                                         break;
1518                                                         if (clientnum < svs.maxclients && realtime - client->connecttime < net_messagerejointimeout.value)
1519                                                         {
1520                                                                 // client is still trying to connect,
1521                                                                 // so we send a duplicate reply
1522                                                                 if (developer.integer)
1523                                                                         Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1524                                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1525                                                         }
1526 #if 0
1527                                                         else if (clientnum < svs.maxclients)
1528                                                         {
1529                                                                 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1530                                                                 {
1531                                                                         // client crashed and is coming back, keep their stuff intact
1532                                                                         SV_SendServerinfo(client);
1533                                                                         //host_client = client;
1534                                                                         //SV_DropClient (true);
1535                                                                 }
1536                                                                 // else ignore them
1537                                                         }
1538 #endif
1539                                                         else
1540                                                         {
1541                                                                 // this is a new client, find a slot
1542                                                                 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1543                                                                         if (!client->active)
1544                                                                                 break;
1545                                                                 if (clientnum < svs.maxclients)
1546                                                                 {
1547                                                                         // prepare the client struct
1548                                                                         if ((conn = NetConn_Open(mysocket, peeraddress)))
1549                                                                         {
1550                                                                                 // allocated connection
1551                                                                                 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1552                                                                                 if (developer.integer)
1553                                                                                         Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1554                                                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1555                                                                                 // now set up the client
1556                                                                                 SV_ConnectClient(clientnum, conn);
1557                                                                                 NetConn_Heartbeat(1);
1558                                                                         }
1559                                                                 }
1560                                                                 else
1561                                                                 {
1562                                                                         // server is full
1563                                                                         if (developer.integer)
1564                                                                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1565                                                                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1566                                                                 }
1567                                                         }
1568                                                 }
1569                                         }
1570                                 }
1571                                 return true;
1572                         }
1573                         if (length >= 7 && !memcmp(string, "getinfo", 7))
1574                         {
1575                                 const char *challenge = NULL;
1576
1577                                 // If there was a challenge in the getinfo message
1578                                 if (length > 8 && string[7] == ' ')
1579                                         challenge = string + 8;
1580
1581                                 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
1582                                 {
1583                                         if (developer.integer)
1584                                                 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1585                                         NetConn_WriteString(mysocket, response, peeraddress);
1586                                 }
1587                                 return true;
1588                         }
1589                         if (length >= 9 && !memcmp(string, "getstatus", 9))
1590                         {
1591                                 const char *challenge = NULL;
1592
1593                                 // If there was a challenge in the getinfo message
1594                                 if (length > 10 && string[9] == ' ')
1595                                         challenge = string + 10;
1596
1597                                 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
1598                                 {
1599                                         if (developer.integer)
1600                                                 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
1601                                         NetConn_WriteString(mysocket, response, peeraddress);
1602                                 }
1603                                 return true;
1604                         }
1605                         /*
1606                         if (!strncmp(string, "ping", 4))
1607                         {
1608                                 if (developer.integer)
1609                                         Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1610                                 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1611                                 return true;
1612                         }
1613                         if (!strncmp(string, "ack", 3))
1614                                 return true;
1615                         */
1616                         // we may not have liked the packet, but it was a command packet, so
1617                         // we're done processing this packet now
1618                         return true;
1619                 }
1620                 // LordHavoc: disabled netquake control packet support in server
1621 #if 0
1622                 {
1623                         int c, control;
1624                         // netquake control packets, supported for compatibility only
1625                         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1626                         {
1627                                 c = data[4];
1628                                 data += 5;
1629                                 length -= 5;
1630                                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1631                                 switch (c)
1632                                 {
1633                                 case CCREQ_CONNECT:
1634                                         //if (developer.integer)
1635                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1636                                         if (length >= (int)strlen("QUAKE") + 1 + 1)
1637                                         {
1638                                                 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1639                                                 {
1640                                                         if (developer.integer)
1641                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1642                                                         SZ_Clear(&net_message);
1643                                                         // save space for the header, filled in later
1644                                                         MSG_WriteLong(&net_message, 0);
1645                                                         MSG_WriteByte(&net_message, CCREP_REJECT);
1646                                                         MSG_WriteString(&net_message, "Incompatible version.\n");
1647                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1648                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1649                                                         SZ_Clear(&net_message);
1650                                                 }
1651                                                 else
1652                                                 {
1653                                                         // see if this is a duplicate connection request
1654                                                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1655                                                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1656                                                                         break;
1657                                                         if (clientnum < svs.maxclients)
1658                                                         {
1659                                                                 // duplicate connection request
1660                                                                 if (realtime - client->connecttime < 2.0)
1661                                                                 {
1662                                                                         // client is still trying to connect,
1663                                                                         // so we send a duplicate reply
1664                                                                         if (developer.integer)
1665                                                                                 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1666                                                                         SZ_Clear(&net_message);
1667                                                                         // save space for the header, filled in later
1668                                                                         MSG_WriteLong(&net_message, 0);
1669                                                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
1670                                                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1671                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1672                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1673                                                                         SZ_Clear(&net_message);
1674                                                                 }
1675 #if 0
1676                                                                 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1677                                                                 {
1678                                                                         SV_SendServerinfo(client);
1679                                                                         // the old client hasn't sent us anything
1680                                                                         // in quite a while, so kick off and let
1681                                                                         // the retry take care of it...
1682                                                                         //host_client = client;
1683                                                                         //SV_DropClient (true);
1684                                                                 }
1685 #endif
1686                                                         }
1687                                                         else
1688                                                         {
1689                                                                 // this is a new client, find a slot
1690                                                                 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1691                                                                         if (!client->active)
1692                                                                                 break;
1693                                                                 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1694                                                                 {
1695                                                                         // connect to the client
1696                                                                         // everything is allocated, just fill in the details
1697                                                                         strlcpy (conn->address, addressstring2, sizeof (conn->address));
1698                                                                         if (developer.integer)
1699                                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1700                                                                         // send back the info about the server connection
1701                                                                         SZ_Clear(&net_message);
1702                                                                         // save space for the header, filled in later
1703                                                                         MSG_WriteLong(&net_message, 0);
1704                                                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
1705                                                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1706                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1707                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1708                                                                         SZ_Clear(&net_message);
1709                                                                         // now set up the client struct
1710                                                                         SV_ConnectClient(clientnum, conn);
1711                                                                         NetConn_Heartbeat(1);
1712                                                                 }
1713                                                                 else
1714                                                                 {
1715                                                                         //if (developer.integer)
1716                                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1717                                                                         // no room; try to let player know
1718                                                                         SZ_Clear(&net_message);
1719                                                                         // save space for the header, filled in later
1720                                                                         MSG_WriteLong(&net_message, 0);
1721                                                                         MSG_WriteByte(&net_message, CCREP_REJECT);
1722                                                                         MSG_WriteString(&net_message, "Server is full.\n");
1723                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1724                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1725                                                                         SZ_Clear(&net_message);
1726                                                                 }
1727                                                         }
1728                                                 }
1729                                         }
1730                                         break;
1731 #if 0
1732                                 case CCREQ_SERVER_INFO:
1733                                         if (developer.integer)
1734                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1735                                         if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1736                                         {
1737                                                 if (developer.integer)
1738                                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1739                                                 SZ_Clear(&net_message);
1740                                                 // save space for the header, filled in later
1741                                                 MSG_WriteLong(&net_message, 0);
1742                                                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1743                                                 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1744                                                 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1745                                                 MSG_WriteString(&net_message, hostname.string);
1746                                                 MSG_WriteString(&net_message, sv.name);
1747                                                 MSG_WriteByte(&net_message, net_activeconnections);
1748                                                 MSG_WriteByte(&net_message, svs.maxclients);
1749                                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1750                                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1751                                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1752                                                 SZ_Clear(&net_message);
1753                                         }
1754                                         break;
1755                                 case CCREQ_PLAYER_INFO:
1756                                         if (developer.integer)
1757                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1758                                         if (sv.active)
1759                                         {
1760                                                 int playerNumber, activeNumber, clientNumber;
1761                                                 client_t *client;
1762
1763                                                 playerNumber = MSG_ReadByte();
1764                                                 activeNumber = -1;
1765                                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1766                                                         if (client->active && ++activeNumber == playerNumber)
1767                                                                 break;
1768                                                 if (clientNumber != svs.maxclients)
1769                                                 {
1770                                                         SZ_Clear(&net_message);
1771                                                         // save space for the header, filled in later
1772                                                         MSG_WriteLong(&net_message, 0);
1773                                                         MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1774                                                         MSG_WriteByte(&net_message, playerNumber);
1775                                                         MSG_WriteString(&net_message, client->name);
1776                                                         MSG_WriteLong(&net_message, client->colors);
1777                                                         MSG_WriteLong(&net_message, (int)client->edict->fields.server->frags);
1778                                                         MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
1779                                                         MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
1780                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1781                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1782                                                         SZ_Clear(&net_message);
1783                                                 }
1784                                         }
1785                                         break;
1786                                 case CCREQ_RULE_INFO:
1787                                         if (developer.integer)
1788                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1789                                         if (sv.active)
1790                                         {
1791                                                 char *prevCvarName;
1792                                                 cvar_t *var;
1793
1794                                                 // find the search start location
1795                                                 prevCvarName = MSG_ReadString();
1796                                                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1797
1798                                                 // send the response
1799                                                 SZ_Clear(&net_message);
1800                                                 // save space for the header, filled in later
1801                                                 MSG_WriteLong(&net_message, 0);
1802                                                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1803                                                 if (var)
1804                                                 {
1805                                                         MSG_WriteString(&net_message, var->name);
1806                                                         MSG_WriteString(&net_message, var->string);
1807                                                 }
1808                                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1809                                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1810                                                 SZ_Clear(&net_message);
1811                                         }
1812                                         break;
1813 #endif
1814                                 default:
1815                                         break;
1816                                 }
1817                                 // we may not have liked the packet, but it was a valid control
1818                                 // packet, so we're done processing this packet now
1819                                 return true;
1820                         }
1821                 }
1822 #endif
1823                 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1824                 {
1825                         if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1826                         {
1827                                 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1828                                         SV_ReadClientMessage();
1829                                 return ret;
1830                         }
1831                 }
1832         }
1833         return 0;
1834 }
1835
1836 void NetConn_ServerFrame(void)
1837 {
1838         int i, length;
1839         lhnetaddress_t peeraddress;
1840         netconn_t *conn;
1841         NetConn_UpdateServerStuff();
1842         for (i = 0;i < sv_numsockets;i++)
1843                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1844                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1845         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1846         {
1847                 // never timeout loopback connections
1848                 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1849                 {
1850                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1851                         SV_DropClient(false);
1852                 }
1853         }
1854         for (conn = netconn_list;conn;conn = conn->next)
1855                 NetConn_ReSendMessage(conn);
1856 }
1857
1858 void NetConn_QueryMasters(void)
1859 {
1860         int i;
1861         int masternum;
1862         lhnetaddress_t masteraddress;
1863         lhnetaddress_t broadcastaddress;
1864         char request[256];
1865
1866         if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
1867                 return;
1868
1869         // 26000 is the default quake server port, servers on other ports will not
1870         // be found
1871         // note this is IPv4-only, I doubt there are IPv6-only LANs out there
1872         LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
1873
1874         for (i = 0;i < cl_numsockets;i++)
1875         {
1876                 if (cl_sockets[i])
1877                 {
1878                         // search LAN for Quake servers
1879                         SZ_Clear(&net_message);
1880                         // save space for the header, filled in later
1881                         MSG_WriteLong(&net_message, 0);
1882                         MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1883                         MSG_WriteString(&net_message, "QUAKE");
1884                         MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1885                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1886                         NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
1887                         SZ_Clear(&net_message);
1888
1889                         // search LAN for DarkPlaces servers
1890                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
1891
1892                         // build the getservers message to send to the master servers
1893                         dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1894
1895                         // search internet
1896                         for (masternum = 0;sv_masters[masternum].name;masternum++)
1897                         {
1898                                 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1899                                 {
1900                                         masterquerycount++;
1901                                         NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1902                                 }
1903                         }
1904                 }
1905         }
1906         if (!masterquerycount)
1907         {
1908                 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1909                 M_Update_Return_Reason("No network");
1910         }
1911 }
1912
1913 void NetConn_Heartbeat(int priority)
1914 {
1915         lhnetaddress_t masteraddress;
1916         int masternum;
1917         lhnetsocket_t *mysocket;
1918
1919         // if it's a state change (client connected), limit next heartbeat to no
1920         // more than 30 sec in the future
1921         if (priority == 1 && nextheartbeattime > realtime + 30.0)
1922                 nextheartbeattime = realtime + 30.0;
1923
1924         // limit heartbeatperiod to 30 to 270 second range,
1925         // lower limit is to avoid abusing master servers with excess traffic,
1926         // upper limit is to avoid timing out on the master server (which uses
1927         // 300 sec timeout)
1928         if (sv_heartbeatperiod.value < 30)
1929                 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1930         if (sv_heartbeatperiod.value > 270)
1931                 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1932
1933         // make advertising optional and don't advertise singleplayer games, and
1934         // only send a heartbeat as often as the admin wants
1935         if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1936         {
1937                 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1938                 for (masternum = 0;sv_masters[masternum].name;masternum++)
1939                         if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1940                                 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1941         }
1942 }
1943
1944 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1945 {
1946         int i, count = 0;
1947         qbyte sent[MAX_SCOREBOARD];
1948
1949         memset(sent, 0, sizeof(sent));
1950
1951         // simultaneously wait for the first CanSendMessage and send the message,
1952         // then wait for a second CanSendMessage (verifying it was received), or
1953         // the client drops and is no longer counted
1954         // the loop aborts when either it runs out of clients to send to, or a
1955         // timeout expires
1956         blocktime += Sys_DoubleTime();
1957         do
1958         {
1959                 count = 0;
1960                 NetConn_ClientFrame();
1961                 NetConn_ServerFrame();
1962                 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1963                 {
1964                         if (host_client->netconnection)
1965                         {
1966                                 if (NetConn_CanSendMessage(host_client->netconnection))
1967                                 {
1968                                         if (!sent[i])
1969                                                 NetConn_SendReliableMessage(host_client->netconnection, data);
1970                                         sent[i] = true;
1971                                 }
1972                                 if (!NetConn_CanSendMessage(host_client->netconnection))
1973                                         count++;
1974                         }
1975                 }
1976         }
1977         while (count && Sys_DoubleTime() < blocktime);
1978         return count;
1979 }
1980
1981 static void Net_Heartbeat_f(void)
1982 {
1983         if (sv.active)
1984                 NetConn_Heartbeat(2);
1985         else
1986                 Con_Print("No server running, can not heartbeat to master server.\n");
1987 }
1988
1989 void PrintStats(netconn_t *conn)
1990 {
1991         Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1992 }
1993
1994 void Net_Stats_f(void)
1995 {
1996         netconn_t *conn;
1997         Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
1998         Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
1999         Con_Printf("reliable messages sent     = %i\n", reliableMessagesSent);
2000         Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
2001         Con_Printf("packetsSent                = %i\n", packetsSent);
2002         Con_Printf("packetsReSent              = %i\n", packetsReSent);
2003         Con_Printf("packetsReceived            = %i\n", packetsReceived);
2004         Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
2005         Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
2006         Con_Print("connections                =\n");
2007         for (conn = netconn_list;conn;conn = conn->next)
2008                 PrintStats(conn);
2009 }
2010
2011 void Net_Slist_f(void)
2012 {
2013         ServerList_ResetMasks();
2014         serverlist_sortbyfield = SLIF_PING;
2015         serverlist_sortdescending = false;
2016     if (m_state != m_slist) {
2017                 Con_Print("Sending requests to master servers\n");
2018                 ServerList_QueryList();
2019                 serverlist_consoleoutput = true;
2020                 Con_Print("Listening for replies...\n");
2021         } else
2022                 ServerList_QueryList();
2023 }
2024
2025 void NetConn_Init(void)
2026 {
2027         int i;
2028         lhnetaddress_t tempaddress;
2029         netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
2030         Cmd_AddCommand("net_stats", Net_Stats_f);
2031         Cmd_AddCommand("net_slist", Net_Slist_f);
2032         Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
2033         Cvar_RegisterVariable(&net_slist_queriespersecond);
2034         Cvar_RegisterVariable(&net_slist_queriesperframe);
2035         Cvar_RegisterVariable(&net_slist_timeout);
2036         Cvar_RegisterVariable(&net_slist_maxtries);
2037         Cvar_RegisterVariable(&net_messagetimeout);
2038         Cvar_RegisterVariable(&net_messagerejointimeout);
2039         Cvar_RegisterVariable(&net_connecttimeout);
2040         Cvar_RegisterVariable(&cl_netlocalping);
2041         Cvar_RegisterVariable(&cl_netpacketloss);
2042         Cvar_RegisterVariable(&hostname);
2043         Cvar_RegisterVariable(&developer_networking);
2044         Cvar_RegisterVariable(&cl_netport);
2045         Cvar_RegisterVariable(&sv_netport);
2046         Cvar_RegisterVariable(&net_address);
2047         //Cvar_RegisterVariable(&net_address_ipv6);
2048         Cvar_RegisterVariable(&sv_public);
2049         Cvar_RegisterVariable(&sv_heartbeatperiod);
2050         for (i = 0;sv_masters[i].name;i++)
2051                 Cvar_RegisterVariable(&sv_masters[i]);
2052 // 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.
2053         if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
2054         {
2055                 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
2056                 {
2057                         Con_Printf("-ip option used, setting net_address to \"%s\"\n");
2058                         Cvar_SetQuick(&net_address, com_argv[i + 1]);
2059                 }
2060                 else
2061                         Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
2062         }
2063 // 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
2064         if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
2065         {
2066                 i = atoi(com_argv[i + 1]);
2067                 if (i >= 0 && i < 65536)
2068                 {
2069                         Con_Printf("-port option used, setting port cvar to %i\n", i);
2070                         Cvar_SetValueQuick(&sv_netport, i);
2071                 }
2072                 else
2073                         Con_Printf("-port option used, but %i is not a valid port number\n", i);
2074         }
2075         cl_numsockets = 0;
2076         sv_numsockets = 0;
2077         net_message.data = net_message_buf;
2078         net_message.maxsize = sizeof(net_message_buf);
2079         net_message.cursize = 0;
2080         LHNET_Init();
2081 }
2082
2083 void NetConn_Shutdown(void)
2084 {
2085         NetConn_CloseClientPorts();
2086         NetConn_CloseServerPorts();
2087         LHNET_Shutdown();
2088 }
2089