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