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 /* statistic counters */
53 static int packetsSent = 0;
54 static int packetsReSent = 0;
55 static int packetsReceived = 0;
56 static int receivedDuplicateCount = 0;
57 static int droppedDatagrams = 0;
59 static int unreliableMessagesSent = 0;
60 static int unreliableMessagesReceived = 0;
61 static int reliableMessagesSent = 0;
62 static int reliableMessagesReceived = 0;
64 int hostCacheCount = 0;
65 hostcache_t hostcache[HOSTCACHESIZE];
67 static qbyte sendbuffer[NET_MAXMESSAGE];
68 static qbyte readbuffer[NET_MAXMESSAGE];
71 lhnetsocket_t *cl_sockets[16];
73 lhnetsocket_t *sv_sockets[16];
75 netconn_t *netconn_list = NULL;
76 mempool_t *netconn_mempool = NULL;
78 cvar_t cl_netport = {0, "cl_port", "0"};
79 cvar_t cl_netaddress = {0, "cl_netaddress", "0.0.0.0"};
80 cvar_t cl_netaddress_ipv6 = {0, "cl_netaddress_ipv6", "[0:0:0:0:0:0:0:0]:0"};
82 cvar_t sv_netport = {0, "port", "26000"};
83 cvar_t sv_netaddress = {0, "sv_netaddress", "0.0.0.0"};
84 cvar_t sv_netaddress_ipv6 = {0, "sv_netaddress_ipv6", "[0:0:0:0:0:0:0:0]:26000"};
86 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
88 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
89 if (developer_networking.integer && length != 0)
91 char addressstring[128], addressstring2[128];
92 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
95 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
96 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
97 Com_HexDumpToConsole(data, length);
100 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
105 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
107 int ret = LHNET_Write(mysocket, data, length, peeraddress);
108 if (developer_networking.integer && ret != 0)
110 char addressstring[128], addressstring2[128];
111 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
112 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
113 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
114 Com_HexDumpToConsole(data, length);
119 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
121 unsigned int packetLen;
122 unsigned int dataLen;
124 unsigned int *header;
127 if (data->cursize == 0)
128 Sys_Error("Datagram_SendMessage: zero length message\n");
130 if (data->cursize > NET_MAXMESSAGE)
131 Sys_Error("Datagram_SendMessage: message too big %u\n", data->cursize);
133 if (conn->canSend == false)
134 Sys_Error("SendMessage: called with canSend == false\n");
137 memcpy(conn->sendMessage, data->data, data->cursize);
138 conn->sendMessageLength = data->cursize;
140 if (conn->sendMessageLength <= MAX_DATAGRAM)
142 dataLen = conn->sendMessageLength;
147 dataLen = MAX_DATAGRAM;
151 packetLen = NET_HEADERSIZE + dataLen;
153 header = (void *)sendbuffer;
154 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
155 header[1] = BigLong(conn->sendSequence);
156 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
158 conn->sendSequence++;
159 conn->canSend = false;
161 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
164 conn->lastSendTime = realtime;
166 reliableMessagesSent++;
170 static void NetConn_SendMessageNext(netconn_t *conn)
172 unsigned int packetLen;
173 unsigned int dataLen;
175 unsigned int *header;
177 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
179 if (conn->sendMessageLength <= MAX_DATAGRAM)
181 dataLen = conn->sendMessageLength;
186 dataLen = MAX_DATAGRAM;
190 packetLen = NET_HEADERSIZE + dataLen;
192 header = (void *)sendbuffer;
193 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
194 header[1] = BigLong(conn->sendSequence);
195 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
197 conn->sendSequence++;
198 conn->sendNext = false;
200 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
203 conn->lastSendTime = realtime;
208 static void NetConn_ReSendMessage(netconn_t *conn)
210 unsigned int packetLen;
211 unsigned int dataLen;
213 unsigned int *header;
215 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
217 if (conn->sendMessageLength <= MAX_DATAGRAM)
219 dataLen = conn->sendMessageLength;
224 dataLen = MAX_DATAGRAM;
228 packetLen = NET_HEADERSIZE + dataLen;
230 header = (void *)sendbuffer;
231 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
232 header[1] = BigLong(conn->sendSequence - 1);
233 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
235 conn->sendNext = false;
237 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
240 conn->lastSendTime = realtime;
245 qboolean NetConn_CanSendMessage(netconn_t *conn)
247 return conn->canSend;
250 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
256 if (data->cursize == 0)
257 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
259 if (data->cursize > MAX_DATAGRAM)
260 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
263 packetLen = NET_HEADERSIZE + data->cursize;
265 header = (void *)sendbuffer;
266 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
267 header[1] = BigLong(conn->unreliableSendSequence);
268 memcpy(sendbuffer + 8, data->data, data->cursize);
270 conn->unreliableSendSequence++;
272 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
276 unreliableMessagesSent++;
280 void NetConn_CloseClientPorts(void)
282 for (;cl_numsockets > 0;cl_numsockets--)
283 if (cl_sockets[cl_numsockets - 1])
284 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
287 void NetConn_OpenClientPorts(void)
290 lhnetaddress_t address;
291 NetConn_CloseClientPorts();
292 port = bound(0, cl_netport.integer, 65535);
293 if (cl_netport.integer != port)
294 Cvar_SetValueQuick(&cl_netport, port);
295 LHNETADDRESS_FromString(&address, "local", port);
296 cl_sockets[cl_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
297 LHNETADDRESS_FromString(&address, cl_netaddress.string, port);
298 cl_sockets[cl_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
299 LHNETADDRESS_FromString(&address, cl_netaddress_ipv6.string, port);
300 cl_sockets[cl_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
303 void NetConn_CloseServerPorts(void)
305 for (;sv_numsockets > 0;sv_numsockets--)
306 if (sv_sockets[sv_numsockets - 1])
307 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
310 void NetConn_OpenServerPorts(int opennetports)
313 lhnetaddress_t address;
314 NetConn_CloseServerPorts();
315 port = bound(0, sv_netport.integer, 65535);
318 if (sv_netport.integer != port)
319 Cvar_SetValueQuick(&sv_netport, port);
320 LHNETADDRESS_FromString(&address, "local", port);
321 sv_sockets[sv_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
324 LHNETADDRESS_FromString(&address, sv_netaddress.string, port);
325 sv_sockets[sv_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
326 LHNETADDRESS_FromString(&address, sv_netaddress_ipv6.string, port);
327 sv_sockets[sv_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
331 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
333 int i, a = LHNETADDRESS_GetAddressType(address);
334 for (i = 0;i < cl_numsockets;i++)
335 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
336 return cl_sockets[i];
340 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
342 int i, a = LHNETADDRESS_GetAddressType(address);
343 for (i = 0;i < sv_numsockets;i++)
344 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
345 return sv_sockets[i];
349 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
352 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
353 conn->mysocket = mysocket;
354 conn->peeraddress = *peeraddress;
355 conn->canSend = true;
356 conn->connecttime = realtime;
357 conn->lastMessageTime = realtime;
358 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
359 // reduce effectiveness of connection request floods
360 conn->timeout = realtime + net_connecttimeout.value;
361 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
362 conn->next = netconn_list;
367 void NetConn_Close(netconn_t *conn)
370 // remove connection from list
371 if (conn == netconn_list)
372 netconn_list = conn->next;
375 for (c = netconn_list;c;c = c->next)
379 c->next = conn->next;
383 // not found in list, we'll avoid crashing here...
391 static int clientport = -1;
392 static int clientport2 = -1;
393 static int hostport = -1;
394 static void NetConn_UpdateServerStuff(void)
396 if (clientport2 != cl_netport.integer)
398 clientport2 = cl_netport.integer;
399 if (cls.state == ca_connected)
400 Con_Printf("Changing \"cl_port\" will not take effect until you reconnect.\n");
402 if (cls.state != ca_dedicated)
404 if (cls.state == ca_disconnected && clientport != cl_netport.integer)
406 clientport = cl_netport.integer;
407 NetConn_CloseClientPorts();
409 if (cl_numsockets == 0)
410 NetConn_OpenClientPorts();
413 if (hostport != sv_netport.integer)
415 hostport = sv_netport.integer;
417 Con_Printf("Changing \"port\" will not take effect until \"map\" command is executed.\n");
421 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
425 unsigned int sequence;
429 length = BigLong(((int *)data)[0]);
430 flags = length & ~NETFLAG_LENGTH_MASK;
431 length &= NETFLAG_LENGTH_MASK;
432 // control packets were already handled
433 if (!(flags & NETFLAG_CTL))
435 sequence = BigLong(((int *)data)[1]);
439 if (flags & NETFLAG_UNRELIABLE)
441 if (sequence >= conn->unreliableReceiveSequence)
443 if (sequence > conn->unreliableReceiveSequence)
445 count = sequence - conn->unreliableReceiveSequence;
446 droppedDatagrams += count;
447 Con_DPrintf("Dropped %u datagram(s)\n", count);
449 conn->unreliableReceiveSequence = sequence + 1;
450 conn->lastMessageTime = realtime;
451 conn->timeout = realtime + net_messagetimeout.value;
452 unreliableMessagesReceived++;
453 SZ_Clear(&net_message);
454 SZ_Write(&net_message, data, length);
459 Con_DPrintf("Got a stale datagram\n");
462 else if (flags & NETFLAG_ACK)
464 if (sequence == (conn->sendSequence - 1))
466 if (sequence == conn->ackSequence)
469 if (conn->ackSequence != conn->sendSequence)
470 Con_DPrintf("ack sequencing error\n");
471 conn->lastMessageTime = realtime;
472 conn->timeout = realtime + net_messagetimeout.value;
473 conn->sendMessageLength -= MAX_DATAGRAM;
474 if (conn->sendMessageLength > 0)
476 memcpy(conn->sendMessage, conn->sendMessage+MAX_DATAGRAM, conn->sendMessageLength);
477 conn->sendNext = true;
478 NetConn_SendMessageNext(conn);
482 conn->sendMessageLength = 0;
483 conn->canSend = true;
487 Con_DPrintf("Duplicate ACK received\n");
490 Con_DPrintf("Stale ACK received\n");
493 else if (flags & NETFLAG_DATA)
495 unsigned int temppacket[2];
496 temppacket[0] = BigLong(8 | NETFLAG_ACK);
497 temppacket[1] = BigLong(sequence);
498 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
499 if (sequence == conn->receiveSequence)
501 conn->lastMessageTime = realtime;
502 conn->timeout = realtime + net_messagetimeout.value;
503 conn->receiveSequence++;
504 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
505 conn->receiveMessageLength += length;
506 if (flags & NETFLAG_EOM)
508 reliableMessagesReceived++;
509 SZ_Clear(&net_message);
510 SZ_Write(&net_message, conn->receiveMessage, conn->receiveMessageLength);
511 conn->receiveMessageLength = 0;
517 receivedDuplicateCount++;
528 lhnetaddress_t peeraddress;
530 pingcache[HOSTCACHESIZE];
532 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
535 lhnetaddress_t svaddress;
537 char *string, addressstring2[128], cname[128], ipstring[32];
539 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
543 string = (char *)data;
544 if (developer.integer)
546 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
547 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
548 Com_HexDumpToConsole(data, length);
550 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
552 int i, j, c, n, users, maxusers;
553 char game[32], mod[32], map[32], name[128];
557 // hostcache only uses text addresses
558 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
559 // search the cache for this server
560 for (n = 0; n < hostCacheCount; n++)
561 if (!strcmp(cname, hostcache[n].cname))
563 // add it or update it
564 if (n == hostCacheCount)
566 // if cache is full replace highest ping server (the list is
567 // kept sorted so this is always the last, and if this server
568 // is good it will be sorted into an early part of the list)
569 if (hostCacheCount >= HOSTCACHESIZE)
570 n = hostCacheCount - 1;
574 if ((s = SearchInfostring(string, "gamename" )) != NULL) strncpy(game, s, sizeof(game) - 1);else game[0] = 0;
575 if ((s = SearchInfostring(string, "modname" )) != NULL) strncpy(mod , s, sizeof(mod ) - 1);else mod[0] = 0;
576 if ((s = SearchInfostring(string, "mapname" )) != NULL) strncpy(map , s, sizeof(map ) - 1);else map[0] = 0;
577 if ((s = SearchInfostring(string, "hostname" )) != NULL) strncpy(name, s, sizeof(name) - 1);else name[0] = 0;
578 if ((s = SearchInfostring(string, "protocol" )) != NULL) c = atoi(s);else c = -1;
579 if ((s = SearchInfostring(string, "clients" )) != NULL) users = atoi(s);else users = 0;
580 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) maxusers = atoi(s);else maxusers = 0;
582 for (i = 0;i < HOSTCACHESIZE;i++)
583 if (!LHNETADDRESS_Compare(peeraddress, &pingcache[i].peeraddress))
584 pingtime = (int)(realtime - pingcache[i].senttime);
585 pingtime = bound(0, pingtime, 9999);
586 memset(&hostcache[n], 0, sizeof(hostcache[n]));
587 // store the data the engine cares about (address and ping)
588 strcpy(hostcache[n].cname, cname);
589 hostcache[n].ping = pingtime;
590 // build description strings for the things users care about
591 snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, c != NET_PROTOCOL_VERSION ? '*' : ' ', users, maxusers, name);
592 snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", cname, game, mod, map);
593 // if ping is especially high, display it as such
596 // orange numbers (lower block)
597 for (i = 0;i < 5;i++)
598 if (hostcache[n].line1[i] != ' ')
599 hostcache[n].line1[i] += 128;
601 else if (pingtime >= 200)
603 // yellow numbers (in upper block)
604 for (i = 0;i < 5;i++)
605 if (hostcache[n].line1[i] != ' ')
606 hostcache[n].line1[i] -= 30;
608 // if not in the slist menu we should print the server to console
609 if (m_state != m_slist)
610 Con_Printf("%s\n%s\n", hostcache[n].line1, hostcache[n].line2);
611 // and finally, re-sort the list
612 for (i = 0;i < hostCacheCount;i++)
614 for (j = i + 1;j < hostCacheCount;j++)
616 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
617 if (hostcache[i].ping > hostcache[j].ping)
619 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
620 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
621 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
627 if (!strncmp(string, "getserversResponse\\", 19) && hostCacheCount < HOSTCACHESIZE)
631 // Extract the IP addresses
634 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
636 sprintf(ipstring, "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
637 if (developer.integer)
638 Con_Printf("Requesting info from server %s\n", ipstring);
639 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
640 NetConn_Write(mysocket, "\377\377\377\377getinfo", 11, &svaddress);
641 // replace oldest or matching entry in ping cache
642 // we scan this later when getting a reply to see how long it took
645 for (i = 0;i < HOSTCACHESIZE;i++)
647 if (!LHNETADDRESS_Compare(&svaddress, &pingcache[i].peeraddress))
652 if (besttime > pingcache[i].senttime)
654 besttime = pingcache[i].senttime;
656 // if ping cache isn't full yet we can skip out early
661 pingcache[best].peeraddress = svaddress;
662 pingcache[best].senttime = realtime;
663 // move on to next address in packet
670 if (!strncmp(string, "ping", 4))
672 if (developer.integer)
673 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
674 NetConn_Write(mysocket, "\377\377\377\377ack", 7, peeraddress);
677 if (!strncmp(string, "ack", 3))
680 // we may not have liked the packet, but it was a command packet, so
681 // we're done processing this packet now
684 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
689 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
693 if (developer.integer)
694 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
695 if (cls.connect_trying)
697 Con_Printf("Connection accepted to %s\n", addressstring2);
700 cls.netcon = NetConn_Open(mysocket, peeraddress);
703 unsigned int port = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3];
706 LHNETADDRESS_SetPort(&cls.netcon->peeraddress, port);
708 cls.connect_trying = false;
709 cls.demonum = -1; // not in the demo loop now
710 cls.state = ca_connected;
711 cls.signon = 0; // need all the signon messages before playing
717 if (developer.integer)
718 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
719 Con_Printf("%s\n", data);
720 strncpy(m_return_reason, data, sizeof(m_return_reason) - 1);
723 case CCREP_SERVER_INFO:
724 if (developer.integer)
725 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
726 if (cls.state != ca_dedicated)
728 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
729 // string we just ignore it and keep the real address
731 // hostcache only uses text addresses
732 cname = UDP_AddrToString(readaddr);
733 // search the cache for this server
734 for (n = 0; n < hostCacheCount; n++)
735 if (!strcmp(cname, hostcache[n].cname))
738 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
741 memset(&hostcache[n], 0, sizeof(hostcache[n]));
742 strcpy(hostcache[n].name, MSG_ReadString());
743 strcpy(hostcache[n].map, MSG_ReadString());
744 hostcache[n].users = MSG_ReadByte();
745 hostcache[n].maxusers = MSG_ReadByte();
747 if (c != NET_PROTOCOL_VERSION)
749 strncpy(hostcache[n].cname, hostcache[n].name, sizeof(hostcache[n].cname) - 1);
750 hostcache[n].cname[sizeof(hostcache[n].cname) - 1] = 0;
751 strcpy(hostcache[n].name, "*");
752 strncat(hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name) - 1);
753 hostcache[n].name[sizeof(hostcache[n].name) - 1] = 0;
755 strcpy(hostcache[n].cname, cname);
759 case CCREP_PLAYER_INFO:
760 // we got a CCREP_PLAYER_INFO??
761 //if (developer.integer)
762 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
764 case CCREP_RULE_INFO:
765 // we got a CCREP_RULE_INFO??
766 //if (developer.integer)
767 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
773 // we may not have liked the packet, but it was a valid control
774 // packet, so we're done processing this packet now
778 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)
779 CL_ParseServerMessage();
783 void NetConn_ClientFrame(void)
786 lhnetaddress_t peeraddress;
788 NetConn_UpdateServerStuff();
789 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
791 if (cls.connect_remainingtries == 0)
793 cls.connect_trying = false;
794 Host_Error("Connect failed\n");
797 if (cls.connect_nextsendtime)
798 Con_Printf("Still trying...\n");
800 Con_Printf("Trying...\n");
801 cls.connect_nextsendtime = realtime + 1;
802 cls.connect_remainingtries--;
803 SZ_Clear(&net_message);
804 // save space for the header, filled in later
805 MSG_WriteLong(&net_message, 0);
806 MSG_WriteByte(&net_message, CCREQ_CONNECT);
807 MSG_WriteString(&net_message, "QUAKE");
808 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
809 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
810 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
811 SZ_Clear(&net_message);
813 for (i = 0;i < cl_numsockets;i++)
814 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
815 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
816 if (cls.netcon && realtime > cls.netcon->timeout)
818 Con_Printf("Connection timed out\n");
821 for (conn = netconn_list;conn;conn = conn->next)
822 NetConn_ReSendMessage(conn);
825 extern void SV_ConnectClient(int clientnum, netconn_t *netconnection);
826 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
828 int i, c, n, ret, clientnum, control, responselength;
831 char *string, response[512], addressstring2[128];
835 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
839 string = (char *)data;
841 if (developer.integer)
843 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
844 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
845 Com_HexDumpToConsole(data, length);
848 if (length >= 7 && !memcmp(string, "getinfo", 7))
850 const char *challenge = NULL;
851 // If there was a challenge in the getinfo message
852 if (length > 8 && string[7] == ' ')
853 challenge = string + 8;
854 for (i = 0, n = 0;i < svs.maxclients;i++)
855 if (svs.clients[i].active)
857 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
858 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
859 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
860 gamename, com_modname, svs.maxclients, n,
861 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
862 // does it fit in the buffer?
863 if (responselength < (int)sizeof(response))
865 if (developer.integer)
866 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
867 NetConn_Write(mysocket, response, responselength, peeraddress);
872 if (!strncmp(string, "ping", 4))
874 if (developer.integer)
875 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
876 NetConn_Write(mysocket, "\377\377\377\377ack", 7, peeraddress);
879 if (!strncmp(string, "ack", 3))
882 // we may not have liked the packet, but it was a command packet, so
883 // we're done processing this packet now
889 control = BigLong(*((int *)data));
890 if ((control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
895 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
899 //if (developer.integer)
900 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
901 if (length >= (int)strlen("QUAKE") + 1 + 1)
903 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
905 if (developer.integer)
906 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
908 NetConn_Write(mysocket, "\377\377\377\377reject Incompatible version.", 32, peeraddress);
910 SZ_Clear(&net_message);
911 // save space for the header, filled in later
912 MSG_WriteLong(&net_message, 0);
913 MSG_WriteByte(&net_message, CCREP_REJECT);
914 MSG_WriteString(&net_message, "Incompatible version.\n");
915 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
916 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
917 SZ_Clear(&net_message);
922 // see if this is a duplicate connection request
923 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
924 if (client->active && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
926 if (clientnum < svs.maxclients)
928 // duplicate connection request
929 if (realtime - client->netconnection->connecttime < 2.0)
931 // client is still trying to connect,
932 // so we send a duplicate reply
933 if (developer.integer)
934 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
936 NetConn_Write(mysocket, "\377\377\377\377accept", 10, peeraddress);
938 SZ_Clear(&net_message);
939 // save space for the header, filled in later
940 MSG_WriteLong(&net_message, 0);
941 MSG_WriteByte(&net_message, CCREP_ACCEPT);
942 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
943 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
944 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
945 SZ_Clear(&net_message);
948 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
950 // the old client hasn't sent us anything
951 // in quite a while, so kick off and let
952 // the retry take care of it...
953 client->deadsocket = true;
958 // this is a new client, find a slot
959 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
962 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
964 // connect to the client
965 // everything is allocated, just fill in the details
966 strcpy(conn->address, addressstring2);
967 if (developer.integer)
968 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
970 NetConn_Write(mysocket, "\377\377\377\377accept", 10, peeraddress);
972 // send back the info about the server connection
973 SZ_Clear(&net_message);
974 // save space for the header, filled in later
975 MSG_WriteLong(&net_message, 0);
976 MSG_WriteByte(&net_message, CCREP_ACCEPT);
977 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
978 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
979 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
980 SZ_Clear(&net_message);
982 // now set up the client struct
983 SV_ConnectClient(clientnum, conn);
984 NetConn_Heartbeat(1);
988 //if (developer.integer)
989 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
990 // no room; try to let player know
992 NetConn_Write(mysocket, "\377\377\377\377reject Server is full.", 26, peeraddress);
994 SZ_Clear(&net_message);
995 // save space for the header, filled in later
996 MSG_WriteLong(&net_message, 0);
997 MSG_WriteByte(&net_message, CCREP_REJECT);
998 MSG_WriteString(&net_message, "Server is full.\n");
999 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1000 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1001 SZ_Clear(&net_message);
1009 case CCREQ_SERVER_INFO:
1010 if (developer.integer)
1011 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1012 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1014 if (developer.integer)
1015 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1016 SZ_Clear(&net_message);
1017 // save space for the header, filled in later
1018 MSG_WriteLong(&net_message, 0);
1019 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1020 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1021 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1022 MSG_WriteString(&net_message, hostname.string);
1023 MSG_WriteString(&net_message, sv.name);
1024 MSG_WriteByte(&net_message, net_activeconnections);
1025 MSG_WriteByte(&net_message, svs.maxclients);
1026 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1027 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1028 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1029 SZ_Clear(&net_message);
1032 case CCREQ_PLAYER_INFO:
1033 if (developer.integer)
1034 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1037 int playerNumber, activeNumber, clientNumber;
1040 playerNumber = MSG_ReadByte();
1042 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1043 if (client->active && ++activeNumber == playerNumber)
1045 if (clientNumber != svs.maxclients)
1047 SZ_Clear(&net_message);
1048 // save space for the header, filled in later
1049 MSG_WriteLong(&net_message, 0);
1050 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1051 MSG_WriteByte(&net_message, playerNumber);
1052 MSG_WriteString(&net_message, client->name);
1053 MSG_WriteLong(&net_message, client->colors);
1054 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1055 MSG_WriteLong(&net_message, (int)(realtime - client->netconnection->connecttime));
1056 MSG_WriteString(&net_message, client->netconnection->address);
1057 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1058 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1059 SZ_Clear(&net_message);
1063 case CCREQ_RULE_INFO:
1064 if (developer.integer)
1065 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1071 // find the search start location
1072 prevCvarName = MSG_ReadString();
1073 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1075 // send the response
1076 SZ_Clear(&net_message);
1077 // save space for the header, filled in later
1078 MSG_WriteLong(&net_message, 0);
1079 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1082 MSG_WriteString(&net_message, var->name);
1083 MSG_WriteString(&net_message, var->string);
1085 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1086 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1087 SZ_Clear(&net_message);
1094 // we may not have liked the packet, but it was a valid control
1095 // packet, so we're done processing this packet now
1100 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1102 if (host_client->active && host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1104 sv_player = host_client->edict;
1105 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1106 SV_ReadClientMessage();
1114 void NetConn_ServerFrame(void)
1117 lhnetaddress_t peeraddress;
1119 NetConn_UpdateServerStuff();
1120 for (i = 0;i < sv_numsockets;i++)
1121 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1122 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1123 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1125 if (host_client->active && realtime > host_client->netconnection->timeout)
1127 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1128 sv_player = host_client->edict;
1129 SV_DropClient(false);
1132 for (conn = netconn_list;conn;conn = conn->next)
1133 NetConn_ReSendMessage(conn);
1136 void NetConn_QueryMasters(void)
1141 lhnetaddress_t masteraddress;
1144 if (hostCacheCount >= HOSTCACHESIZE)
1147 for (i = 0;i < cl_numsockets;i++)
1154 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1156 SZ_Clear(&net_message);
1157 // save space for the header, filled in later
1158 MSG_WriteLong(&net_message, 0);
1159 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1160 MSG_WriteString(&net_message, "QUAKE");
1161 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1162 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1163 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1164 SZ_Clear(&net_message);
1168 // build the getservers
1169 requestlen = snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1172 for (masternum = 0;sv_masters[masternum].name;masternum++)
1173 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1174 NetConn_Write(cl_sockets[i], request, requestlen, &masteraddress);
1179 void NetConn_Heartbeat(int priority)
1181 lhnetaddress_t masteraddress;
1183 char *request = "\377\377\377\377heartbeat DarkPlaces\x0A";
1184 int requestlen = strlen(request);
1185 lhnetsocket_t *mysocket;
1187 // if it's a state change (client connected), limit next heartbeat to no
1188 // more than 30 sec in the future
1189 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1190 nextheartbeattime = realtime + 30.0;
1192 // limit heartbeatperiod to 30 to 270 second range,
1193 // lower limit is to avoid abusing master servers with excess traffic,
1194 // upper limit is to avoid timing out on the master server (which uses
1196 if (sv_heartbeatperiod.value < 30)
1197 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1198 if (sv_heartbeatperiod.value > 270)
1199 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1201 // make advertising optional and don't advertise singleplayer games, and
1202 // only send a heartbeat as often as the admin wants
1203 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1205 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1206 for (masternum = 0;sv_masters[masternum].name;masternum++)
1207 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1208 NetConn_Write(mysocket, request, requestlen, &masteraddress);
1212 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1215 qbyte sent[MAX_SCOREBOARD];
1217 memset(sent, 0, sizeof(sent));
1219 // simultaneously wait for the first CanSendMessage and send the message,
1220 // then wait for a second CanSendMessage (verifying it was received), or
1221 // the client drops and is no longer counted
1222 // the loop aborts when either it runs out of clients to send to, or a
1224 blocktime += Sys_DoubleTime();
1228 NetConn_ClientFrame();
1229 NetConn_ServerFrame();
1230 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1232 if (host_client->active)
1234 if (NetConn_CanSendMessage(host_client->netconnection))
1237 NetConn_SendReliableMessage(host_client->netconnection, data);
1240 if (!NetConn_CanSendMessage(host_client->netconnection))
1245 while (count && Sys_DoubleTime() < blocktime);
1249 static void MaxPlayers_f(void)
1253 if (Cmd_Argc() != 2)
1255 Con_Printf("\"maxplayers\" is \"%u\"\n", svs.maxclients);
1261 Con_Printf("maxplayers can not be changed while a server is running.\n");
1265 n = atoi(Cmd_Argv(1));
1266 n = bound(1, n, MAX_SCOREBOARD);
1267 if (svs.maxclients != n)
1268 Con_Printf("\"maxplayers\" set to \"%u\"\n", n);
1270 SV_SetMaxClients(n);
1273 static void Net_Heartbeat_f(void)
1275 NetConn_Heartbeat(2);
1278 void PrintStats(netconn_t *conn)
1280 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1283 void Net_Stats_f(void)
1286 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1287 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1288 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1289 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1290 Con_Printf("packetsSent = %i\n", packetsSent);
1291 Con_Printf("packetsReSent = %i\n", packetsReSent);
1292 Con_Printf("packetsReceived = %i\n", packetsReceived);
1293 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1294 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1295 Con_Printf("connections =\n");
1296 for (conn = netconn_list;conn;conn = conn->next)
1300 void Net_Slist_f(void)
1303 memset(&pingcache, 0, sizeof(pingcache));
1304 if (m_state != m_slist)
1305 Con_Printf("Sending requests to master servers\n");
1306 NetConn_QueryMasters();
1307 if (m_state != m_slist)
1308 Con_Printf("Listening for replies...\n");
1311 void NetConn_Init(void)
1314 netconn_mempool = Mem_AllocPool("Networking");
1315 Cmd_AddCommand("net_stats", Net_Stats_f);
1316 Cmd_AddCommand("net_slist", Net_Slist_f);
1317 Cmd_AddCommand("maxplayers", MaxPlayers_f);
1318 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1319 Cvar_RegisterVariable(&net_messagetimeout);
1320 Cvar_RegisterVariable(&net_messagerejointimeout);
1321 Cvar_RegisterVariable(&net_connecttimeout);
1322 Cvar_RegisterVariable(&hostname);
1323 Cvar_RegisterVariable(&developer_networking);
1324 Cvar_RegisterVariable(&cl_netport);
1325 Cvar_RegisterVariable(&cl_netaddress);
1326 Cvar_RegisterVariable(&cl_netaddress_ipv6);
1327 Cvar_RegisterVariable(&sv_netport);
1328 Cvar_RegisterVariable(&sv_netaddress);
1329 Cvar_RegisterVariable(&sv_netaddress_ipv6);
1330 Cvar_RegisterVariable(&sv_public);
1331 Cvar_RegisterVariable(&sv_heartbeatperiod);
1332 for (masternum = 0;sv_masters[masternum].name;masternum++)
1333 Cvar_RegisterVariable(&sv_masters[masternum]);
1336 memset(&pingcache, 0, sizeof(pingcache));
1337 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1341 void NetConn_Shutdown(void)
1343 NetConn_CloseClientPorts();
1344 NetConn_CloseServerPorts();