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