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