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 // FIXME: resolve DNS on masters whenever their value changes and cache it (to avoid major delays in active servers when they heartbeat)
32 static cvar_t sv_masters [] =
34 {CVAR_SAVE, "sv_master1", ""},
35 {CVAR_SAVE, "sv_master2", ""},
36 {CVAR_SAVE, "sv_master3", ""},
37 {CVAR_SAVE, "sv_master4", ""},
38 {0, "sv_masterextra1", "69.59.212.88"}, // ghdigital.com
39 {0, "sv_masterextra2", "66.169.205.13"}, // dpmaster.deathmask.net
43 static double nextheartbeattime = 0;
45 sizebuf_t net_message;
47 cvar_t net_messagetimeout = {0, "net_messagetimeout","300"};
48 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10"};
49 cvar_t net_connecttimeout = {0, "net_connecttimeout","10"};
50 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED"};
51 cvar_t developer_networking = {0, "developer_networking", "0"};
53 cvar_t cl_netlocalping = {0, "cl_netlocalping","0"};
54 static cvar_t cl_netpacketloss = {0, "cl_netpacketloss","0"};
57 /* statistic counters */
58 static int packetsSent = 0;
59 static int packetsReSent = 0;
60 static int packetsReceived = 0;
61 static int receivedDuplicateCount = 0;
62 static int droppedDatagrams = 0;
64 static int unreliableMessagesSent = 0;
65 static int unreliableMessagesReceived = 0;
66 static int reliableMessagesSent = 0;
67 static int reliableMessagesReceived = 0;
69 double masterquerytime = -1000;
70 int masterquerycount = 0;
71 int masterreplycount = 0;
72 int serverquerycount = 0;
73 int serverreplycount = 0;
75 int hostCacheCount = 0;
76 hostcache_t hostcache[HOSTCACHESIZE];
78 static qbyte sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
79 static qbyte readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
82 lhnetsocket_t *cl_sockets[16];
84 lhnetsocket_t *sv_sockets[16];
86 netconn_t *netconn_list = NULL;
87 mempool_t *netconn_mempool = NULL;
89 cvar_t cl_netport = {0, "cl_port", "0"};
90 cvar_t sv_netport = {0, "port", "26000"};
91 cvar_t net_address = {0, "net_address", "0.0.0.0"};
92 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]"};
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_netpacketloss.integer)
99 for (i = 0;i < cl_numsockets;i++)
100 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
102 if (developer_networking.integer && length != 0)
104 char addressstring[128], addressstring2[128];
105 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
108 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
109 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
110 Com_HexDumpToConsole(data, length);
113 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
118 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
122 if (cl_netpacketloss.integer)
123 for (i = 0;i < cl_numsockets;i++)
124 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
126 ret = LHNET_Write(mysocket, data, length, peeraddress);
127 if (developer_networking.integer)
129 char addressstring[128], addressstring2[128];
130 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
131 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
132 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
133 Com_HexDumpToConsole(data, length);
138 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
140 // note this does not include the trailing NULL because we add that in the parser
141 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
144 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
146 unsigned int packetLen;
147 unsigned int dataLen;
149 unsigned int *header;
152 if (data->cursize == 0)
153 Sys_Error("Datagram_SendMessage: zero length message\n");
155 if (data->cursize > (int)sizeof(conn->sendMessage))
156 Sys_Error("Datagram_SendMessage: message too big (%u > %u)\n", data->cursize, sizeof(conn->sendMessage));
158 if (conn->canSend == false)
159 Sys_Error("SendMessage: called with canSend == false\n");
162 memcpy(conn->sendMessage, data->data, data->cursize);
163 conn->sendMessageLength = data->cursize;
165 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
167 dataLen = conn->sendMessageLength;
172 dataLen = MAX_PACKETFRAGMENT;
176 packetLen = NET_HEADERSIZE + dataLen;
178 header = (void *)sendbuffer;
179 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
180 header[1] = BigLong(conn->sendSequence);
181 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
183 conn->sendSequence++;
184 conn->canSend = false;
186 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
189 conn->lastSendTime = realtime;
191 reliableMessagesSent++;
195 static void NetConn_SendMessageNext(netconn_t *conn)
197 unsigned int packetLen;
198 unsigned int dataLen;
200 unsigned int *header;
202 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
204 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
206 dataLen = conn->sendMessageLength;
211 dataLen = MAX_PACKETFRAGMENT;
215 packetLen = NET_HEADERSIZE + dataLen;
217 header = (void *)sendbuffer;
218 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
219 header[1] = BigLong(conn->sendSequence);
220 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
222 conn->sendSequence++;
223 conn->sendNext = false;
225 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
228 conn->lastSendTime = realtime;
233 static void NetConn_ReSendMessage(netconn_t *conn)
235 unsigned int packetLen;
236 unsigned int dataLen;
238 unsigned int *header;
240 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
242 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
244 dataLen = conn->sendMessageLength;
249 dataLen = MAX_PACKETFRAGMENT;
253 packetLen = NET_HEADERSIZE + dataLen;
255 header = (void *)sendbuffer;
256 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
257 header[1] = BigLong(conn->sendSequence - 1);
258 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
260 conn->sendNext = false;
262 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
265 conn->lastSendTime = realtime;
270 qboolean NetConn_CanSendMessage(netconn_t *conn)
272 return conn->canSend;
275 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
280 packetLen = NET_HEADERSIZE + data->cursize;
283 if (data->cursize == 0)
284 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
286 if (packetLen > (int)sizeof(sendbuffer))
287 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
290 header = (void *)sendbuffer;
291 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
292 header[1] = BigLong(conn->unreliableSendSequence);
293 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
295 conn->unreliableSendSequence++;
297 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
301 unreliableMessagesSent++;
305 void NetConn_CloseClientPorts(void)
307 for (;cl_numsockets > 0;cl_numsockets--)
308 if (cl_sockets[cl_numsockets - 1])
309 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
312 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
314 lhnetaddress_t address;
316 char addressstring2[1024];
317 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
319 if ((s = LHNET_OpenSocket_Connectionless(&address)))
321 cl_sockets[cl_numsockets++] = s;
322 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
323 Con_Printf("Client opened a socket on address %s\n", addressstring2);
327 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
328 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
332 Con_Printf("Client unable to parse address %s\n", addressstring);
335 void NetConn_OpenClientPorts(void)
338 NetConn_CloseClientPorts();
339 port = bound(0, cl_netport.integer, 65535);
340 if (cl_netport.integer != port)
341 Cvar_SetValueQuick(&cl_netport, port);
342 Con_Printf("Client using port %i\n", port);
343 NetConn_OpenClientPort("local:2", 0);
344 NetConn_OpenClientPort(net_address.string, port);
345 //NetConn_OpenClientPort(net_address_ipv6.string, port);
348 void NetConn_CloseServerPorts(void)
350 for (;sv_numsockets > 0;sv_numsockets--)
351 if (sv_sockets[sv_numsockets - 1])
352 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
355 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
357 lhnetaddress_t address;
359 char addressstring2[1024];
360 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
362 if ((s = LHNET_OpenSocket_Connectionless(&address)))
364 sv_sockets[sv_numsockets++] = s;
365 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
366 Con_Printf("Server listening on address %s\n", addressstring2);
370 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
371 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
375 Con_Printf("Server unable to parse address %s\n", addressstring);
378 void NetConn_OpenServerPorts(int opennetports)
381 NetConn_CloseServerPorts();
382 port = bound(0, sv_netport.integer, 65535);
385 Con_Printf("Server using port %i\n", port);
386 if (sv_netport.integer != port)
387 Cvar_SetValueQuick(&sv_netport, port);
388 if (cls.state != ca_dedicated)
389 NetConn_OpenServerPort("local:1", 0);
392 NetConn_OpenServerPort(net_address.string, port);
393 //NetConn_OpenServerPort(net_address_ipv6.string, port);
395 if (sv_numsockets == 0)
396 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
399 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
401 int i, a = LHNETADDRESS_GetAddressType(address);
402 for (i = 0;i < cl_numsockets;i++)
403 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
404 return cl_sockets[i];
408 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
410 int i, a = LHNETADDRESS_GetAddressType(address);
411 for (i = 0;i < sv_numsockets;i++)
412 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
413 return sv_sockets[i];
417 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
420 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
421 conn->mysocket = mysocket;
422 conn->peeraddress = *peeraddress;
423 conn->canSend = true;
424 conn->lastMessageTime = realtime;
425 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
426 // reduce effectiveness of connection request floods
427 conn->timeout = realtime + net_connecttimeout.value;
428 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
429 conn->next = netconn_list;
434 void NetConn_Close(netconn_t *conn)
437 // remove connection from list
438 if (conn == netconn_list)
439 netconn_list = conn->next;
442 for (c = netconn_list;c;c = c->next)
446 c->next = conn->next;
450 // not found in list, we'll avoid crashing here...
458 static int clientport = -1;
459 static int clientport2 = -1;
460 static int hostport = -1;
461 static void NetConn_UpdateServerStuff(void)
463 if (cls.state != ca_dedicated)
465 if (clientport2 != cl_netport.integer)
467 clientport2 = cl_netport.integer;
468 if (cls.state == ca_connected)
469 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
471 if (cls.state == ca_disconnected && clientport != clientport2)
473 clientport = clientport2;
474 NetConn_CloseClientPorts();
476 if (cl_numsockets == 0)
477 NetConn_OpenClientPorts();
480 if (hostport != sv_netport.integer)
482 hostport = sv_netport.integer;
484 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
488 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
492 unsigned int sequence;
496 length = BigLong(((int *)data)[0]);
497 flags = length & ~NETFLAG_LENGTH_MASK;
498 length &= NETFLAG_LENGTH_MASK;
499 // control packets were already handled
500 if (!(flags & NETFLAG_CTL))
502 sequence = BigLong(((int *)data)[1]);
506 if (flags & NETFLAG_UNRELIABLE)
508 if (sequence >= conn->unreliableReceiveSequence)
510 if (sequence > conn->unreliableReceiveSequence)
512 count = sequence - conn->unreliableReceiveSequence;
513 droppedDatagrams += count;
514 Con_DPrintf("Dropped %u datagram(s)\n", count);
516 conn->unreliableReceiveSequence = sequence + 1;
517 conn->lastMessageTime = realtime;
518 conn->timeout = realtime + net_messagetimeout.value;
519 unreliableMessagesReceived++;
522 SZ_Clear(&net_message);
523 SZ_Write(&net_message, data, length);
529 Con_DPrint("Got a stale datagram\n");
532 else if (flags & NETFLAG_ACK)
534 if (sequence == (conn->sendSequence - 1))
536 if (sequence == conn->ackSequence)
539 if (conn->ackSequence != conn->sendSequence)
540 Con_DPrint("ack sequencing error\n");
541 conn->lastMessageTime = realtime;
542 conn->timeout = realtime + net_messagetimeout.value;
543 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
544 if (conn->sendMessageLength > 0)
546 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
547 conn->sendNext = true;
548 NetConn_SendMessageNext(conn);
552 conn->sendMessageLength = 0;
553 conn->canSend = true;
557 Con_DPrint("Duplicate ACK received\n");
560 Con_DPrint("Stale ACK received\n");
563 else if (flags & NETFLAG_DATA)
565 unsigned int temppacket[2];
566 temppacket[0] = BigLong(8 | NETFLAG_ACK);
567 temppacket[1] = BigLong(sequence);
568 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
569 if (sequence == conn->receiveSequence)
571 conn->lastMessageTime = realtime;
572 conn->timeout = realtime + net_messagetimeout.value;
573 conn->receiveSequence++;
574 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
575 conn->receiveMessageLength += length;
576 if (flags & NETFLAG_EOM)
578 reliableMessagesReceived++;
579 length = conn->receiveMessageLength;
580 conn->receiveMessageLength = 0;
583 SZ_Clear(&net_message);
584 SZ_Write(&net_message, conn->receiveMessage, length);
591 receivedDuplicateCount++;
599 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
601 cls.connect_trying = false;
602 M_Update_Return_Reason("");
603 // the connection request succeeded, stop current connection and set up a new connection
605 cls.netcon = NetConn_Open(mysocket, peeraddress);
606 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
609 cls.demonum = -1; // not in the demo loop now
610 cls.state = ca_connected;
611 cls.signon = 0; // need all the signon messages before playing
613 SCR_BeginLoadingPlaque();
616 int NetConn_IsLocalGame(void)
618 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
626 lhnetaddress_t peeraddress;
628 pingcache[HOSTCACHESIZE];
630 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
633 lhnetaddress_t svaddress;
635 char *string, addressstring2[128], cname[128], ipstring[32];
636 char stringbuf[16384];
638 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
640 // received a command string - strip off the packaging and put it
641 // into our string buffer with NULL termination
644 length = min(length, (int)sizeof(stringbuf) - 1);
645 memcpy(stringbuf, data, length);
646 stringbuf[length] = 0;
649 if (developer.integer)
651 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
652 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
653 Com_HexDumpToConsole(data, length);
656 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
658 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
659 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
660 M_Update_Return_Reason("Got challenge response");
661 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
664 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
666 M_Update_Return_Reason("Accepted");
667 NetConn_ConnectionEstablished(mysocket, peeraddress);
670 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
672 char rejectreason[32];
673 cls.connect_trying = false;
675 length = max(length - 7, (int)sizeof(rejectreason) - 1);
676 memcpy(rejectreason, string, length);
677 rejectreason[length] = 0;
678 M_Update_Return_Reason(rejectreason);
681 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
683 int i, j, c, n, users, maxusers;
684 char game[32], mod[32], map[32], name[128];
688 // hostcache only uses text addresses
689 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
690 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(game, s, sizeof (game));else game[0] = 0;
691 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(mod , s, sizeof (mod ));else mod[0] = 0;
692 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(map , s, sizeof (map ));else map[0] = 0;
693 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(name, s, sizeof (name));else name[0] = 0;
694 if ((s = SearchInfostring(string, "protocol" )) != NULL) c = atoi(s);else c = -1;
695 if ((s = SearchInfostring(string, "clients" )) != NULL) users = atoi(s);else users = 0;
696 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) maxusers = atoi(s);else maxusers = 0;
697 // search the cache for this server and update it
698 for (n = 0; n < hostCacheCount; n++)
700 if (!strcmp(cname, hostcache[n].cname))
702 if (hostcache[n].ping == 100000)
704 pingtime = (int)((realtime - hostcache[n].querytime) * 1000.0);
705 pingtime = bound(0, pingtime, 9999);
707 hostcache[n].ping = pingtime;
708 // build description strings for the things users care about
709 snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, c != NET_PROTOCOL_VERSION ? '*' : ' ', users, maxusers, name);
710 snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", cname, game, mod, map);
711 // if ping is especially high, display it as such
714 // orange numbers (lower block)
715 for (i = 0;i < 5;i++)
716 if (hostcache[n].line1[i] != ' ')
717 hostcache[n].line1[i] += 128;
719 else if (pingtime >= 200)
721 // yellow numbers (in upper block)
722 for (i = 0;i < 5;i++)
723 if (hostcache[n].line1[i] != ' ')
724 hostcache[n].line1[i] -= 30;
726 // if not in the slist menu we should print the server to console
727 if (m_state != m_slist)
728 Con_Printf("%s\n%s\n", hostcache[n].line1, hostcache[n].line2);
729 // and finally, re-sort the list
730 for (i = 0;i < hostCacheCount;i++)
732 for (j = i + 1;j < hostCacheCount;j++)
734 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
735 if (hostcache[i].ping > hostcache[j].ping)
737 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
738 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
739 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
748 if (!strncmp(string, "getserversResponse\\", 19) && hostCacheCount < HOSTCACHESIZE)
752 // Extract the IP addresses
756 if (m_state != m_slist)
757 Con_Print("received server list...\n");
758 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
760 snprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
761 if (developer.integer)
762 Con_Printf("Requesting info from server %s\n", ipstring);
763 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
764 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
767 // add to slist (hostCache)
768 // search the cache for this server
769 for (n = 0; n < hostCacheCount; n++)
770 if (!strcmp(ipstring, hostcache[n].cname))
772 // add it or update it
773 if (n == hostCacheCount)
775 // if cache is full replace highest ping server (the list is
776 // kept sorted so this is always the last, and if this server
777 // is good it will be sorted into an early part of the list)
778 if (hostCacheCount >= HOSTCACHESIZE)
779 n = hostCacheCount - 1;
786 memset(&hostcache[n], 0, sizeof(hostcache[n]));
787 // store the data the engine cares about (address and ping)
788 strlcpy (hostcache[n].cname, ipstring, sizeof (hostcache[n].cname));
789 hostcache[n].ping = 100000;
790 hostcache[n].querytime = realtime;
791 // build description strings for the things users care about
792 strlcpy (hostcache[n].line1, "?", sizeof (hostcache[n].line1));
793 strlcpy (hostcache[n].line2, ipstring, sizeof (hostcache[n].line2));
794 // if not in the slist menu we should print the server to console
795 if (m_state != m_slist)
796 Con_Printf("querying %s\n", ipstring);
797 // and finally, re-sort the list
798 for (i = 0;i < hostCacheCount;i++)
800 for (j = i + 1;j < hostCacheCount;j++)
802 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
803 if (hostcache[i].ping > hostcache[j].ping)
805 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
806 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
807 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
813 // move on to next address in packet
820 if (!strncmp(string, "ping", 4))
822 if (developer.integer)
823 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
824 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
827 if (!strncmp(string, "ack", 3))
830 // we may not have liked the packet, but it was a command packet, so
831 // we're done processing this packet now
834 // netquake control packets, supported for compatibility only
835 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
840 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
844 if (developer.integer)
845 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
846 if (cls.connect_trying)
848 lhnetaddress_t clientportaddress;
849 clientportaddress = *peeraddress;
852 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
855 LHNETADDRESS_SetPort(&clientportaddress, port);
857 M_Update_Return_Reason("Accepted");
858 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
862 if (developer.integer)
863 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
864 cls.connect_trying = false;
865 M_Update_Return_Reason(data);
868 case CCREP_SERVER_INFO:
869 if (developer.integer)
870 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
871 if (cls.state != ca_dedicated)
873 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
874 // string we just ignore it and keep the real address
876 // hostcache only uses text addresses
877 cname = UDP_AddrToString(readaddr);
878 // search the cache for this server
879 for (n = 0; n < hostCacheCount; n++)
880 if (!strcmp(cname, hostcache[n].cname))
883 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
886 memset(&hostcache[n], 0, sizeof(hostcache[n]));
887 strlcpy (hostcache[n].name, MSG_ReadString(), sizeof (hostcache[n].name));
888 strlcpy (hostcache[n].map, MSG_ReadString(), sizeof (hostcache[n].map));
889 hostcache[n].users = MSG_ReadByte();
890 hostcache[n].maxusers = MSG_ReadByte();
892 if (c != NET_PROTOCOL_VERSION)
894 strlcpy (hostcache[n].cname, hostcache[n].name, sizeof (hostcache[n].cname));
895 strcpy(hostcache[n].name, "*");
896 strlcat (hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name));
898 strlcpy (hostcache[n].cname, cname, sizeof (hostcache[n].cname));
902 case CCREP_PLAYER_INFO:
903 // we got a CCREP_PLAYER_INFO??
904 //if (developer.integer)
905 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
907 case CCREP_RULE_INFO:
908 // we got a CCREP_RULE_INFO??
909 //if (developer.integer)
910 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
916 // we may not have liked the packet, but it was a valid control
917 // packet, so we're done processing this packet now
921 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)
922 CL_ParseServerMessage();
926 void NetConn_ClientFrame(void)
929 lhnetaddress_t peeraddress;
931 NetConn_UpdateServerStuff();
932 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
934 if (cls.connect_remainingtries == 0)
936 cls.connect_trying = false;
937 M_Update_Return_Reason("Connect: Failed");
940 cls.connect_nextsendtime = realtime + 1;
941 cls.connect_remainingtries--;
942 // try challenge first (newer server)
943 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
944 // then try netquake as a fallback (old server, or netquake)
945 SZ_Clear(&net_message);
946 // save space for the header, filled in later
947 MSG_WriteLong(&net_message, 0);
948 MSG_WriteByte(&net_message, CCREQ_CONNECT);
949 MSG_WriteString(&net_message, "QUAKE");
950 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
951 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
952 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
953 SZ_Clear(&net_message);
955 for (i = 0;i < cl_numsockets;i++)
956 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
957 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
958 if (cls.netcon && realtime > cls.netcon->timeout)
960 Con_Print("Connection timed out\n");
962 Host_ShutdownServer (false);
964 for (conn = netconn_list;conn;conn = conn->next)
965 NetConn_ReSendMessage(conn);
968 #define MAX_CHALLENGES 128
971 lhnetaddress_t address;
975 challenge[MAX_CHALLENGES];
977 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
981 for (i = 0;i < bufferlength - 1;i++)
985 c = rand () % (127 - 33) + 33;
986 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
992 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
994 int i, n, ret, clientnum, responselength, best;
998 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1002 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1004 // received a command string - strip off the packaging and put it
1005 // into our string buffer with NULL termination
1008 length = min(length, (int)sizeof(stringbuf) - 1);
1009 memcpy(stringbuf, data, length);
1010 stringbuf[length] = 0;
1013 if (developer.integer)
1015 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1016 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1017 Com_HexDumpToConsole(data, length);
1020 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1022 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1024 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1026 if (besttime > challenge[i].time)
1027 besttime = challenge[best = i].time;
1029 // if we did not find an exact match, choose the oldest and
1030 // update address and string
1031 if (i == MAX_CHALLENGES)
1034 challenge[i].address = *peeraddress;
1035 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1037 challenge[i].time = realtime;
1038 // send the challenge
1039 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1042 if (length > 8 && !memcmp(string, "connect\\", 8))
1046 if ((s = SearchInfostring(string, "challenge")))
1048 // validate the challenge
1049 for (i = 0;i < MAX_CHALLENGES;i++)
1050 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1052 if (i < MAX_CHALLENGES)
1054 // check engine protocol
1055 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1057 if (developer.integer)
1058 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1059 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1063 // see if this is a duplicate connection request
1064 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1065 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1067 if (clientnum < svs.maxclients)
1069 // duplicate connection request
1070 if (realtime - client->connecttime < 2.0)
1072 // client is still trying to connect,
1073 // so we send a duplicate reply
1074 if (developer.integer)
1075 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1076 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1078 // only kick if old connection seems dead
1079 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1081 // kick off connection and await retry
1082 client->deadsocket = true;
1087 // this is a new client, find a slot
1088 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1089 if (!client->active)
1091 if (clientnum < svs.maxclients)
1093 // prepare the client struct
1094 if ((conn = NetConn_Open(mysocket, peeraddress)))
1096 // allocated connection
1097 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1098 if (developer.integer)
1099 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1100 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1101 // now set up the client
1102 SV_ConnectClient(clientnum, conn);
1103 NetConn_Heartbeat(1);
1109 if (developer.integer)
1110 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1111 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1119 if (length >= 7 && !memcmp(string, "getinfo", 7))
1121 const char *challenge = NULL;
1122 // If there was a challenge in the getinfo message
1123 if (length > 8 && string[7] == ' ')
1124 challenge = string + 8;
1125 for (i = 0, n = 0;i < svs.maxclients;i++)
1126 if (svs.clients[i].active)
1128 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1129 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1130 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1131 gamename, com_modname, svs.maxclients, n,
1132 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1133 // does it fit in the buffer?
1134 if (responselength < (int)sizeof(response))
1136 if (developer.integer)
1137 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1138 NetConn_WriteString(mysocket, response, peeraddress);
1143 if (!strncmp(string, "ping", 4))
1145 if (developer.integer)
1146 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1147 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1150 if (!strncmp(string, "ack", 3))
1153 // we may not have liked the packet, but it was a command packet, so
1154 // we're done processing this packet now
1157 // LordHavoc: disabled netquake control packet support in server
1161 // netquake control packets, supported for compatibility only
1162 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1167 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1171 //if (developer.integer)
1172 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1173 if (length >= (int)strlen("QUAKE") + 1 + 1)
1175 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1177 if (developer.integer)
1178 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1179 SZ_Clear(&net_message);
1180 // save space for the header, filled in later
1181 MSG_WriteLong(&net_message, 0);
1182 MSG_WriteByte(&net_message, CCREP_REJECT);
1183 MSG_WriteString(&net_message, "Incompatible version.\n");
1184 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1185 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1186 SZ_Clear(&net_message);
1190 // see if this is a duplicate connection request
1191 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1192 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1194 if (clientnum < svs.maxclients)
1196 // duplicate connection request
1197 if (realtime - client->connecttime < 2.0)
1199 // client is still trying to connect,
1200 // so we send a duplicate reply
1201 if (developer.integer)
1202 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1203 SZ_Clear(&net_message);
1204 // save space for the header, filled in later
1205 MSG_WriteLong(&net_message, 0);
1206 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1207 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1208 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1209 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1210 SZ_Clear(&net_message);
1212 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1214 // the old client hasn't sent us anything
1215 // in quite a while, so kick off and let
1216 // the retry take care of it...
1217 client->deadsocket = true;
1222 // this is a new client, find a slot
1223 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1224 if (!client->active)
1226 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1228 // connect to the client
1229 // everything is allocated, just fill in the details
1230 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1231 if (developer.integer)
1232 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1233 // send back the info about the server connection
1234 SZ_Clear(&net_message);
1235 // save space for the header, filled in later
1236 MSG_WriteLong(&net_message, 0);
1237 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1238 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1239 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1240 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1241 SZ_Clear(&net_message);
1242 // now set up the client struct
1243 SV_ConnectClient(clientnum, conn);
1244 NetConn_Heartbeat(1);
1248 //if (developer.integer)
1249 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1250 // no room; try to let player know
1251 SZ_Clear(&net_message);
1252 // save space for the header, filled in later
1253 MSG_WriteLong(&net_message, 0);
1254 MSG_WriteByte(&net_message, CCREP_REJECT);
1255 MSG_WriteString(&net_message, "Server is full.\n");
1256 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1257 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1258 SZ_Clear(&net_message);
1265 case CCREQ_SERVER_INFO:
1266 if (developer.integer)
1267 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1268 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1270 if (developer.integer)
1271 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1272 SZ_Clear(&net_message);
1273 // save space for the header, filled in later
1274 MSG_WriteLong(&net_message, 0);
1275 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1276 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1277 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1278 MSG_WriteString(&net_message, hostname.string);
1279 MSG_WriteString(&net_message, sv.name);
1280 MSG_WriteByte(&net_message, net_activeconnections);
1281 MSG_WriteByte(&net_message, svs.maxclients);
1282 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1283 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1284 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1285 SZ_Clear(&net_message);
1288 case CCREQ_PLAYER_INFO:
1289 if (developer.integer)
1290 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1293 int playerNumber, activeNumber, clientNumber;
1296 playerNumber = MSG_ReadByte();
1298 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1299 if (client->active && ++activeNumber == playerNumber)
1301 if (clientNumber != svs.maxclients)
1303 SZ_Clear(&net_message);
1304 // save space for the header, filled in later
1305 MSG_WriteLong(&net_message, 0);
1306 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1307 MSG_WriteByte(&net_message, playerNumber);
1308 MSG_WriteString(&net_message, client->name);
1309 MSG_WriteLong(&net_message, client->colors);
1310 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1311 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
1312 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
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);
1319 case CCREQ_RULE_INFO:
1320 if (developer.integer)
1321 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1327 // find the search start location
1328 prevCvarName = MSG_ReadString();
1329 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1331 // send the response
1332 SZ_Clear(&net_message);
1333 // save space for the header, filled in later
1334 MSG_WriteLong(&net_message, 0);
1335 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1338 MSG_WriteString(&net_message, var->name);
1339 MSG_WriteString(&net_message, var->string);
1341 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1342 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1343 SZ_Clear(&net_message);
1350 // we may not have liked the packet, but it was a valid control
1351 // packet, so we're done processing this packet now
1356 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1358 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1360 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1361 SV_ReadClientMessage();
1369 void NetConn_ServerFrame(void)
1372 lhnetaddress_t peeraddress;
1374 NetConn_UpdateServerStuff();
1375 for (i = 0;i < sv_numsockets;i++)
1376 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1377 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1378 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1380 // never timeout loopback connections
1381 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1383 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1384 SV_DropClient(false);
1387 for (conn = netconn_list;conn;conn = conn->next)
1388 NetConn_ReSendMessage(conn);
1391 void NetConn_QueryMasters(void)
1395 lhnetaddress_t masteraddress;
1398 if (hostCacheCount >= HOSTCACHESIZE)
1401 for (i = 0;i < cl_numsockets;i++)
1408 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1410 SZ_Clear(&net_message);
1411 // save space for the header, filled in later
1412 MSG_WriteLong(&net_message, 0);
1413 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1414 MSG_WriteString(&net_message, "QUAKE");
1415 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1416 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1417 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1418 SZ_Clear(&net_message);
1422 // build the getservers
1423 snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1426 for (masternum = 0;sv_masters[masternum].name;masternum++)
1428 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1431 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1436 if (!masterquerycount)
1438 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1439 M_Update_Return_Reason("No network");
1443 void NetConn_Heartbeat(int priority)
1445 lhnetaddress_t masteraddress;
1447 lhnetsocket_t *mysocket;
1449 // if it's a state change (client connected), limit next heartbeat to no
1450 // more than 30 sec in the future
1451 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1452 nextheartbeattime = realtime + 30.0;
1454 // limit heartbeatperiod to 30 to 270 second range,
1455 // lower limit is to avoid abusing master servers with excess traffic,
1456 // upper limit is to avoid timing out on the master server (which uses
1458 if (sv_heartbeatperiod.value < 30)
1459 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1460 if (sv_heartbeatperiod.value > 270)
1461 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1463 // make advertising optional and don't advertise singleplayer games, and
1464 // only send a heartbeat as often as the admin wants
1465 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1467 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1468 for (masternum = 0;sv_masters[masternum].name;masternum++)
1469 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1470 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1474 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1477 qbyte sent[MAX_SCOREBOARD];
1479 memset(sent, 0, sizeof(sent));
1481 // simultaneously wait for the first CanSendMessage and send the message,
1482 // then wait for a second CanSendMessage (verifying it was received), or
1483 // the client drops and is no longer counted
1484 // the loop aborts when either it runs out of clients to send to, or a
1486 blocktime += Sys_DoubleTime();
1490 NetConn_ClientFrame();
1491 NetConn_ServerFrame();
1492 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1494 if (host_client->netconnection)
1496 if (NetConn_CanSendMessage(host_client->netconnection))
1499 NetConn_SendReliableMessage(host_client->netconnection, data);
1502 if (!NetConn_CanSendMessage(host_client->netconnection))
1507 while (count && Sys_DoubleTime() < blocktime);
1511 static void Net_Heartbeat_f(void)
1514 NetConn_Heartbeat(2);
1516 Con_Print("No server running, can not heartbeat to master server.\n");
1519 void PrintStats(netconn_t *conn)
1521 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1524 void Net_Stats_f(void)
1527 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1528 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1529 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1530 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1531 Con_Printf("packetsSent = %i\n", packetsSent);
1532 Con_Printf("packetsReSent = %i\n", packetsReSent);
1533 Con_Printf("packetsReceived = %i\n", packetsReceived);
1534 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1535 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1536 Con_Print("connections =\n");
1537 for (conn = netconn_list;conn;conn = conn->next)
1541 void Net_Slist_f(void)
1543 masterquerytime = realtime;
1544 masterquerycount = 0;
1545 masterreplycount = 0;
1546 serverquerycount = 0;
1547 serverreplycount = 0;
1549 memset(&pingcache, 0, sizeof(pingcache));
1550 if (m_state != m_slist)
1551 Con_Print("Sending requests to master servers\n");
1552 NetConn_QueryMasters();
1553 if (m_state != m_slist)
1554 Con_Print("Listening for replies...\n");
1557 void NetConn_Init(void)
1560 lhnetaddress_t tempaddress;
1561 netconn_mempool = Mem_AllocPool("Networking", 0, NULL);
1562 Cmd_AddCommand("net_stats", Net_Stats_f);
1563 Cmd_AddCommand("net_slist", Net_Slist_f);
1564 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1565 Cvar_RegisterVariable(&net_messagetimeout);
1566 Cvar_RegisterVariable(&net_messagerejointimeout);
1567 Cvar_RegisterVariable(&net_connecttimeout);
1568 Cvar_RegisterVariable(&cl_netlocalping);
1569 Cvar_RegisterVariable(&cl_netpacketloss);
1570 Cvar_RegisterVariable(&hostname);
1571 Cvar_RegisterVariable(&developer_networking);
1572 Cvar_RegisterVariable(&cl_netport);
1573 Cvar_RegisterVariable(&sv_netport);
1574 Cvar_RegisterVariable(&net_address);
1575 //Cvar_RegisterVariable(&net_address_ipv6);
1576 Cvar_RegisterVariable(&sv_public);
1577 Cvar_RegisterVariable(&sv_heartbeatperiod);
1578 for (i = 0;sv_masters[i].name;i++)
1579 Cvar_RegisterVariable(&sv_masters[i]);
1580 // 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.
1581 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1583 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1585 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
1586 Cvar_SetQuick(&net_address, com_argv[i + 1]);
1589 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1591 // 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
1592 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1594 i = atoi(com_argv[i + 1]);
1595 if (i >= 0 && i < 65536)
1597 Con_Printf("-port option used, setting port cvar to %i\n", i);
1598 Cvar_SetValueQuick(&sv_netport, i);
1601 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1605 memset(&pingcache, 0, sizeof(pingcache));
1606 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1610 void NetConn_Shutdown(void)
1612 NetConn_CloseClientPorts();
1613 NetConn_CloseServerPorts();