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