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