fix a thinko in big endian support (forgot to use defined() in a #elif)
[divverent/darkplaces.git] / netconn.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
5
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
15 See the GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20
21 */
22
23 #include "quakedef.h"
24 #include "lhnet.h"
25
26 #define MASTER_PORT 27950
27
28 cvar_t sv_public = {0, "sv_public", "0"};
29 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "180"};
30
31 static cvar_t sv_masters [] =
32 {
33         {CVAR_SAVE, "sv_master1", ""},
34         {CVAR_SAVE, "sv_master2", ""},
35         {CVAR_SAVE, "sv_master3", ""},
36         {CVAR_SAVE, "sv_master4", ""},
37         {0, "sv_masterextra1", "69.59.212.88"},
38         {0, 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) strlcpy(game, s, sizeof (game));else game[0] = 0;
699                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(mod , s, sizeof (mod ));else mod[0]  = 0;
700                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(map , s, sizeof (map ));else map[0]  = 0;
701                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(name, s, sizeof (name));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                                 snprintf (ipstring, sizeof (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                                 strlcpy (hostcache[n].cname, ipstring, sizeof (hostcache[n].cname));
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                         strlcpy (m_return_reason, data, sizeof (m_return_reason));
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                                         strlcpy (hostcache[n].name, MSG_ReadString(), sizeof (hostcache[n].name));
895                                         strlcpy (hostcache[n].map, MSG_ReadString(), sizeof (hostcache[n].map));
896                                         hostcache[n].users = MSG_ReadByte();
897                                         hostcache[n].maxusers = MSG_ReadByte();
898                                         c = MSG_ReadByte();
899                                         if (c != NET_PROTOCOL_VERSION)
900                                         {
901                                                 strlcpy (hostcache[n].cname, hostcache[n].name, sizeof (hostcache[n].cname));
902                                                 strcpy(hostcache[n].name, "*");
903                                                 strlcat (hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name));
904                                         }
905                                         strlcpy (hostcache[n].cname, cname, sizeof (hostcache[n].cname));
906                                 }
907                         }
908                         break;
909                 case CCREP_PLAYER_INFO:
910                         // we got a CCREP_PLAYER_INFO??
911                         //if (developer.integer)
912                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
913                         break;
914                 case CCREP_RULE_INFO:
915                         // we got a CCREP_RULE_INFO??
916                         //if (developer.integer)
917                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
918                         break;
919 #endif
920                 default:
921                         break;
922                 }
923                 // we may not have liked the packet, but it was a valid control
924                 // packet, so we're done processing this packet now
925                 return true;
926         }
927         ret = 0;
928         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)
929                 CL_ParseServerMessage();
930         return ret;
931 }
932
933 void NetConn_ClientFrame(void)
934 {
935         int i, length;
936         lhnetaddress_t peeraddress;
937         netconn_t *conn;
938         NetConn_UpdateServerStuff();
939         if (cls.connect_trying && cls.connect_nextsendtime < realtime)
940         {
941                 if (cls.connect_remainingtries == 0)
942                 {
943                         cls.connect_trying = false;
944                         if (m_state == m_slist)
945                                 strcpy (m_return_reason, "Connect: Failed");
946                         else
947                                 Con_Printf("Connect failed\n");
948                         return;
949                 }
950                 if (cls.connect_nextsendtime)
951                 {
952                         if (m_state == m_slist)
953                                 strcpy (m_return_reason, "Connect: Still trying");
954                         else
955                                 Con_Printf("Still trying...\n");
956                 }
957                 else
958                 {
959                         if (m_state == m_slist)
960                                 strcpy (m_return_reason, "Connect: Trying");
961                         else
962                                 Con_Printf("Trying...\n");
963                 }
964                 cls.connect_nextsendtime = realtime + 1;
965                 cls.connect_remainingtries--;
966                 // try challenge first (newer server)
967                 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
968                 // then try netquake as a fallback (old server, or netquake)
969                 SZ_Clear(&net_message);
970                 // save space for the header, filled in later
971                 MSG_WriteLong(&net_message, 0);
972                 MSG_WriteByte(&net_message, CCREQ_CONNECT);
973                 MSG_WriteString(&net_message, "QUAKE");
974                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
975                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
976                 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
977                 SZ_Clear(&net_message);
978         }
979         for (i = 0;i < cl_numsockets;i++)
980                 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
981                         NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
982         if (cls.netcon && realtime > cls.netcon->timeout)
983         {
984                 Con_Printf("Connection timed out\n");
985                 CL_Disconnect();
986         }
987         for (conn = netconn_list;conn;conn = conn->next)
988                 NetConn_ReSendMessage(conn);
989 }
990
991 #define MAX_CHALLENGES 128
992 struct
993 {
994         lhnetaddress_t address;
995         double time;
996         char string[12];
997 }
998 challenge[MAX_CHALLENGES];
999
1000 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1001 {
1002         int i;
1003         char c;
1004         for (i = 0;i < bufferlength - 1;i++)
1005         {
1006                 do
1007                 {
1008                         c = rand () % (127 - 33) + 33;
1009                 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1010                 buffer[i] = c;
1011         }
1012         buffer[i] = 0;
1013 }
1014
1015 extern void SV_ConnectClient(int clientnum, netconn_t *netconnection);
1016 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1017 {
1018         int i, n, ret, clientnum, responselength, best;
1019         double besttime;
1020         client_t *client;
1021         netconn_t *conn;
1022         char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1023
1024         if (sv.active)
1025         {
1026                 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1027                 {
1028                         // received a command string - strip off the packaging and put it
1029                         // into our string buffer with NULL termination
1030                         data += 4;
1031                         length -= 4;
1032                         length = min(length, (int)sizeof(stringbuf) - 1);
1033                         memcpy(stringbuf, data, length);
1034                         stringbuf[length] = 0;
1035                         string = stringbuf;
1036
1037                         if (developer.integer)
1038                         {
1039                                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1040                                 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1041                                 Com_HexDumpToConsole(data, length);
1042                         }
1043
1044                         if (length >= 12 && !memcmp(string, "getchallenge", 12))
1045                         {
1046                                 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1047                                 {
1048                                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1049                                                 break;
1050                                         if (besttime > challenge[i].time)
1051                                                 besttime = challenge[best = i].time;
1052                                 }
1053                                 // if we did not find an exact match, choose the oldest and
1054                                 // update address and string
1055                                 if (i == MAX_CHALLENGES)
1056                                 {
1057                                         i = best;
1058                                         challenge[i].address = *peeraddress;
1059                                         NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1060                                 }
1061                                 challenge[i].time = realtime;
1062                                 // send the challenge
1063                                 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1064                                 return true;
1065                         }
1066                         if (length > 8 && !memcmp(string, "connect\\", 8))
1067                         {
1068                                 string += 7;
1069                                 length -= 7;
1070                                 if ((s = SearchInfostring(string, "challenge")))
1071                                 {
1072                                         // validate the challenge
1073                                         for (i = 0;i < MAX_CHALLENGES;i++)
1074                                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1075                                                         break;
1076                                         if (i < MAX_CHALLENGES)
1077                                         {
1078                                                 // check engine protocol
1079                                                 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1080                                                 {
1081                                                         if (developer.integer)
1082                                                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1083                                                         NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1084                                                 }
1085                                                 else
1086                                                 {
1087                                                         // see if this is a duplicate connection request
1088                                                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1089                                                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1090                                                                         break;
1091                                                         if (clientnum < svs.maxclients)
1092                                                         {
1093                                                                 // duplicate connection request
1094                                                                 if (realtime - client->netconnection->connecttime < 2.0)
1095                                                                 {
1096                                                                         // client is still trying to connect,
1097                                                                         // so we send a duplicate reply
1098                                                                         if (developer.integer)
1099                                                                                 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1100                                                                         NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1101                                                                 }
1102                                                                 // only kick if old connection seems dead
1103                                                                 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1104                                                                 {
1105                                                                         // kick off connection and await retry
1106                                                                         client->deadsocket = true;
1107                                                                 }
1108                                                         }
1109                                                         else
1110                                                         {
1111                                                                 // this is a new client, find a slot
1112                                                                 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1113                                                                         if (!client->active)
1114                                                                                 break;
1115                                                                 if (clientnum < svs.maxclients)
1116                                                                 {
1117                                                                         // prepare the client struct
1118                                                                         if ((client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_clients_mempool)))
1119                                                                         {
1120                                                                                 if ((conn = NetConn_Open(mysocket, peeraddress)))
1121                                                                                 {
1122                                                                                         // allocated connection
1123                                                                                         LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1124                                                                                         if (developer.integer)
1125                                                                                                 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1126                                                                                         NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1127                                                                                         // now set up the client
1128                                                                                         SV_ConnectClient(clientnum, conn);
1129                                                                                         NetConn_Heartbeat(1);
1130                                                                                 }
1131                                                                                 else
1132                                                                                         EntityFrame4_FreeDatabase(client->entitydatabase4);
1133                                                                         }
1134                                                                 }
1135                                                                 else
1136                                                                 {
1137                                                                         // server is full
1138                                                                         if (developer.integer)
1139                                                                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1140                                                                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1141                                                                 }
1142                                                         }
1143                                                 }
1144                                         }
1145                                 }
1146                                 return true;
1147                         }
1148                         if (length >= 7 && !memcmp(string, "getinfo", 7))
1149                         {
1150                                 const char *challenge = NULL;
1151                                 // If there was a challenge in the getinfo message
1152                                 if (length > 8 && string[7] == ' ')
1153                                         challenge = string + 8;
1154                                 for (i = 0, n = 0;i < svs.maxclients;i++)
1155                                         if (svs.clients[i].active)
1156                                                 n++;
1157                                 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1158                                                         "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1159                                                         "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1160                                                         gamename, com_modname, svs.maxclients, n,
1161                                                         sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1162                                 // does it fit in the buffer?
1163                                 if (responselength < (int)sizeof(response))
1164                                 {
1165                                         if (developer.integer)
1166                                                 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1167                                         NetConn_WriteString(mysocket, response, peeraddress);
1168                                 }
1169                                 return true;
1170                         }
1171                         /*
1172                         if (!strncmp(string, "ping", 4))
1173                         {
1174                                 if (developer.integer)
1175                                         Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1176                                 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1177                                 return true;
1178                         }
1179                         if (!strncmp(string, "ack", 3))
1180                                 return true;
1181                         */
1182                         // we may not have liked the packet, but it was a command packet, so
1183                         // we're done processing this packet now
1184                         return true;
1185                 }
1186                 // LordHavoc: disabled netquake control packet support in server
1187 #if 0
1188                 {
1189                         int c, control;
1190                         // netquake control packets, supported for compatibility only
1191                         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1192                         {
1193                                 c = data[4];
1194                                 data += 5;
1195                                 length -= 5;
1196                                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1197                                 switch (c)
1198                                 {
1199                                 case CCREQ_CONNECT:
1200                                         //if (developer.integer)
1201                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1202                                         if (length >= (int)strlen("QUAKE") + 1 + 1)
1203                                         {
1204                                                 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1205                                                 {
1206                                                         if (developer.integer)
1207                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1208                                                         SZ_Clear(&net_message);
1209                                                         // save space for the header, filled in later
1210                                                         MSG_WriteLong(&net_message, 0);
1211                                                         MSG_WriteByte(&net_message, CCREP_REJECT);
1212                                                         MSG_WriteString(&net_message, "Incompatible version.\n");
1213                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1214                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1215                                                         SZ_Clear(&net_message);
1216                                                 }
1217                                                 else
1218                                                 {
1219                                                         // see if this is a duplicate connection request
1220                                                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1221                                                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1222                                                                         break;
1223                                                         if (clientnum < svs.maxclients)
1224                                                         {
1225                                                                 // duplicate connection request
1226                                                                 if (realtime - client->netconnection->connecttime < 2.0)
1227                                                                 {
1228                                                                         // client is still trying to connect,
1229                                                                         // so we send a duplicate reply
1230                                                                         if (developer.integer)
1231                                                                                 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1232                                                                         SZ_Clear(&net_message);
1233                                                                         // save space for the header, filled in later
1234                                                                         MSG_WriteLong(&net_message, 0);
1235                                                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
1236                                                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1237                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1238                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1239                                                                         SZ_Clear(&net_message);
1240                                                                 }
1241                                                                 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1242                                                                 {
1243                                                                         // the old client hasn't sent us anything
1244                                                                         // in quite a while, so kick off and let
1245                                                                         // the retry take care of it...
1246                                                                         client->deadsocket = true;
1247                                                                 }
1248                                                         }
1249                                                         else
1250                                                         {
1251                                                                 // this is a new client, find a slot
1252                                                                 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1253                                                                         if (!client->active)
1254                                                                                 break;
1255                                                                 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1256                                                                 {
1257                                                                         // connect to the client
1258                                                                         // everything is allocated, just fill in the details
1259                                                                         strlcpy (conn->address, addressstring2, sizeof (conn->address));
1260                                                                         if (developer.integer)
1261                                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1262                                                                         // send back the info about the server connection
1263                                                                         SZ_Clear(&net_message);
1264                                                                         // save space for the header, filled in later
1265                                                                         MSG_WriteLong(&net_message, 0);
1266                                                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
1267                                                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1268                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1269                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1270                                                                         SZ_Clear(&net_message);
1271                                                                         // now set up the client struct
1272                                                                         SV_ConnectClient(clientnum, conn);
1273                                                                         NetConn_Heartbeat(1);
1274                                                                 }
1275                                                                 else
1276                                                                 {
1277                                                                         //if (developer.integer)
1278                                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1279                                                                         // no room; try to let player know
1280                                                                         SZ_Clear(&net_message);
1281                                                                         // save space for the header, filled in later
1282                                                                         MSG_WriteLong(&net_message, 0);
1283                                                                         MSG_WriteByte(&net_message, CCREP_REJECT);
1284                                                                         MSG_WriteString(&net_message, "Server is full.\n");
1285                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1286                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1287                                                                         SZ_Clear(&net_message);
1288                                                                 }
1289                                                         }
1290                                                 }
1291                                         }
1292                                         break;
1293 #if 0
1294                                 case CCREQ_SERVER_INFO:
1295                                         if (developer.integer)
1296                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1297                                         if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1298                                         {
1299                                                 if (developer.integer)
1300                                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1301                                                 SZ_Clear(&net_message);
1302                                                 // save space for the header, filled in later
1303                                                 MSG_WriteLong(&net_message, 0);
1304                                                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1305                                                 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1306                                                 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1307                                                 MSG_WriteString(&net_message, hostname.string);
1308                                                 MSG_WriteString(&net_message, sv.name);
1309                                                 MSG_WriteByte(&net_message, net_activeconnections);
1310                                                 MSG_WriteByte(&net_message, svs.maxclients);
1311                                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1312                                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1313                                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1314                                                 SZ_Clear(&net_message);
1315                                         }
1316                                         break;
1317                                 case CCREQ_PLAYER_INFO:
1318                                         if (developer.integer)
1319                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1320                                         if (sv.active)
1321                                         {
1322                                                 int playerNumber, activeNumber, clientNumber;
1323                                                 client_t *client;
1324
1325                                                 playerNumber = MSG_ReadByte();
1326                                                 activeNumber = -1;
1327                                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1328                                                         if (client->active && ++activeNumber == playerNumber)
1329                                                                 break;
1330                                                 if (clientNumber != svs.maxclients)
1331                                                 {
1332                                                         SZ_Clear(&net_message);
1333                                                         // save space for the header, filled in later
1334                                                         MSG_WriteLong(&net_message, 0);
1335                                                         MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1336                                                         MSG_WriteByte(&net_message, playerNumber);
1337                                                         MSG_WriteString(&net_message, client->name);
1338                                                         MSG_WriteLong(&net_message, client->colors);
1339                                                         MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1340                                                         MSG_WriteLong(&net_message, (int)(realtime - client->netconnection->connecttime));
1341                                                         MSG_WriteString(&net_message, client->netconnection->address);
1342                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1343                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1344                                                         SZ_Clear(&net_message);
1345                                                 }
1346                                         }
1347                                         break;
1348                                 case CCREQ_RULE_INFO:
1349                                         if (developer.integer)
1350                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1351                                         if (sv.active)
1352                                         {
1353                                                 char *prevCvarName;
1354                                                 cvar_t *var;
1355
1356                                                 // find the search start location
1357                                                 prevCvarName = MSG_ReadString();
1358                                                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1359
1360                                                 // send the response
1361                                                 SZ_Clear(&net_message);
1362                                                 // save space for the header, filled in later
1363                                                 MSG_WriteLong(&net_message, 0);
1364                                                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1365                                                 if (var)
1366                                                 {
1367                                                         MSG_WriteString(&net_message, var->name);
1368                                                         MSG_WriteString(&net_message, var->string);
1369                                                 }
1370                                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1371                                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1372                                                 SZ_Clear(&net_message);
1373                                         }
1374                                         break;
1375 #endif
1376                                 default:
1377                                         break;
1378                                 }
1379                                 // we may not have liked the packet, but it was a valid control
1380                                 // packet, so we're done processing this packet now
1381                                 return true;
1382                         }
1383                 }
1384 #endif
1385                 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1386                 {
1387                         if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1388                         {
1389                                 sv_player = host_client->edict;
1390                                 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1391                                         SV_ReadClientMessage();
1392                                 return ret;
1393                         }
1394                 }
1395         }
1396         return 0;
1397 }
1398
1399 void NetConn_ServerFrame(void)
1400 {
1401         int i, length;
1402         lhnetaddress_t peeraddress;
1403         netconn_t *conn;
1404         NetConn_UpdateServerStuff();
1405         for (i = 0;i < sv_numsockets;i++)
1406                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1407                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1408         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1409         {
1410                 // never timeout loopback connections
1411                 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(host_client->netconnection->mysocket)) != LHNETADDRESSTYPE_LOOP)
1412                 {
1413                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1414                         sv_player = host_client->edict;
1415                         SV_DropClient(false);
1416                 }
1417         }
1418         for (conn = netconn_list;conn;conn = conn->next)
1419                 NetConn_ReSendMessage(conn);
1420 }
1421
1422 void NetConn_QueryMasters(void)
1423 {
1424         int i;
1425         int masternum;
1426         lhnetaddress_t masteraddress;
1427         char request[256];
1428
1429         if (hostCacheCount >= HOSTCACHESIZE)
1430                 return;
1431
1432         for (i = 0;i < cl_numsockets;i++)
1433         {
1434                 if (cl_sockets[i])
1435                 {
1436 #if 0
1437                         // search LAN
1438 #if 1
1439                         UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1440 #else
1441                         SZ_Clear(&net_message);
1442                         // save space for the header, filled in later
1443                         MSG_WriteLong(&net_message, 0);
1444                         MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1445                         MSG_WriteString(&net_message, "QUAKE");
1446                         MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1447                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1448                         UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1449                         SZ_Clear(&net_message);
1450 #endif
1451 #endif
1452
1453                         // build the getservers
1454                         snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1455
1456                         // search internet
1457                         for (masternum = 0;sv_masters[masternum].name;masternum++)
1458                         {
1459                                 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1460                                 {
1461                                         masterquerycount++;
1462                                         NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1463                                 }
1464                         }
1465                 }
1466         }
1467         if (!masterquerycount)
1468         {
1469                 Con_Printf("Unable to query master servers, no suitable network sockets active.\n");
1470                 strcpy(m_return_reason, "No network");
1471         }
1472 }
1473
1474 void NetConn_Heartbeat(int priority)
1475 {
1476         lhnetaddress_t masteraddress;
1477         int masternum;
1478         lhnetsocket_t *mysocket;
1479
1480         // if it's a state change (client connected), limit next heartbeat to no
1481         // more than 30 sec in the future
1482         if (priority == 1 && nextheartbeattime > realtime + 30.0)
1483                 nextheartbeattime = realtime + 30.0;
1484
1485         // limit heartbeatperiod to 30 to 270 second range,
1486         // lower limit is to avoid abusing master servers with excess traffic,
1487         // upper limit is to avoid timing out on the master server (which uses
1488         // 300 sec timeout)
1489         if (sv_heartbeatperiod.value < 30)
1490                 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1491         if (sv_heartbeatperiod.value > 270)
1492                 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1493
1494         // make advertising optional and don't advertise singleplayer games, and
1495         // only send a heartbeat as often as the admin wants
1496         if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1497         {
1498                 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1499                 for (masternum = 0;sv_masters[masternum].name;masternum++)
1500                         if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1501                                 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1502         }
1503 }
1504
1505 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1506 {
1507         int i, count = 0;
1508         qbyte sent[MAX_SCOREBOARD];
1509
1510         memset(sent, 0, sizeof(sent));
1511
1512         // simultaneously wait for the first CanSendMessage and send the message,
1513         // then wait for a second CanSendMessage (verifying it was received), or
1514         // the client drops and is no longer counted
1515         // the loop aborts when either it runs out of clients to send to, or a
1516         // timeout expires
1517         blocktime += Sys_DoubleTime();
1518         do
1519         {
1520                 count = 0;
1521                 NetConn_ClientFrame();
1522                 NetConn_ServerFrame();
1523                 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1524                 {
1525                         if (host_client->netconnection)
1526                         {
1527                                 if (NetConn_CanSendMessage(host_client->netconnection))
1528                                 {
1529                                         if (!sent[i])
1530                                                 NetConn_SendReliableMessage(host_client->netconnection, data);
1531                                         sent[i] = true;
1532                                 }
1533                                 if (!NetConn_CanSendMessage(host_client->netconnection))
1534                                         count++;
1535                         }
1536                 }
1537         }
1538         while (count && Sys_DoubleTime() < blocktime);
1539         return count;
1540 }
1541
1542 static void Net_Heartbeat_f(void)
1543 {
1544         if (sv.active)
1545                 NetConn_Heartbeat(2);
1546         else
1547                 Con_Printf("No server running, can not heartbeat to master server.\n");
1548 }
1549
1550 void PrintStats(netconn_t *conn)
1551 {
1552         Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1553 }
1554
1555 void Net_Stats_f(void)
1556 {
1557         netconn_t *conn;
1558         Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
1559         Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
1560         Con_Printf("reliable messages sent     = %i\n", reliableMessagesSent);
1561         Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1562         Con_Printf("packetsSent                = %i\n", packetsSent);
1563         Con_Printf("packetsReSent              = %i\n", packetsReSent);
1564         Con_Printf("packetsReceived            = %i\n", packetsReceived);
1565         Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
1566         Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
1567         Con_Printf("connections                =\n");
1568         for (conn = netconn_list;conn;conn = conn->next)
1569                 PrintStats(conn);
1570 }
1571
1572 void Net_Slist_f(void)
1573 {
1574         masterquerytime = realtime;
1575         masterquerycount = 0;
1576         masterreplycount = 0;
1577         serverquerycount = 0;
1578         serverreplycount = 0;
1579         hostCacheCount = 0;
1580         memset(&pingcache, 0, sizeof(pingcache));
1581         if (m_state != m_slist)
1582                 Con_Printf("Sending requests to master servers\n");
1583         NetConn_QueryMasters();
1584         if (m_state != m_slist)
1585                 Con_Printf("Listening for replies...\n");
1586 }
1587
1588 void NetConn_Init(void)
1589 {
1590         int i;
1591         lhnetaddress_t tempaddress;
1592         netconn_mempool = Mem_AllocPool("Networking");
1593         Cmd_AddCommand("net_stats", Net_Stats_f);
1594         Cmd_AddCommand("net_slist", Net_Slist_f);
1595         Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1596         Cvar_RegisterVariable(&net_messagetimeout);
1597         Cvar_RegisterVariable(&net_messagerejointimeout);
1598         Cvar_RegisterVariable(&net_connecttimeout);
1599         Cvar_RegisterVariable(&cl_fakelocalping_min);
1600         Cvar_RegisterVariable(&cl_fakelocalping_max);
1601         Cvar_RegisterVariable(&cl_fakepacketloss_receive);
1602         Cvar_RegisterVariable(&cl_fakepacketloss_send);
1603         Cvar_RegisterVariable(&sv_fakepacketloss_receive);
1604         Cvar_RegisterVariable(&sv_fakepacketloss_send);
1605         Cvar_RegisterVariable(&hostname);
1606         Cvar_RegisterVariable(&developer_networking);
1607         Cvar_RegisterVariable(&cl_netport);
1608         Cvar_RegisterVariable(&cl_netaddress);
1609         Cvar_RegisterVariable(&cl_netaddress_ipv6);
1610         Cvar_RegisterVariable(&sv_netport);
1611         Cvar_RegisterVariable(&sv_netaddress);
1612         Cvar_RegisterVariable(&sv_netaddress_ipv6);
1613         Cvar_RegisterVariable(&sv_public);
1614         Cvar_RegisterVariable(&sv_heartbeatperiod);
1615         for (i = 0;sv_masters[i].name;i++)
1616                 Cvar_RegisterVariable(&sv_masters[i]);
1617         if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1618         {
1619                 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1620                 {
1621                         Con_Printf("-ip option used, setting cl_netaddress and sv_netaddress to address \"%s\"\n");
1622                         Cvar_SetQuick(&cl_netaddress, com_argv[i + 1]);
1623                         Cvar_SetQuick(&sv_netaddress, com_argv[i + 1]);
1624                 }
1625                 else
1626                         Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1627         }
1628         if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1629         {
1630                 i = atoi(com_argv[i + 1]);
1631                 if (i >= 0 && i < 65536)
1632                 {
1633                         Con_Printf("-port option used, setting port cvar to %i\n", i);
1634                         Cvar_SetValueQuick(&sv_netport, i);
1635                 }
1636                 else
1637                         Con_Printf("-port option used, but %i is not a valid port number\n", i);
1638         }
1639         cl_numsockets = 0;
1640         sv_numsockets = 0;
1641         memset(&pingcache, 0, sizeof(pingcache));
1642         SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1643         LHNET_Init();
1644 }
1645
1646 void NetConn_Shutdown(void)
1647 {
1648         NetConn_CloseClientPorts();
1649         NetConn_CloseServerPorts();
1650         LHNET_Shutdown();
1651 }
1652