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