2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
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.
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.
15 See the GNU General Public License for more details.
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.
26 #define MASTER_PORT 27950
28 cvar_t sv_public = {0, "sv_public", "0"};
29 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "180"};
31 static cvar_t sv_masters [] =
33 {CVAR_SAVE, "sv_master1", ""},
34 {CVAR_SAVE, "sv_master2", ""},
35 {CVAR_SAVE, "sv_master3", ""},
36 {CVAR_SAVE, "sv_master4", ""},
37 {0, "sv_masterextra1", "198.88.152.4"},
38 {0, "sv_masterextra2", "68.102.242.12"},
42 static double nextheartbeattime = 0;
44 sizebuf_t net_message;
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"};
52 cvar_t cl_fakelocalping_min = {0, "cl_fakelocalping_min","0"};
53 cvar_t cl_fakelocalping_max = {0, "cl_fakelocalping_max","0"};
54 static cvar_t cl_fakepacketloss_receive = {0, "cl_fakepacketloss_receive","0"};
55 static cvar_t cl_fakepacketloss_send = {0, "cl_fakepacketloss_send","0"};
56 static cvar_t sv_fakepacketloss_receive = {0, "sv_fakepacketloss_receive","0"};
57 static cvar_t sv_fakepacketloss_send = {0, "sv_fakepacketloss_send","0"};
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;
67 static int unreliableMessagesSent = 0;
68 static int unreliableMessagesReceived = 0;
69 static int reliableMessagesSent = 0;
70 static int reliableMessagesReceived = 0;
72 int hostCacheCount = 0;
73 hostcache_t hostcache[HOSTCACHESIZE];
75 static qbyte sendbuffer[NET_MAXMESSAGE];
76 static qbyte readbuffer[NET_MAXMESSAGE];
79 lhnetsocket_t *cl_sockets[16];
81 lhnetsocket_t *sv_sockets[16];
83 netconn_t *netconn_list = NULL;
84 mempool_t *netconn_mempool = NULL;
86 cvar_t cl_netport = {0, "cl_port", "0"};
87 cvar_t cl_netaddress = {0, "cl_netaddress", "0.0.0.0"};
88 cvar_t cl_netaddress_ipv6 = {0, "cl_netaddress_ipv6", "[0:0:0:0:0:0:0:0]:0"};
90 cvar_t sv_netport = {0, "port", "26000"};
91 cvar_t sv_netaddress = {0, "sv_netaddress", "0.0.0.0"};
92 cvar_t sv_netaddress_ipv6 = {0, "sv_netaddress_ipv6", "[0:0:0:0:0:0:0:0]:26000"};
94 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
96 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
98 if (cl_fakepacketloss_receive.integer)
99 for (i = 0;i < cl_numsockets;i++)
100 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_fakepacketloss_receive.integer)
102 if (sv_fakepacketloss_receive.integer)
103 for (i = 0;i < cl_numsockets;i++)
104 if (sv_sockets[i] == mysocket && (rand() % 100) < sv_fakepacketloss_receive.integer)
106 if (developer_networking.integer && length != 0)
108 char addressstring[128], addressstring2[128];
109 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
112 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
113 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
114 Com_HexDumpToConsole(data, length);
117 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
122 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
126 if (cl_fakepacketloss_send.integer)
127 for (i = 0;i < cl_numsockets;i++)
128 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_fakepacketloss_send.integer)
130 if (sv_fakepacketloss_send.integer)
131 for (i = 0;i < cl_numsockets;i++)
132 if (sv_sockets[i] == mysocket && (rand() % 100) < sv_fakepacketloss_send.integer)
134 ret = LHNET_Write(mysocket, data, length, peeraddress);
135 if (developer_networking.integer)
137 char addressstring[128], addressstring2[128];
138 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
139 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
140 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
141 Com_HexDumpToConsole(data, length);
146 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
148 // note this does not include the trailing NULL because we add that in the parser
149 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
152 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
154 unsigned int packetLen;
155 unsigned int dataLen;
157 unsigned int *header;
160 if (data->cursize == 0)
161 Sys_Error("Datagram_SendMessage: zero length message\n");
163 if (data->cursize > NET_MAXMESSAGE)
164 Sys_Error("Datagram_SendMessage: message too big %u\n", data->cursize);
166 if (conn->canSend == false)
167 Sys_Error("SendMessage: called with canSend == false\n");
170 memcpy(conn->sendMessage, data->data, data->cursize);
171 conn->sendMessageLength = data->cursize;
173 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
175 dataLen = conn->sendMessageLength;
180 dataLen = MAX_PACKETFRAGMENT;
184 packetLen = NET_HEADERSIZE + dataLen;
186 header = (void *)sendbuffer;
187 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
188 header[1] = BigLong(conn->sendSequence);
189 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
191 conn->sendSequence++;
192 conn->canSend = false;
194 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
197 conn->lastSendTime = realtime;
199 reliableMessagesSent++;
203 static void NetConn_SendMessageNext(netconn_t *conn)
205 unsigned int packetLen;
206 unsigned int dataLen;
208 unsigned int *header;
210 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
212 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
214 dataLen = conn->sendMessageLength;
219 dataLen = MAX_PACKETFRAGMENT;
223 packetLen = NET_HEADERSIZE + dataLen;
225 header = (void *)sendbuffer;
226 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
227 header[1] = BigLong(conn->sendSequence);
228 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
230 conn->sendSequence++;
231 conn->sendNext = false;
233 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
236 conn->lastSendTime = realtime;
241 static void NetConn_ReSendMessage(netconn_t *conn)
243 unsigned int packetLen;
244 unsigned int dataLen;
246 unsigned int *header;
248 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
250 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
252 dataLen = conn->sendMessageLength;
257 dataLen = MAX_PACKETFRAGMENT;
261 packetLen = NET_HEADERSIZE + dataLen;
263 header = (void *)sendbuffer;
264 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
265 header[1] = BigLong(conn->sendSequence - 1);
266 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
268 conn->sendNext = false;
270 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
273 conn->lastSendTime = realtime;
278 qboolean NetConn_CanSendMessage(netconn_t *conn)
280 return conn->canSend;
283 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
289 if (data->cursize == 0)
290 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
292 if (data->cursize > MAX_DATAGRAM)
293 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
296 packetLen = NET_HEADERSIZE + data->cursize;
298 header = (void *)sendbuffer;
299 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
300 header[1] = BigLong(conn->unreliableSendSequence);
301 memcpy(sendbuffer + 8, data->data, data->cursize);
303 conn->unreliableSendSequence++;
305 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
309 unreliableMessagesSent++;
313 void NetConn_CloseClientPorts(void)
315 for (;cl_numsockets > 0;cl_numsockets--)
316 if (cl_sockets[cl_numsockets - 1])
317 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
320 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
322 lhnetaddress_t address;
324 char addressstring2[1024];
325 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
327 if ((s = LHNET_OpenSocket_Connectionless(&address)))
329 cl_sockets[cl_numsockets++] = s;
330 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
331 Con_Printf("Client opened a socket on address %s\n", addressstring2);
335 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
336 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
340 Con_Printf("Client unable to parse address %s\n", addressstring);
343 void NetConn_OpenClientPorts(void)
346 NetConn_CloseClientPorts();
347 port = bound(0, cl_netport.integer, 65535);
348 if (cl_netport.integer != port)
349 Cvar_SetValueQuick(&cl_netport, port);
350 Con_Printf("Client using port %i\n", port);
351 NetConn_OpenClientPort("local", port);
352 NetConn_OpenClientPort(cl_netaddress.string, port);
353 NetConn_OpenClientPort(cl_netaddress_ipv6.string, port);
356 void NetConn_CloseServerPorts(void)
358 for (;sv_numsockets > 0;sv_numsockets--)
359 if (sv_sockets[sv_numsockets - 1])
360 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
363 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
365 lhnetaddress_t address;
367 char addressstring2[1024];
368 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
370 if ((s = LHNET_OpenSocket_Connectionless(&address)))
372 sv_sockets[sv_numsockets++] = s;
373 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
374 Con_Printf("Server listening on address %s\n", addressstring2);
378 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
379 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
383 Con_Printf("Server unable to parse address %s\n", addressstring);
386 void NetConn_OpenServerPorts(int opennetports)
389 NetConn_CloseServerPorts();
390 port = bound(0, sv_netport.integer, 65535);
393 Con_Printf("Server using port %i\n", port);
394 if (sv_netport.integer != port)
395 Cvar_SetValueQuick(&sv_netport, port);
396 if (cls.state != ca_dedicated)
397 NetConn_OpenServerPort("local", port);
400 NetConn_OpenServerPort(sv_netaddress.string, port);
401 NetConn_OpenServerPort(sv_netaddress_ipv6.string, port);
403 if (sv_numsockets == 0)
404 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
407 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
409 int i, a = LHNETADDRESS_GetAddressType(address);
410 for (i = 0;i < cl_numsockets;i++)
411 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
412 return cl_sockets[i];
416 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
418 int i, a = LHNETADDRESS_GetAddressType(address);
419 for (i = 0;i < sv_numsockets;i++)
420 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
421 return sv_sockets[i];
425 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
428 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
429 conn->mysocket = mysocket;
430 conn->peeraddress = *peeraddress;
431 conn->canSend = true;
432 conn->connecttime = realtime;
433 conn->lastMessageTime = realtime;
434 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
435 // reduce effectiveness of connection request floods
436 conn->timeout = realtime + net_connecttimeout.value;
437 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
438 conn->next = netconn_list;
443 void NetConn_Close(netconn_t *conn)
446 // remove connection from list
447 if (conn == netconn_list)
448 netconn_list = conn->next;
451 for (c = netconn_list;c;c = c->next)
455 c->next = conn->next;
459 // not found in list, we'll avoid crashing here...
467 static int clientport = -1;
468 static int clientport2 = -1;
469 static int hostport = -1;
470 static void NetConn_UpdateServerStuff(void)
472 if (clientport2 != cl_netport.integer)
474 clientport2 = cl_netport.integer;
475 if (cls.state == ca_connected)
476 Con_Printf("Changing \"cl_port\" will not take effect until you reconnect.\n");
478 if (cls.state != ca_dedicated)
480 if (cls.state == ca_disconnected && clientport != cl_netport.integer)
482 clientport = cl_netport.integer;
483 NetConn_CloseClientPorts();
485 if (cl_numsockets == 0)
486 NetConn_OpenClientPorts();
489 if (hostport != sv_netport.integer)
491 hostport = sv_netport.integer;
493 Con_Printf("Changing \"port\" will not take effect until \"map\" command is executed.\n");
497 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
501 unsigned int sequence;
505 length = BigLong(((int *)data)[0]);
506 flags = length & ~NETFLAG_LENGTH_MASK;
507 length &= NETFLAG_LENGTH_MASK;
508 // control packets were already handled
509 if (!(flags & NETFLAG_CTL))
511 sequence = BigLong(((int *)data)[1]);
515 if (flags & NETFLAG_UNRELIABLE)
517 if (sequence >= conn->unreliableReceiveSequence)
519 if (sequence > conn->unreliableReceiveSequence)
521 count = sequence - conn->unreliableReceiveSequence;
522 droppedDatagrams += count;
523 Con_DPrintf("Dropped %u datagram(s)\n", count);
525 conn->unreliableReceiveSequence = sequence + 1;
526 conn->lastMessageTime = realtime;
527 conn->timeout = realtime + net_messagetimeout.value;
528 unreliableMessagesReceived++;
531 SZ_Clear(&net_message);
532 SZ_Write(&net_message, data, length);
538 Con_DPrintf("Got a stale datagram\n");
541 else if (flags & NETFLAG_ACK)
543 if (sequence == (conn->sendSequence - 1))
545 if (sequence == conn->ackSequence)
548 if (conn->ackSequence != conn->sendSequence)
549 Con_DPrintf("ack sequencing error\n");
550 conn->lastMessageTime = realtime;
551 conn->timeout = realtime + net_messagetimeout.value;
552 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
553 if (conn->sendMessageLength > 0)
555 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
556 conn->sendNext = true;
557 NetConn_SendMessageNext(conn);
561 conn->sendMessageLength = 0;
562 conn->canSend = true;
566 Con_DPrintf("Duplicate ACK received\n");
569 Con_DPrintf("Stale ACK received\n");
572 else if (flags & NETFLAG_DATA)
574 unsigned int temppacket[2];
575 temppacket[0] = BigLong(8 | NETFLAG_ACK);
576 temppacket[1] = BigLong(sequence);
577 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
578 if (sequence == conn->receiveSequence)
580 conn->lastMessageTime = realtime;
581 conn->timeout = realtime + net_messagetimeout.value;
582 conn->receiveSequence++;
583 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
584 conn->receiveMessageLength += length;
585 if (flags & NETFLAG_EOM)
587 reliableMessagesReceived++;
588 length = conn->receiveMessageLength;
589 conn->receiveMessageLength = 0;
592 SZ_Clear(&net_message);
593 SZ_Write(&net_message, conn->receiveMessage, length);
600 receivedDuplicateCount++;
608 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
610 cls.netcon = NetConn_Open(mysocket, peeraddress);
611 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
614 cls.connect_trying = false;
615 cls.demonum = -1; // not in the demo loop now
616 cls.state = ca_connected;
617 cls.signon = 0; // need all the signon messages before playing
622 int NetConn_IsLocalGame(void)
624 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
632 lhnetaddress_t peeraddress;
634 pingcache[HOSTCACHESIZE];
636 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
639 lhnetaddress_t svaddress;
641 char *string, addressstring2[128], cname[128], ipstring[32];
642 char stringbuf[16384];
644 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
646 // received a command string - strip off the packaging and put it
647 // into our string buffer with NULL termination
650 length = min(length, (int)sizeof(stringbuf) - 1);
651 memcpy(stringbuf, data, length);
652 stringbuf[length] = 0;
655 if (developer.integer)
657 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
658 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
659 Com_HexDumpToConsole(data, length);
662 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
664 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
665 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
666 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
669 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
671 NetConn_ConnectionEstablished(mysocket, peeraddress);
674 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
676 cls.connect_trying = false;
678 length = max(length - 7, (int)sizeof(m_return_reason) - 1);
679 memcpy(m_return_reason, string, length);
680 m_return_reason[length] = 0;
681 Con_Printf("%s\n", m_return_reason);
684 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
686 int i, j, c, n, users, maxusers;
687 char game[32], mod[32], map[32], name[128];
691 // hostcache only uses text addresses
692 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
693 // search the cache for this server
694 for (n = 0; n < hostCacheCount; n++)
695 if (!strcmp(cname, hostcache[n].cname))
697 // add it or update it
698 if (n == hostCacheCount)
700 // if cache is full replace highest ping server (the list is
701 // kept sorted so this is always the last, and if this server
702 // is good it will be sorted into an early part of the list)
703 if (hostCacheCount >= HOSTCACHESIZE)
704 n = hostCacheCount - 1;
708 if ((s = SearchInfostring(string, "gamename" )) != NULL) strncpy(game, s, sizeof(game) - 1);else game[0] = 0;
709 if ((s = SearchInfostring(string, "modname" )) != NULL) strncpy(mod , s, sizeof(mod ) - 1);else mod[0] = 0;
710 if ((s = SearchInfostring(string, "mapname" )) != NULL) strncpy(map , s, sizeof(map ) - 1);else map[0] = 0;
711 if ((s = SearchInfostring(string, "hostname" )) != NULL) strncpy(name, s, sizeof(name) - 1);else name[0] = 0;
712 if ((s = SearchInfostring(string, "protocol" )) != NULL) c = atoi(s);else c = -1;
713 if ((s = SearchInfostring(string, "clients" )) != NULL) users = atoi(s);else users = 0;
714 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) maxusers = atoi(s);else maxusers = 0;
716 for (i = 0;i < HOSTCACHESIZE;i++)
717 if (!LHNETADDRESS_Compare(peeraddress, &pingcache[i].peeraddress))
718 pingtime = (int)(realtime - pingcache[i].senttime);
719 pingtime = bound(0, pingtime, 9999);
720 memset(&hostcache[n], 0, sizeof(hostcache[n]));
721 // store the data the engine cares about (address and ping)
722 strcpy(hostcache[n].cname, cname);
723 hostcache[n].ping = pingtime;
724 // build description strings for the things users care about
725 snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, c != NET_PROTOCOL_VERSION ? '*' : ' ', users, maxusers, name);
726 snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", cname, game, mod, map);
727 // if ping is especially high, display it as such
730 // orange numbers (lower block)
731 for (i = 0;i < 5;i++)
732 if (hostcache[n].line1[i] != ' ')
733 hostcache[n].line1[i] += 128;
735 else if (pingtime >= 200)
737 // yellow numbers (in upper block)
738 for (i = 0;i < 5;i++)
739 if (hostcache[n].line1[i] != ' ')
740 hostcache[n].line1[i] -= 30;
742 // if not in the slist menu we should print the server to console
743 if (m_state != m_slist)
744 Con_Printf("%s\n%s\n", hostcache[n].line1, hostcache[n].line2);
745 // and finally, re-sort the list
746 for (i = 0;i < hostCacheCount;i++)
748 for (j = i + 1;j < hostCacheCount;j++)
750 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
751 if (hostcache[i].ping > hostcache[j].ping)
753 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
754 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
755 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
761 if (!strncmp(string, "getserversResponse\\", 19) && hostCacheCount < HOSTCACHESIZE)
765 // Extract the IP addresses
768 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
770 sprintf(ipstring, "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
771 if (developer.integer)
772 Con_Printf("Requesting info from server %s\n", ipstring);
773 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
774 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
775 // replace oldest or matching entry in ping cache
776 // we scan this later when getting a reply to see how long it took
779 for (i = 0;i < HOSTCACHESIZE;i++)
781 if (!LHNETADDRESS_Compare(&svaddress, &pingcache[i].peeraddress))
786 if (besttime > pingcache[i].senttime)
788 besttime = pingcache[i].senttime;
790 // if ping cache isn't full yet we can skip out early
795 pingcache[best].peeraddress = svaddress;
796 pingcache[best].senttime = realtime;
797 // move on to next address in packet
804 if (!strncmp(string, "ping", 4))
806 if (developer.integer)
807 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
808 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
811 if (!strncmp(string, "ack", 3))
814 // we may not have liked the packet, but it was a command packet, so
815 // we're done processing this packet now
818 // netquake control packets, supported for compatibility only
819 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
824 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
828 if (developer.integer)
829 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
830 if (cls.connect_trying)
832 lhnetaddress_t clientportaddress;
833 clientportaddress = *peeraddress;
836 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
839 LHNETADDRESS_SetPort(&clientportaddress, port);
841 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
845 if (developer.integer)
846 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
847 Con_Printf("%s\n", data);
848 strncpy(m_return_reason, data, sizeof(m_return_reason) - 1);
851 case CCREP_SERVER_INFO:
852 if (developer.integer)
853 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
854 if (cls.state != ca_dedicated)
856 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
857 // string we just ignore it and keep the real address
859 // hostcache only uses text addresses
860 cname = UDP_AddrToString(readaddr);
861 // search the cache for this server
862 for (n = 0; n < hostCacheCount; n++)
863 if (!strcmp(cname, hostcache[n].cname))
866 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
869 memset(&hostcache[n], 0, sizeof(hostcache[n]));
870 strcpy(hostcache[n].name, MSG_ReadString());
871 strcpy(hostcache[n].map, MSG_ReadString());
872 hostcache[n].users = MSG_ReadByte();
873 hostcache[n].maxusers = MSG_ReadByte();
875 if (c != NET_PROTOCOL_VERSION)
877 strncpy(hostcache[n].cname, hostcache[n].name, sizeof(hostcache[n].cname) - 1);
878 hostcache[n].cname[sizeof(hostcache[n].cname) - 1] = 0;
879 strcpy(hostcache[n].name, "*");
880 strncat(hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name) - 1);
881 hostcache[n].name[sizeof(hostcache[n].name) - 1] = 0;
883 strcpy(hostcache[n].cname, cname);
887 case CCREP_PLAYER_INFO:
888 // we got a CCREP_PLAYER_INFO??
889 //if (developer.integer)
890 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
892 case CCREP_RULE_INFO:
893 // we got a CCREP_RULE_INFO??
894 //if (developer.integer)
895 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
901 // we may not have liked the packet, but it was a valid control
902 // packet, so we're done processing this packet now
906 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)
907 CL_ParseServerMessage();
911 void NetConn_ClientFrame(void)
914 lhnetaddress_t peeraddress;
916 NetConn_UpdateServerStuff();
917 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
919 if (cls.connect_remainingtries == 0)
921 cls.connect_trying = false;
922 Host_Error("Connect failed\n");
925 if (cls.connect_nextsendtime)
926 Con_Printf("Still trying...\n");
928 Con_Printf("Trying...\n");
929 cls.connect_nextsendtime = realtime + 1;
930 cls.connect_remainingtries--;
931 // try challenge first (newer server)
932 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
933 // then try netquake as a fallback (old server, or netquake)
934 SZ_Clear(&net_message);
935 // save space for the header, filled in later
936 MSG_WriteLong(&net_message, 0);
937 MSG_WriteByte(&net_message, CCREQ_CONNECT);
938 MSG_WriteString(&net_message, "QUAKE");
939 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
940 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
941 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
942 SZ_Clear(&net_message);
944 for (i = 0;i < cl_numsockets;i++)
945 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
946 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
947 if (cls.netcon && realtime > cls.netcon->timeout)
949 Con_Printf("Connection timed out\n");
952 for (conn = netconn_list;conn;conn = conn->next)
953 NetConn_ReSendMessage(conn);
956 #define MAX_CHALLENGES 128
959 lhnetaddress_t address;
963 challenge[MAX_CHALLENGES];
965 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
969 for (i = 0;i < bufferlength - 1;i++)
973 c = rand () % (127 - 33) + 33;
974 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
980 extern void SV_ConnectClient(int clientnum, netconn_t *netconnection);
981 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
983 int i, n, ret, clientnum, responselength, best;
987 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
991 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
993 // received a command string - strip off the packaging and put it
994 // into our string buffer with NULL termination
997 length = min(length, (int)sizeof(stringbuf) - 1);
998 memcpy(stringbuf, data, length);
999 stringbuf[length] = 0;
1002 if (developer.integer)
1004 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1005 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1006 Com_HexDumpToConsole(data, length);
1009 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1011 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1013 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1015 if (besttime > challenge[i].time)
1016 besttime = challenge[best = i].time;
1018 // if we did not find an exact match, choose the oldest and
1019 // update address and string
1020 if (i == MAX_CHALLENGES)
1023 challenge[i].address = *peeraddress;
1024 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1026 challenge[i].time = realtime;
1027 // send the challenge
1028 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1031 if (length > 8 && !memcmp(string, "connect\\", 8))
1035 if ((s = SearchInfostring(string, "challenge")))
1037 // validate the challenge
1038 for (i = 0;i < MAX_CHALLENGES;i++)
1039 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1041 if (i < MAX_CHALLENGES)
1043 // check engine protocol
1044 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1046 if (developer.integer)
1047 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1048 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1052 // see if this is a duplicate connection request
1053 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1054 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1056 if (clientnum < svs.maxclients)
1058 // duplicate connection request
1059 if (realtime - client->netconnection->connecttime < 2.0)
1061 // client is still trying to connect,
1062 // so we send a duplicate reply
1063 if (developer.integer)
1064 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1065 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1067 // only kick if old connection seems dead
1068 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1070 // kick off connection and await retry
1071 client->deadsocket = true;
1076 // this is a new client, find a slot
1077 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1078 if (!client->active)
1080 if (clientnum < svs.maxclients)
1082 // prepare the client struct
1083 if ((client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_clients_mempool)))
1085 if ((conn = NetConn_Open(mysocket, peeraddress)))
1087 // allocated connection
1088 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1089 if (developer.integer)
1090 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1091 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1092 // now set up the client
1093 SV_ConnectClient(clientnum, conn);
1094 NetConn_Heartbeat(1);
1097 EntityFrame4_FreeDatabase(client->entitydatabase4);
1103 if (developer.integer)
1104 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1105 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1113 if (length >= 7 && !memcmp(string, "getinfo", 7))
1115 const char *challenge = NULL;
1116 // If there was a challenge in the getinfo message
1117 if (length > 8 && string[7] == ' ')
1118 challenge = string + 8;
1119 for (i = 0, n = 0;i < svs.maxclients;i++)
1120 if (svs.clients[i].active)
1122 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1123 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1124 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1125 gamename, com_modname, svs.maxclients, n,
1126 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1127 // does it fit in the buffer?
1128 if (responselength < (int)sizeof(response))
1130 if (developer.integer)
1131 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1132 NetConn_WriteString(mysocket, response, peeraddress);
1137 if (!strncmp(string, "ping", 4))
1139 if (developer.integer)
1140 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1141 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1144 if (!strncmp(string, "ack", 3))
1147 // we may not have liked the packet, but it was a command packet, so
1148 // we're done processing this packet now
1151 // LordHavoc: disabled netquake control packet support in server
1155 // netquake control packets, supported for compatibility only
1156 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1161 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1165 //if (developer.integer)
1166 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1167 if (length >= (int)strlen("QUAKE") + 1 + 1)
1169 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1171 if (developer.integer)
1172 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1173 SZ_Clear(&net_message);
1174 // save space for the header, filled in later
1175 MSG_WriteLong(&net_message, 0);
1176 MSG_WriteByte(&net_message, CCREP_REJECT);
1177 MSG_WriteString(&net_message, "Incompatible version.\n");
1178 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1179 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1180 SZ_Clear(&net_message);
1184 // see if this is a duplicate connection request
1185 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1186 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1188 if (clientnum < svs.maxclients)
1190 // duplicate connection request
1191 if (realtime - client->netconnection->connecttime < 2.0)
1193 // client is still trying to connect,
1194 // so we send a duplicate reply
1195 if (developer.integer)
1196 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1197 SZ_Clear(&net_message);
1198 // save space for the header, filled in later
1199 MSG_WriteLong(&net_message, 0);
1200 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1201 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1202 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1203 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1204 SZ_Clear(&net_message);
1206 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1208 // the old client hasn't sent us anything
1209 // in quite a while, so kick off and let
1210 // the retry take care of it...
1211 client->deadsocket = true;
1216 // this is a new client, find a slot
1217 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1218 if (!client->active)
1220 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1222 // connect to the client
1223 // everything is allocated, just fill in the details
1224 strcpy(conn->address, addressstring2);
1225 if (developer.integer)
1226 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1227 // send back the info about the server connection
1228 SZ_Clear(&net_message);
1229 // save space for the header, filled in later
1230 MSG_WriteLong(&net_message, 0);
1231 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1232 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1233 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1234 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1235 SZ_Clear(&net_message);
1236 // now set up the client struct
1237 SV_ConnectClient(clientnum, conn);
1238 NetConn_Heartbeat(1);
1242 //if (developer.integer)
1243 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1244 // no room; try to let player know
1245 SZ_Clear(&net_message);
1246 // save space for the header, filled in later
1247 MSG_WriteLong(&net_message, 0);
1248 MSG_WriteByte(&net_message, CCREP_REJECT);
1249 MSG_WriteString(&net_message, "Server is full.\n");
1250 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1251 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1252 SZ_Clear(&net_message);
1259 case CCREQ_SERVER_INFO:
1260 if (developer.integer)
1261 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1262 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1264 if (developer.integer)
1265 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1266 SZ_Clear(&net_message);
1267 // save space for the header, filled in later
1268 MSG_WriteLong(&net_message, 0);
1269 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1270 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1271 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1272 MSG_WriteString(&net_message, hostname.string);
1273 MSG_WriteString(&net_message, sv.name);
1274 MSG_WriteByte(&net_message, net_activeconnections);
1275 MSG_WriteByte(&net_message, svs.maxclients);
1276 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1277 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1278 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1279 SZ_Clear(&net_message);
1282 case CCREQ_PLAYER_INFO:
1283 if (developer.integer)
1284 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1287 int playerNumber, activeNumber, clientNumber;
1290 playerNumber = MSG_ReadByte();
1292 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1293 if (client->active && ++activeNumber == playerNumber)
1295 if (clientNumber != svs.maxclients)
1297 SZ_Clear(&net_message);
1298 // save space for the header, filled in later
1299 MSG_WriteLong(&net_message, 0);
1300 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1301 MSG_WriteByte(&net_message, playerNumber);
1302 MSG_WriteString(&net_message, client->name);
1303 MSG_WriteLong(&net_message, client->colors);
1304 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1305 MSG_WriteLong(&net_message, (int)(realtime - client->netconnection->connecttime));
1306 MSG_WriteString(&net_message, client->netconnection->address);
1307 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1308 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1309 SZ_Clear(&net_message);
1313 case CCREQ_RULE_INFO:
1314 if (developer.integer)
1315 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1321 // find the search start location
1322 prevCvarName = MSG_ReadString();
1323 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1325 // send the response
1326 SZ_Clear(&net_message);
1327 // save space for the header, filled in later
1328 MSG_WriteLong(&net_message, 0);
1329 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1332 MSG_WriteString(&net_message, var->name);
1333 MSG_WriteString(&net_message, var->string);
1335 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1336 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1337 SZ_Clear(&net_message);
1344 // we may not have liked the packet, but it was a valid control
1345 // packet, so we're done processing this packet now
1350 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1352 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1354 sv_player = host_client->edict;
1355 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1356 SV_ReadClientMessage();
1364 void NetConn_ServerFrame(void)
1367 lhnetaddress_t peeraddress;
1369 NetConn_UpdateServerStuff();
1370 for (i = 0;i < sv_numsockets;i++)
1371 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1372 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1373 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1375 if (host_client->netconnection && realtime > host_client->netconnection->timeout)
1377 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1378 sv_player = host_client->edict;
1379 SV_DropClient(false);
1382 for (conn = netconn_list;conn;conn = conn->next)
1383 NetConn_ReSendMessage(conn);
1386 void NetConn_QueryMasters(void)
1390 lhnetaddress_t masteraddress;
1393 if (hostCacheCount >= HOSTCACHESIZE)
1396 for (i = 0;i < cl_numsockets;i++)
1403 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1405 SZ_Clear(&net_message);
1406 // save space for the header, filled in later
1407 MSG_WriteLong(&net_message, 0);
1408 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1409 MSG_WriteString(&net_message, "QUAKE");
1410 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1411 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1412 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1413 SZ_Clear(&net_message);
1417 // build the getservers
1418 snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1421 for (masternum = 0;sv_masters[masternum].name;masternum++)
1422 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1423 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1428 void NetConn_Heartbeat(int priority)
1430 lhnetaddress_t masteraddress;
1432 lhnetsocket_t *mysocket;
1434 // if it's a state change (client connected), limit next heartbeat to no
1435 // more than 30 sec in the future
1436 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1437 nextheartbeattime = realtime + 30.0;
1439 // limit heartbeatperiod to 30 to 270 second range,
1440 // lower limit is to avoid abusing master servers with excess traffic,
1441 // upper limit is to avoid timing out on the master server (which uses
1443 if (sv_heartbeatperiod.value < 30)
1444 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1445 if (sv_heartbeatperiod.value > 270)
1446 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1448 // make advertising optional and don't advertise singleplayer games, and
1449 // only send a heartbeat as often as the admin wants
1450 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1452 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1453 for (masternum = 0;sv_masters[masternum].name;masternum++)
1454 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1455 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1459 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1462 qbyte sent[MAX_SCOREBOARD];
1464 memset(sent, 0, sizeof(sent));
1466 // simultaneously wait for the first CanSendMessage and send the message,
1467 // then wait for a second CanSendMessage (verifying it was received), or
1468 // the client drops and is no longer counted
1469 // the loop aborts when either it runs out of clients to send to, or a
1471 blocktime += Sys_DoubleTime();
1475 NetConn_ClientFrame();
1476 NetConn_ServerFrame();
1477 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1479 if (host_client->netconnection)
1481 if (NetConn_CanSendMessage(host_client->netconnection))
1484 NetConn_SendReliableMessage(host_client->netconnection, data);
1487 if (!NetConn_CanSendMessage(host_client->netconnection))
1492 while (count && Sys_DoubleTime() < blocktime);
1496 static void Net_Heartbeat_f(void)
1498 NetConn_Heartbeat(2);
1501 void PrintStats(netconn_t *conn)
1503 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1506 void Net_Stats_f(void)
1509 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1510 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1511 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1512 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1513 Con_Printf("packetsSent = %i\n", packetsSent);
1514 Con_Printf("packetsReSent = %i\n", packetsReSent);
1515 Con_Printf("packetsReceived = %i\n", packetsReceived);
1516 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1517 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1518 Con_Printf("connections =\n");
1519 for (conn = netconn_list;conn;conn = conn->next)
1523 void Net_Slist_f(void)
1526 memset(&pingcache, 0, sizeof(pingcache));
1527 if (m_state != m_slist)
1528 Con_Printf("Sending requests to master servers\n");
1529 NetConn_QueryMasters();
1530 if (m_state != m_slist)
1531 Con_Printf("Listening for replies...\n");
1534 void NetConn_Init(void)
1537 lhnetaddress_t tempaddress;
1538 netconn_mempool = Mem_AllocPool("Networking");
1539 Cmd_AddCommand("net_stats", Net_Stats_f);
1540 Cmd_AddCommand("net_slist", Net_Slist_f);
1541 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1542 Cvar_RegisterVariable(&net_messagetimeout);
1543 Cvar_RegisterVariable(&net_messagerejointimeout);
1544 Cvar_RegisterVariable(&net_connecttimeout);
1545 Cvar_RegisterVariable(&cl_fakelocalping_min);
1546 Cvar_RegisterVariable(&cl_fakelocalping_max);
1547 Cvar_RegisterVariable(&cl_fakepacketloss_receive);
1548 Cvar_RegisterVariable(&cl_fakepacketloss_send);
1549 Cvar_RegisterVariable(&sv_fakepacketloss_receive);
1550 Cvar_RegisterVariable(&sv_fakepacketloss_send);
1551 Cvar_RegisterVariable(&hostname);
1552 Cvar_RegisterVariable(&developer_networking);
1553 Cvar_RegisterVariable(&cl_netport);
1554 Cvar_RegisterVariable(&cl_netaddress);
1555 Cvar_RegisterVariable(&cl_netaddress_ipv6);
1556 Cvar_RegisterVariable(&sv_netport);
1557 Cvar_RegisterVariable(&sv_netaddress);
1558 Cvar_RegisterVariable(&sv_netaddress_ipv6);
1559 Cvar_RegisterVariable(&sv_public);
1560 Cvar_RegisterVariable(&sv_heartbeatperiod);
1561 for (i = 0;sv_masters[i].name;i++)
1562 Cvar_RegisterVariable(&sv_masters[i]);
1563 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1565 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1567 Con_Printf("-ip option used, setting cl_netaddress and sv_netaddress to address \"%s\"\n");
1568 Cvar_SetQuick(&cl_netaddress, com_argv[i + 1]);
1569 Cvar_SetQuick(&sv_netaddress, com_argv[i + 1]);
1572 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1574 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1576 i = atoi(com_argv[i + 1]);
1577 if (i >= 0 && i < 65536)
1579 Con_Printf("-port option used, setting port cvar to %i\n", i);
1580 Cvar_SetValueQuick(&sv_netport, i);
1583 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1587 memset(&pingcache, 0, sizeof(pingcache));
1588 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1592 void NetConn_Shutdown(void)
1594 NetConn_CloseClientPorts();
1595 NetConn_CloseServerPorts();