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