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)
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_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
121 // note this does not include the trailing NULL because we add that in the parser
122 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
125 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
127 unsigned int packetLen;
128 unsigned int dataLen;
130 unsigned int *header;
133 if (data->cursize == 0)
134 Sys_Error("Datagram_SendMessage: zero length message\n");
136 if (data->cursize > NET_MAXMESSAGE)
137 Sys_Error("Datagram_SendMessage: message too big %u\n", data->cursize);
139 if (conn->canSend == false)
140 Sys_Error("SendMessage: called with canSend == false\n");
143 memcpy(conn->sendMessage, data->data, data->cursize);
144 conn->sendMessageLength = data->cursize;
146 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
148 dataLen = conn->sendMessageLength;
153 dataLen = MAX_PACKETFRAGMENT;
157 packetLen = NET_HEADERSIZE + dataLen;
159 header = (void *)sendbuffer;
160 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
161 header[1] = BigLong(conn->sendSequence);
162 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
164 conn->sendSequence++;
165 conn->canSend = false;
167 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
170 conn->lastSendTime = realtime;
172 reliableMessagesSent++;
176 static void NetConn_SendMessageNext(netconn_t *conn)
178 unsigned int packetLen;
179 unsigned int dataLen;
181 unsigned int *header;
183 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
185 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
187 dataLen = conn->sendMessageLength;
192 dataLen = MAX_PACKETFRAGMENT;
196 packetLen = NET_HEADERSIZE + dataLen;
198 header = (void *)sendbuffer;
199 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
200 header[1] = BigLong(conn->sendSequence);
201 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
203 conn->sendSequence++;
204 conn->sendNext = false;
206 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
209 conn->lastSendTime = realtime;
214 static void NetConn_ReSendMessage(netconn_t *conn)
216 unsigned int packetLen;
217 unsigned int dataLen;
219 unsigned int *header;
221 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
223 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
225 dataLen = conn->sendMessageLength;
230 dataLen = MAX_PACKETFRAGMENT;
234 packetLen = NET_HEADERSIZE + dataLen;
236 header = (void *)sendbuffer;
237 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
238 header[1] = BigLong(conn->sendSequence - 1);
239 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
241 conn->sendNext = false;
243 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
246 conn->lastSendTime = realtime;
251 qboolean NetConn_CanSendMessage(netconn_t *conn)
253 return conn->canSend;
256 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
262 if (data->cursize == 0)
263 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
265 if (data->cursize > MAX_DATAGRAM)
266 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
269 packetLen = NET_HEADERSIZE + data->cursize;
271 header = (void *)sendbuffer;
272 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
273 header[1] = BigLong(conn->unreliableSendSequence);
274 memcpy(sendbuffer + 8, data->data, data->cursize);
276 conn->unreliableSendSequence++;
278 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
282 unreliableMessagesSent++;
286 void NetConn_CloseClientPorts(void)
288 for (;cl_numsockets > 0;cl_numsockets--)
289 if (cl_sockets[cl_numsockets - 1])
290 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
293 void NetConn_OpenClientPorts(void)
296 lhnetaddress_t address;
297 NetConn_CloseClientPorts();
298 port = bound(0, cl_netport.integer, 65535);
299 if (cl_netport.integer != port)
300 Cvar_SetValueQuick(&cl_netport, port);
301 LHNETADDRESS_FromString(&address, "local", port);
302 cl_sockets[cl_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
303 LHNETADDRESS_FromString(&address, cl_netaddress.string, port);
304 cl_sockets[cl_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
305 LHNETADDRESS_FromString(&address, cl_netaddress_ipv6.string, port);
306 cl_sockets[cl_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
309 void NetConn_CloseServerPorts(void)
311 for (;sv_numsockets > 0;sv_numsockets--)
312 if (sv_sockets[sv_numsockets - 1])
313 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
316 void NetConn_OpenServerPorts(int opennetports)
319 lhnetaddress_t address;
320 NetConn_CloseServerPorts();
321 port = bound(0, sv_netport.integer, 65535);
324 if (sv_netport.integer != port)
325 Cvar_SetValueQuick(&sv_netport, port);
326 LHNETADDRESS_FromString(&address, "local", port);
327 sv_sockets[sv_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
330 LHNETADDRESS_FromString(&address, sv_netaddress.string, port);
331 sv_sockets[sv_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
332 LHNETADDRESS_FromString(&address, sv_netaddress_ipv6.string, port);
333 sv_sockets[sv_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
337 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
339 int i, a = LHNETADDRESS_GetAddressType(address);
340 for (i = 0;i < cl_numsockets;i++)
341 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
342 return cl_sockets[i];
346 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
348 int i, a = LHNETADDRESS_GetAddressType(address);
349 for (i = 0;i < sv_numsockets;i++)
350 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
351 return sv_sockets[i];
355 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
358 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
359 conn->mysocket = mysocket;
360 conn->peeraddress = *peeraddress;
361 conn->canSend = true;
362 conn->connecttime = realtime;
363 conn->lastMessageTime = realtime;
364 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
365 // reduce effectiveness of connection request floods
366 conn->timeout = realtime + net_connecttimeout.value;
367 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
368 conn->next = netconn_list;
373 void NetConn_Close(netconn_t *conn)
376 // remove connection from list
377 if (conn == netconn_list)
378 netconn_list = conn->next;
381 for (c = netconn_list;c;c = c->next)
385 c->next = conn->next;
389 // not found in list, we'll avoid crashing here...
397 static int clientport = -1;
398 static int clientport2 = -1;
399 static int hostport = -1;
400 static void NetConn_UpdateServerStuff(void)
402 if (clientport2 != cl_netport.integer)
404 clientport2 = cl_netport.integer;
405 if (cls.state == ca_connected)
406 Con_Printf("Changing \"cl_port\" will not take effect until you reconnect.\n");
408 if (cls.state != ca_dedicated)
410 if (cls.state == ca_disconnected && clientport != cl_netport.integer)
412 clientport = cl_netport.integer;
413 NetConn_CloseClientPorts();
415 if (cl_numsockets == 0)
416 NetConn_OpenClientPorts();
419 if (hostport != sv_netport.integer)
421 hostport = sv_netport.integer;
423 Con_Printf("Changing \"port\" will not take effect until \"map\" command is executed.\n");
427 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
431 unsigned int sequence;
435 length = BigLong(((int *)data)[0]);
436 flags = length & ~NETFLAG_LENGTH_MASK;
437 length &= NETFLAG_LENGTH_MASK;
438 // control packets were already handled
439 if (!(flags & NETFLAG_CTL))
441 sequence = BigLong(((int *)data)[1]);
445 if (flags & NETFLAG_UNRELIABLE)
447 if (sequence >= conn->unreliableReceiveSequence)
449 if (sequence > conn->unreliableReceiveSequence)
451 count = sequence - conn->unreliableReceiveSequence;
452 droppedDatagrams += count;
453 Con_DPrintf("Dropped %u datagram(s)\n", count);
455 conn->unreliableReceiveSequence = sequence + 1;
456 conn->lastMessageTime = realtime;
457 conn->timeout = realtime + net_messagetimeout.value;
458 unreliableMessagesReceived++;
461 SZ_Clear(&net_message);
462 SZ_Write(&net_message, data, length);
468 Con_DPrintf("Got a stale datagram\n");
471 else if (flags & NETFLAG_ACK)
473 if (sequence == (conn->sendSequence - 1))
475 if (sequence == conn->ackSequence)
478 if (conn->ackSequence != conn->sendSequence)
479 Con_DPrintf("ack sequencing error\n");
480 conn->lastMessageTime = realtime;
481 conn->timeout = realtime + net_messagetimeout.value;
482 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
483 if (conn->sendMessageLength > 0)
485 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
486 conn->sendNext = true;
487 NetConn_SendMessageNext(conn);
491 conn->sendMessageLength = 0;
492 conn->canSend = true;
496 Con_DPrintf("Duplicate ACK received\n");
499 Con_DPrintf("Stale ACK received\n");
502 else if (flags & NETFLAG_DATA)
504 unsigned int temppacket[2];
505 temppacket[0] = BigLong(8 | NETFLAG_ACK);
506 temppacket[1] = BigLong(sequence);
507 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
508 if (sequence == conn->receiveSequence)
510 conn->lastMessageTime = realtime;
511 conn->timeout = realtime + net_messagetimeout.value;
512 conn->receiveSequence++;
513 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
514 conn->receiveMessageLength += length;
515 if (flags & NETFLAG_EOM)
517 reliableMessagesReceived++;
518 length = conn->receiveMessageLength;
519 conn->receiveMessageLength = 0;
522 SZ_Clear(&net_message);
523 SZ_Write(&net_message, conn->receiveMessage, length);
530 receivedDuplicateCount++;
538 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
540 cls.netcon = NetConn_Open(mysocket, peeraddress);
541 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
544 cls.connect_trying = false;
545 cls.demonum = -1; // not in the demo loop now
546 cls.state = ca_connected;
547 cls.signon = 0; // need all the signon messages before playing
552 int NetConn_IsLocalGame(void)
555 if (cls.state == ca_connected && sv.active/* && LHNETADDRESS_GetAddressType(cl.netcon->peeraddress) == LHNETADDRESSTYPE_LOOP*/)
557 // make sure there are no other connected clients
558 for (i = 1;i < MAX_SCOREBOARD;i++)
559 if (svs.connectedclients[i])
569 lhnetaddress_t peeraddress;
571 pingcache[HOSTCACHESIZE];
573 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
576 lhnetaddress_t svaddress;
578 char *string, addressstring2[128], cname[128], ipstring[32];
579 char stringbuf[16384];
581 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
583 // received a command string - strip off the packaging and put it
584 // into our string buffer with NULL termination
587 length = min(length, (int)sizeof(stringbuf) - 1);
588 memcpy(stringbuf, data, length);
589 stringbuf[length] = 0;
592 if (developer.integer)
594 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
595 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
596 Com_HexDumpToConsole(data, length);
599 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
601 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
602 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
603 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
606 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
608 NetConn_ConnectionEstablished(mysocket, peeraddress);
611 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
613 cls.connect_trying = false;
615 length = max(length - 7, (int)sizeof(m_return_reason) - 1);
616 memcpy(m_return_reason, string, length);
617 m_return_reason[length] = 0;
618 Con_Printf("%s\n", m_return_reason);
621 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
623 int i, j, c, n, users, maxusers;
624 char game[32], mod[32], map[32], name[128];
628 // hostcache only uses text addresses
629 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
630 // search the cache for this server
631 for (n = 0; n < hostCacheCount; n++)
632 if (!strcmp(cname, hostcache[n].cname))
634 // add it or update it
635 if (n == hostCacheCount)
637 // if cache is full replace highest ping server (the list is
638 // kept sorted so this is always the last, and if this server
639 // is good it will be sorted into an early part of the list)
640 if (hostCacheCount >= HOSTCACHESIZE)
641 n = hostCacheCount - 1;
645 if ((s = SearchInfostring(string, "gamename" )) != NULL) strncpy(game, s, sizeof(game) - 1);else game[0] = 0;
646 if ((s = SearchInfostring(string, "modname" )) != NULL) strncpy(mod , s, sizeof(mod ) - 1);else mod[0] = 0;
647 if ((s = SearchInfostring(string, "mapname" )) != NULL) strncpy(map , s, sizeof(map ) - 1);else map[0] = 0;
648 if ((s = SearchInfostring(string, "hostname" )) != NULL) strncpy(name, s, sizeof(name) - 1);else name[0] = 0;
649 if ((s = SearchInfostring(string, "protocol" )) != NULL) c = atoi(s);else c = -1;
650 if ((s = SearchInfostring(string, "clients" )) != NULL) users = atoi(s);else users = 0;
651 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) maxusers = atoi(s);else maxusers = 0;
653 for (i = 0;i < HOSTCACHESIZE;i++)
654 if (!LHNETADDRESS_Compare(peeraddress, &pingcache[i].peeraddress))
655 pingtime = (int)(realtime - pingcache[i].senttime);
656 pingtime = bound(0, pingtime, 9999);
657 memset(&hostcache[n], 0, sizeof(hostcache[n]));
658 // store the data the engine cares about (address and ping)
659 strcpy(hostcache[n].cname, cname);
660 hostcache[n].ping = pingtime;
661 // build description strings for the things users care about
662 snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, c != NET_PROTOCOL_VERSION ? '*' : ' ', users, maxusers, name);
663 snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", cname, game, mod, map);
664 // if ping is especially high, display it as such
667 // orange numbers (lower block)
668 for (i = 0;i < 5;i++)
669 if (hostcache[n].line1[i] != ' ')
670 hostcache[n].line1[i] += 128;
672 else if (pingtime >= 200)
674 // yellow numbers (in upper block)
675 for (i = 0;i < 5;i++)
676 if (hostcache[n].line1[i] != ' ')
677 hostcache[n].line1[i] -= 30;
679 // if not in the slist menu we should print the server to console
680 if (m_state != m_slist)
681 Con_Printf("%s\n%s\n", hostcache[n].line1, hostcache[n].line2);
682 // and finally, re-sort the list
683 for (i = 0;i < hostCacheCount;i++)
685 for (j = i + 1;j < hostCacheCount;j++)
687 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
688 if (hostcache[i].ping > hostcache[j].ping)
690 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
691 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
692 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
698 if (!strncmp(string, "getserversResponse\\", 19) && hostCacheCount < HOSTCACHESIZE)
702 // Extract the IP addresses
705 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
707 sprintf(ipstring, "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
708 if (developer.integer)
709 Con_Printf("Requesting info from server %s\n", ipstring);
710 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
711 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
712 // replace oldest or matching entry in ping cache
713 // we scan this later when getting a reply to see how long it took
716 for (i = 0;i < HOSTCACHESIZE;i++)
718 if (!LHNETADDRESS_Compare(&svaddress, &pingcache[i].peeraddress))
723 if (besttime > pingcache[i].senttime)
725 besttime = pingcache[i].senttime;
727 // if ping cache isn't full yet we can skip out early
732 pingcache[best].peeraddress = svaddress;
733 pingcache[best].senttime = realtime;
734 // move on to next address in packet
741 if (!strncmp(string, "ping", 4))
743 if (developer.integer)
744 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
745 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
748 if (!strncmp(string, "ack", 3))
751 // we may not have liked the packet, but it was a command packet, so
752 // we're done processing this packet now
755 // netquake control packets, supported for compatibility only
756 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
761 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
765 if (developer.integer)
766 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
767 if (cls.connect_trying)
769 lhnetaddress_t clientportaddress;
770 clientportaddress = *peeraddress;
773 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
776 LHNETADDRESS_SetPort(&clientportaddress, port);
778 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
782 if (developer.integer)
783 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
784 Con_Printf("%s\n", data);
785 strncpy(m_return_reason, data, sizeof(m_return_reason) - 1);
788 case CCREP_SERVER_INFO:
789 if (developer.integer)
790 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
791 if (cls.state != ca_dedicated)
793 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
794 // string we just ignore it and keep the real address
796 // hostcache only uses text addresses
797 cname = UDP_AddrToString(readaddr);
798 // search the cache for this server
799 for (n = 0; n < hostCacheCount; n++)
800 if (!strcmp(cname, hostcache[n].cname))
803 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
806 memset(&hostcache[n], 0, sizeof(hostcache[n]));
807 strcpy(hostcache[n].name, MSG_ReadString());
808 strcpy(hostcache[n].map, MSG_ReadString());
809 hostcache[n].users = MSG_ReadByte();
810 hostcache[n].maxusers = MSG_ReadByte();
812 if (c != NET_PROTOCOL_VERSION)
814 strncpy(hostcache[n].cname, hostcache[n].name, sizeof(hostcache[n].cname) - 1);
815 hostcache[n].cname[sizeof(hostcache[n].cname) - 1] = 0;
816 strcpy(hostcache[n].name, "*");
817 strncat(hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name) - 1);
818 hostcache[n].name[sizeof(hostcache[n].name) - 1] = 0;
820 strcpy(hostcache[n].cname, cname);
824 case CCREP_PLAYER_INFO:
825 // we got a CCREP_PLAYER_INFO??
826 //if (developer.integer)
827 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
829 case CCREP_RULE_INFO:
830 // we got a CCREP_RULE_INFO??
831 //if (developer.integer)
832 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
838 // we may not have liked the packet, but it was a valid control
839 // packet, so we're done processing this packet now
843 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)
844 CL_ParseServerMessage();
848 void NetConn_ClientFrame(void)
851 lhnetaddress_t peeraddress;
853 NetConn_UpdateServerStuff();
854 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
856 if (cls.connect_remainingtries == 0)
858 cls.connect_trying = false;
859 Host_Error("Connect failed\n");
862 if (cls.connect_nextsendtime)
863 Con_Printf("Still trying...\n");
865 Con_Printf("Trying...\n");
866 cls.connect_nextsendtime = realtime + 1;
867 cls.connect_remainingtries--;
868 // try challenge first (newer server)
869 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
870 // then try netquake as a fallback (old server, or netquake)
871 SZ_Clear(&net_message);
872 // save space for the header, filled in later
873 MSG_WriteLong(&net_message, 0);
874 MSG_WriteByte(&net_message, CCREQ_CONNECT);
875 MSG_WriteString(&net_message, "QUAKE");
876 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
877 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
878 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
879 SZ_Clear(&net_message);
881 for (i = 0;i < cl_numsockets;i++)
882 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
883 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
884 if (cls.netcon && realtime > cls.netcon->timeout)
886 Con_Printf("Connection timed out\n");
889 for (conn = netconn_list;conn;conn = conn->next)
890 NetConn_ReSendMessage(conn);
893 #define MAX_CHALLENGES 128
896 lhnetaddress_t address;
900 challenge[MAX_CHALLENGES];
902 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
906 for (i = 0;i < bufferlength - 1;i++)
910 c = rand () % (127 - 33) + 33;
911 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
917 extern void SV_ConnectClient(int clientnum, netconn_t *netconnection);
918 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
920 int i, n, ret, clientnum, responselength, best, clientcount;
924 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
928 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
930 // received a command string - strip off the packaging and put it
931 // into our string buffer with NULL termination
934 length = min(length, (int)sizeof(stringbuf) - 1);
935 memcpy(stringbuf, data, length);
936 stringbuf[length] = 0;
939 if (developer.integer)
941 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
942 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
943 Com_HexDumpToConsole(data, length);
946 if (length >= 12 && !memcmp(string, "getchallenge", 12))
948 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
950 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
952 if (besttime > challenge[i].time)
953 besttime = challenge[best = i].time;
955 // if we did not find an exact match, choose the oldest and
956 // update address and string
957 if (i == MAX_CHALLENGES)
960 challenge[i].address = *peeraddress;
961 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
963 challenge[i].time = realtime;
964 // send the challenge
965 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
968 if (length > 8 && !memcmp(string, "connect\\", 8))
972 if ((s = SearchInfostring(string, "challenge")))
974 // validate the challenge
975 for (i = 0;i < MAX_CHALLENGES;i++)
976 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
978 if (i < MAX_CHALLENGES)
980 // check engine protocol
981 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
983 if (developer.integer)
984 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
985 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
989 // see if this is a duplicate connection request
990 for (clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
991 if ((client = svs.connectedclients[clientnum]) && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
993 if (clientnum < MAX_SCOREBOARD)
995 // duplicate connection request
996 if (realtime - client->netconnection->connecttime < 2.0)
998 // client is still trying to connect,
999 // so we send a duplicate reply
1000 if (developer.integer)
1001 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1002 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1004 // only kick if old connection seems dead
1005 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1007 // kick off connection and await retry
1008 client->deadsocket = true;
1013 // this is a new client, find a slot
1014 for (clientcount = 0, clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1015 if (svs.connectedclients[clientnum])
1017 for (clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1018 if (!svs.connectedclients[clientnum])
1020 if (clientcount < max(1, sv_maxplayers.integer) && clientnum < MAX_SCOREBOARD)
1022 // allocate and prepare the client struct
1023 if ((client = Mem_Alloc(sv_clients_mempool, sizeof(client_t))))
1025 if ((client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_clients_mempool)))
1027 if ((conn = NetConn_Open(mysocket, peeraddress)))
1029 // allocated connection
1030 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1031 if (developer.integer)
1032 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1033 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1034 // now set up the client struct
1035 svs.connectedclients[clientnum] = client;
1036 SV_ConnectClient(clientnum, conn);
1037 NetConn_Heartbeat(1);
1041 EntityFrame4_FreeDatabase(client->entitydatabase4);
1052 if (developer.integer)
1053 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1054 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1062 if (length >= 7 && !memcmp(string, "getinfo", 7))
1064 const char *challenge = NULL;
1065 // If there was a challenge in the getinfo message
1066 if (length > 8 && string[7] == ' ')
1067 challenge = string + 8;
1068 for (i = 0, n = 0;i < MAX_SCOREBOARD;i++)
1069 if (svs.connectedclients[i])
1071 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1072 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1073 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1074 gamename, com_modname, min(sv_maxplayers.integer, MAX_SCOREBOARD), n,
1075 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1076 // does it fit in the buffer?
1077 if (responselength < (int)sizeof(response))
1079 if (developer.integer)
1080 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1081 NetConn_WriteString(mysocket, response, peeraddress);
1086 if (!strncmp(string, "ping", 4))
1088 if (developer.integer)
1089 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1090 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1093 if (!strncmp(string, "ack", 3))
1096 // we may not have liked the packet, but it was a command packet, so
1097 // we're done processing this packet now
1100 // LordHavoc: disabled netquake control packet support in server
1104 // netquake control packets, supported for compatibility only
1105 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1110 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1114 //if (developer.integer)
1115 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1116 if (length >= (int)strlen("QUAKE") + 1 + 1)
1118 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1120 if (developer.integer)
1121 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1122 SZ_Clear(&net_message);
1123 // save space for the header, filled in later
1124 MSG_WriteLong(&net_message, 0);
1125 MSG_WriteByte(&net_message, CCREP_REJECT);
1126 MSG_WriteString(&net_message, "Incompatible version.\n");
1127 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1128 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1129 SZ_Clear(&net_message);
1133 // see if this is a duplicate connection request
1134 for (clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1135 if ((client = svs.connectedclients[clientnum]) && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1137 if (clientnum < MAX_SCOREBOARD)
1139 // duplicate connection request
1140 if (realtime - client->netconnection->connecttime < 2.0)
1142 // client is still trying to connect,
1143 // so we send a duplicate reply
1144 if (developer.integer)
1145 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1146 SZ_Clear(&net_message);
1147 // save space for the header, filled in later
1148 MSG_WriteLong(&net_message, 0);
1149 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1150 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1151 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1152 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1153 SZ_Clear(&net_message);
1155 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1157 // the old client hasn't sent us anything
1158 // in quite a while, so kick off and let
1159 // the retry take care of it...
1160 client->deadsocket = true;
1165 // this is a new client, find a slot
1166 for (clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1167 if (!(client = svs.connectedclients[clientnum]))
1169 // WARNING: this is broken code
1170 if (clientnum < MAX_SCOREBOARD && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1172 // connect to the client
1173 // everything is allocated, just fill in the details
1174 strcpy(conn->address, addressstring2);
1175 if (developer.integer)
1176 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1177 // send back the info about the server connection
1178 SZ_Clear(&net_message);
1179 // save space for the header, filled in later
1180 MSG_WriteLong(&net_message, 0);
1181 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1182 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1183 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1184 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1185 SZ_Clear(&net_message);
1186 // now set up the client struct
1187 SV_ConnectClient(clientnum, conn);
1188 NetConn_Heartbeat(1);
1192 //if (developer.integer)
1193 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1194 // no room; try to let player know
1195 SZ_Clear(&net_message);
1196 // save space for the header, filled in later
1197 MSG_WriteLong(&net_message, 0);
1198 MSG_WriteByte(&net_message, CCREP_REJECT);
1199 MSG_WriteString(&net_message, "Server is full.\n");
1200 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1201 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1202 SZ_Clear(&net_message);
1209 case CCREQ_SERVER_INFO:
1210 if (developer.integer)
1211 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1212 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1214 if (developer.integer)
1215 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1216 SZ_Clear(&net_message);
1217 // save space for the header, filled in later
1218 MSG_WriteLong(&net_message, 0);
1219 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1220 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1221 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1222 MSG_WriteString(&net_message, hostname.string);
1223 MSG_WriteString(&net_message, sv.name);
1224 MSG_WriteByte(&net_message, net_activeconnections);
1225 MSG_WriteByte(&net_message, min(sv_maxplayers.integer, MAX_SCOREBOARD));
1226 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1227 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1228 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1229 SZ_Clear(&net_message);
1232 case CCREQ_PLAYER_INFO:
1233 if (developer.integer)
1234 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1237 int playerNumber, activeNumber, clientNumber;
1240 playerNumber = MSG_ReadByte();
1242 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1243 if (client->active && ++activeNumber == playerNumber)
1245 if (clientNumber != svs.maxclients)
1247 SZ_Clear(&net_message);
1248 // save space for the header, filled in later
1249 MSG_WriteLong(&net_message, 0);
1250 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1251 MSG_WriteByte(&net_message, playerNumber);
1252 MSG_WriteString(&net_message, client->name);
1253 MSG_WriteLong(&net_message, client->colors);
1254 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1255 MSG_WriteLong(&net_message, (int)(realtime - client->netconnection->connecttime));
1256 MSG_WriteString(&net_message, client->netconnection->address);
1257 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1258 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1259 SZ_Clear(&net_message);
1263 case CCREQ_RULE_INFO:
1264 if (developer.integer)
1265 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1271 // find the search start location
1272 prevCvarName = MSG_ReadString();
1273 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1275 // send the response
1276 SZ_Clear(&net_message);
1277 // save space for the header, filled in later
1278 MSG_WriteLong(&net_message, 0);
1279 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1282 MSG_WriteString(&net_message, var->name);
1283 MSG_WriteString(&net_message, var->string);
1285 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1286 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1287 SZ_Clear(&net_message);
1294 // we may not have liked the packet, but it was a valid control
1295 // packet, so we're done processing this packet now
1300 for (i = 0;i < MAX_SCOREBOARD;i++)
1302 if ((host_client = svs.connectedclients[i]))
1304 if (host_client->netconnection)
1306 if (host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1308 sv_player = host_client->edict;
1309 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1310 SV_ReadClientMessage();
1316 Con_Printf("Removing client with no netconnection!\n");
1317 SV_DropClient(true);
1325 void NetConn_ServerFrame(void)
1328 lhnetaddress_t peeraddress;
1330 NetConn_UpdateServerStuff();
1331 for (i = 0;i < sv_numsockets;i++)
1332 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1333 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1334 for (i = 0;i < MAX_SCOREBOARD;i++)
1336 if ((host_client = svs.connectedclients[i]) && realtime > host_client->netconnection->timeout)
1338 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1339 sv_player = host_client->edict;
1340 SV_DropClient(false);
1343 for (conn = netconn_list;conn;conn = conn->next)
1344 NetConn_ReSendMessage(conn);
1347 void NetConn_QueryMasters(void)
1351 lhnetaddress_t masteraddress;
1354 if (hostCacheCount >= HOSTCACHESIZE)
1357 for (i = 0;i < cl_numsockets;i++)
1364 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1366 SZ_Clear(&net_message);
1367 // save space for the header, filled in later
1368 MSG_WriteLong(&net_message, 0);
1369 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1370 MSG_WriteString(&net_message, "QUAKE");
1371 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1372 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1373 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1374 SZ_Clear(&net_message);
1378 // build the getservers
1379 snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1382 for (masternum = 0;sv_masters[masternum].name;masternum++)
1383 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1384 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1389 void NetConn_Heartbeat(int priority)
1391 lhnetaddress_t masteraddress;
1393 lhnetsocket_t *mysocket;
1395 // if it's a state change (client connected), limit next heartbeat to no
1396 // more than 30 sec in the future
1397 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1398 nextheartbeattime = realtime + 30.0;
1400 // limit heartbeatperiod to 30 to 270 second range,
1401 // lower limit is to avoid abusing master servers with excess traffic,
1402 // upper limit is to avoid timing out on the master server (which uses
1404 if (sv_heartbeatperiod.value < 30)
1405 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1406 if (sv_heartbeatperiod.value > 270)
1407 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1409 // make advertising optional and don't advertise singleplayer games, and
1410 // only send a heartbeat as often as the admin wants
1411 if (sv.active && sv_public.integer && (!cl.islocalgame || sv_maxplayers.integer >= 2) && (priority > 1 || realtime > nextheartbeattime))
1413 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1414 for (masternum = 0;sv_masters[masternum].name;masternum++)
1415 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1416 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1420 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1423 qbyte sent[MAX_SCOREBOARD];
1425 memset(sent, 0, sizeof(sent));
1427 // simultaneously wait for the first CanSendMessage and send the message,
1428 // then wait for a second CanSendMessage (verifying it was received), or
1429 // the client drops and is no longer counted
1430 // the loop aborts when either it runs out of clients to send to, or a
1432 blocktime += Sys_DoubleTime();
1436 NetConn_ClientFrame();
1437 NetConn_ServerFrame();
1438 for (i = 0;i < MAX_SCOREBOARD;i++)
1440 if ((host_client = svs.connectedclients[i]))
1442 if (NetConn_CanSendMessage(host_client->netconnection))
1445 NetConn_SendReliableMessage(host_client->netconnection, data);
1448 if (!NetConn_CanSendMessage(host_client->netconnection))
1453 while (count && Sys_DoubleTime() < blocktime);
1457 static void Net_Heartbeat_f(void)
1459 NetConn_Heartbeat(2);
1462 void PrintStats(netconn_t *conn)
1464 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1467 void Net_Stats_f(void)
1470 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1471 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1472 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1473 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1474 Con_Printf("packetsSent = %i\n", packetsSent);
1475 Con_Printf("packetsReSent = %i\n", packetsReSent);
1476 Con_Printf("packetsReceived = %i\n", packetsReceived);
1477 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1478 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1479 Con_Printf("connections =\n");
1480 for (conn = netconn_list;conn;conn = conn->next)
1484 void Net_Slist_f(void)
1487 memset(&pingcache, 0, sizeof(pingcache));
1488 if (m_state != m_slist)
1489 Con_Printf("Sending requests to master servers\n");
1490 NetConn_QueryMasters();
1491 if (m_state != m_slist)
1492 Con_Printf("Listening for replies...\n");
1495 void NetConn_Init(void)
1498 netconn_mempool = Mem_AllocPool("Networking");
1499 Cmd_AddCommand("net_stats", Net_Stats_f);
1500 Cmd_AddCommand("net_slist", Net_Slist_f);
1501 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1502 Cvar_RegisterVariable(&net_messagetimeout);
1503 Cvar_RegisterVariable(&net_messagerejointimeout);
1504 Cvar_RegisterVariable(&net_connecttimeout);
1505 Cvar_RegisterVariable(&hostname);
1506 Cvar_RegisterVariable(&developer_networking);
1507 Cvar_RegisterVariable(&cl_netport);
1508 Cvar_RegisterVariable(&cl_netaddress);
1509 Cvar_RegisterVariable(&cl_netaddress_ipv6);
1510 Cvar_RegisterVariable(&sv_netport);
1511 Cvar_RegisterVariable(&sv_netaddress);
1512 Cvar_RegisterVariable(&sv_netaddress_ipv6);
1513 Cvar_RegisterVariable(&sv_public);
1514 Cvar_RegisterVariable(&sv_heartbeatperiod);
1515 for (masternum = 0;sv_masters[masternum].name;masternum++)
1516 Cvar_RegisterVariable(&sv_masters[masternum]);
1519 memset(&pingcache, 0, sizeof(pingcache));
1520 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1524 void NetConn_Shutdown(void)
1526 NetConn_CloseClientPorts();
1527 NetConn_CloseServerPorts();