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