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