2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 See the GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 #define MASTER_PORT 27950
28 cvar_t sv_public = {0, "sv_public", "0"};
29 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "180"};
31 static cvar_t sv_masters [] =
33 {CVAR_SAVE, "sv_master1", ""},
34 {CVAR_SAVE, "sv_master2", ""},
35 {CVAR_SAVE, "sv_master3", ""},
36 {CVAR_SAVE, "sv_master4", ""},
37 {0, "sv_masterextra1", "198.88.152.4"},
38 {0, "sv_masterextra2", "68.102.242.12"},
42 static double nextheartbeattime = 0;
44 sizebuf_t net_message;
46 cvar_t net_messagetimeout = {0, "net_messagetimeout","300"};
47 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10"};
48 cvar_t net_connecttimeout = {0, "net_connecttimeout","10"};
49 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED"};
50 cvar_t developer_networking = {0, "developer_networking", "0"};
52 cvar_t cl_fakelocalping_min = {0, "cl_fakelocalping_min","0"};
53 cvar_t cl_fakelocalping_max = {0, "cl_fakelocalping_max","0"};
54 static cvar_t cl_fakepacketloss_receive = {0, "cl_fakepacketloss_receive","0"};
55 static cvar_t cl_fakepacketloss_send = {0, "cl_fakepacketloss_send","0"};
56 static cvar_t sv_fakepacketloss_receive = {0, "sv_fakepacketloss_receive","0"};
57 static cvar_t sv_fakepacketloss_send = {0, "sv_fakepacketloss_send","0"};
60 /* statistic counters */
61 static int packetsSent = 0;
62 static int packetsReSent = 0;
63 static int packetsReceived = 0;
64 static int receivedDuplicateCount = 0;
65 static int droppedDatagrams = 0;
67 static int unreliableMessagesSent = 0;
68 static int unreliableMessagesReceived = 0;
69 static int reliableMessagesSent = 0;
70 static int reliableMessagesReceived = 0;
72 int hostCacheCount = 0;
73 hostcache_t hostcache[HOSTCACHESIZE];
75 static qbyte sendbuffer[NET_MAXMESSAGE];
76 static qbyte readbuffer[NET_MAXMESSAGE];
79 lhnetsocket_t *cl_sockets[16];
81 lhnetsocket_t *sv_sockets[16];
83 netconn_t *netconn_list = NULL;
84 mempool_t *netconn_mempool = NULL;
86 cvar_t cl_netport = {0, "cl_port", "0"};
87 cvar_t cl_netaddress = {0, "cl_netaddress", "0.0.0.0"};
88 cvar_t cl_netaddress_ipv6 = {0, "cl_netaddress_ipv6", "[0:0:0:0:0:0:0:0]:0"};
90 cvar_t sv_netport = {0, "port", "26000"};
91 cvar_t sv_netaddress = {0, "sv_netaddress", "0.0.0.0"};
92 cvar_t sv_netaddress_ipv6 = {0, "sv_netaddress_ipv6", "[0:0:0:0:0:0:0:0]:26000"};
94 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
96 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
98 if (cl_fakepacketloss_receive.integer)
99 for (i = 0;i < cl_numsockets;i++)
100 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_fakepacketloss_receive.integer)
102 if (sv_fakepacketloss_receive.integer)
103 for (i = 0;i < cl_numsockets;i++)
104 if (sv_sockets[i] == mysocket && (rand() % 100) < sv_fakepacketloss_receive.integer)
106 if (developer_networking.integer && length != 0)
108 char addressstring[128], addressstring2[128];
109 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
112 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
113 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
114 Com_HexDumpToConsole(data, length);
117 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
122 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
126 if (cl_fakepacketloss_send.integer)
127 for (i = 0;i < cl_numsockets;i++)
128 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_fakepacketloss_send.integer)
130 if (sv_fakepacketloss_send.integer)
131 for (i = 0;i < cl_numsockets;i++)
132 if (sv_sockets[i] == mysocket && (rand() % 100) < sv_fakepacketloss_send.integer)
134 ret = LHNET_Write(mysocket, data, length, peeraddress);
135 if (developer_networking.integer)
137 char addressstring[128], addressstring2[128];
138 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
139 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
140 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
141 Com_HexDumpToConsole(data, length);
146 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
148 // note this does not include the trailing NULL because we add that in the parser
149 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
152 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
154 unsigned int packetLen;
155 unsigned int dataLen;
157 unsigned int *header;
160 if (data->cursize == 0)
161 Sys_Error("Datagram_SendMessage: zero length message\n");
163 if (data->cursize > NET_MAXMESSAGE)
164 Sys_Error("Datagram_SendMessage: message too big %u\n", data->cursize);
166 if (conn->canSend == false)
167 Sys_Error("SendMessage: called with canSend == false\n");
170 memcpy(conn->sendMessage, data->data, data->cursize);
171 conn->sendMessageLength = data->cursize;
173 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
175 dataLen = conn->sendMessageLength;
180 dataLen = MAX_PACKETFRAGMENT;
184 packetLen = NET_HEADERSIZE + dataLen;
186 header = (void *)sendbuffer;
187 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
188 header[1] = BigLong(conn->sendSequence);
189 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
191 conn->sendSequence++;
192 conn->canSend = false;
194 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
197 conn->lastSendTime = realtime;
199 reliableMessagesSent++;
203 static void NetConn_SendMessageNext(netconn_t *conn)
205 unsigned int packetLen;
206 unsigned int dataLen;
208 unsigned int *header;
210 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
212 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
214 dataLen = conn->sendMessageLength;
219 dataLen = MAX_PACKETFRAGMENT;
223 packetLen = NET_HEADERSIZE + dataLen;
225 header = (void *)sendbuffer;
226 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
227 header[1] = BigLong(conn->sendSequence);
228 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
230 conn->sendSequence++;
231 conn->sendNext = false;
233 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
236 conn->lastSendTime = realtime;
241 static void NetConn_ReSendMessage(netconn_t *conn)
243 unsigned int packetLen;
244 unsigned int dataLen;
246 unsigned int *header;
248 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
250 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
252 dataLen = conn->sendMessageLength;
257 dataLen = MAX_PACKETFRAGMENT;
261 packetLen = NET_HEADERSIZE + dataLen;
263 header = (void *)sendbuffer;
264 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
265 header[1] = BigLong(conn->sendSequence - 1);
266 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
268 conn->sendNext = false;
270 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
273 conn->lastSendTime = realtime;
278 qboolean NetConn_CanSendMessage(netconn_t *conn)
280 return conn->canSend;
283 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
289 if (data->cursize == 0)
290 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
292 if (data->cursize > MAX_DATAGRAM)
293 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
296 packetLen = NET_HEADERSIZE + data->cursize;
298 header = (void *)sendbuffer;
299 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
300 header[1] = BigLong(conn->unreliableSendSequence);
301 memcpy(sendbuffer + 8, data->data, data->cursize);
303 conn->unreliableSendSequence++;
305 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
309 unreliableMessagesSent++;
313 void NetConn_CloseClientPorts(void)
315 for (;cl_numsockets > 0;cl_numsockets--)
316 if (cl_sockets[cl_numsockets - 1])
317 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
320 void NetConn_OpenClientPorts(void)
323 lhnetaddress_t address;
324 NetConn_CloseClientPorts();
325 port = bound(0, cl_netport.integer, 65535);
326 if (cl_netport.integer != port)
327 Cvar_SetValueQuick(&cl_netport, port);
328 LHNETADDRESS_FromString(&address, "local", port);
329 cl_sockets[cl_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
330 LHNETADDRESS_FromString(&address, cl_netaddress.string, port);
331 cl_sockets[cl_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
332 LHNETADDRESS_FromString(&address, cl_netaddress_ipv6.string, port);
333 cl_sockets[cl_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
336 void NetConn_CloseServerPorts(void)
338 for (;sv_numsockets > 0;sv_numsockets--)
339 if (sv_sockets[sv_numsockets - 1])
340 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
343 void NetConn_OpenServerPorts(int opennetports)
346 lhnetaddress_t address;
347 NetConn_CloseServerPorts();
348 port = bound(0, sv_netport.integer, 65535);
351 if (sv_netport.integer != port)
352 Cvar_SetValueQuick(&sv_netport, port);
353 LHNETADDRESS_FromString(&address, "local", port);
354 sv_sockets[sv_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
357 LHNETADDRESS_FromString(&address, sv_netaddress.string, port);
358 sv_sockets[sv_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
359 LHNETADDRESS_FromString(&address, sv_netaddress_ipv6.string, port);
360 sv_sockets[sv_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
364 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
366 int i, a = LHNETADDRESS_GetAddressType(address);
367 for (i = 0;i < cl_numsockets;i++)
368 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
369 return cl_sockets[i];
373 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
375 int i, a = LHNETADDRESS_GetAddressType(address);
376 for (i = 0;i < sv_numsockets;i++)
377 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
378 return sv_sockets[i];
382 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
385 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
386 conn->mysocket = mysocket;
387 conn->peeraddress = *peeraddress;
388 conn->canSend = true;
389 conn->connecttime = realtime;
390 conn->lastMessageTime = realtime;
391 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
392 // reduce effectiveness of connection request floods
393 conn->timeout = realtime + net_connecttimeout.value;
394 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
395 conn->next = netconn_list;
400 void NetConn_Close(netconn_t *conn)
403 // remove connection from list
404 if (conn == netconn_list)
405 netconn_list = conn->next;
408 for (c = netconn_list;c;c = c->next)
412 c->next = conn->next;
416 // not found in list, we'll avoid crashing here...
424 static int clientport = -1;
425 static int clientport2 = -1;
426 static int hostport = -1;
427 static void NetConn_UpdateServerStuff(void)
429 if (clientport2 != cl_netport.integer)
431 clientport2 = cl_netport.integer;
432 if (cls.state == ca_connected)
433 Con_Printf("Changing \"cl_port\" will not take effect until you reconnect.\n");
435 if (cls.state != ca_dedicated)
437 if (cls.state == ca_disconnected && clientport != cl_netport.integer)
439 clientport = cl_netport.integer;
440 NetConn_CloseClientPorts();
442 if (cl_numsockets == 0)
443 NetConn_OpenClientPorts();
446 if (hostport != sv_netport.integer)
448 hostport = sv_netport.integer;
450 Con_Printf("Changing \"port\" will not take effect until \"map\" command is executed.\n");
454 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
458 unsigned int sequence;
462 length = BigLong(((int *)data)[0]);
463 flags = length & ~NETFLAG_LENGTH_MASK;
464 length &= NETFLAG_LENGTH_MASK;
465 // control packets were already handled
466 if (!(flags & NETFLAG_CTL))
468 sequence = BigLong(((int *)data)[1]);
472 if (flags & NETFLAG_UNRELIABLE)
474 if (sequence >= conn->unreliableReceiveSequence)
476 if (sequence > conn->unreliableReceiveSequence)
478 count = sequence - conn->unreliableReceiveSequence;
479 droppedDatagrams += count;
480 Con_DPrintf("Dropped %u datagram(s)\n", count);
482 conn->unreliableReceiveSequence = sequence + 1;
483 conn->lastMessageTime = realtime;
484 conn->timeout = realtime + net_messagetimeout.value;
485 unreliableMessagesReceived++;
488 SZ_Clear(&net_message);
489 SZ_Write(&net_message, data, length);
495 Con_DPrintf("Got a stale datagram\n");
498 else if (flags & NETFLAG_ACK)
500 if (sequence == (conn->sendSequence - 1))
502 if (sequence == conn->ackSequence)
505 if (conn->ackSequence != conn->sendSequence)
506 Con_DPrintf("ack sequencing error\n");
507 conn->lastMessageTime = realtime;
508 conn->timeout = realtime + net_messagetimeout.value;
509 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
510 if (conn->sendMessageLength > 0)
512 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
513 conn->sendNext = true;
514 NetConn_SendMessageNext(conn);
518 conn->sendMessageLength = 0;
519 conn->canSend = true;
523 Con_DPrintf("Duplicate ACK received\n");
526 Con_DPrintf("Stale ACK received\n");
529 else if (flags & NETFLAG_DATA)
531 unsigned int temppacket[2];
532 temppacket[0] = BigLong(8 | NETFLAG_ACK);
533 temppacket[1] = BigLong(sequence);
534 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
535 if (sequence == conn->receiveSequence)
537 conn->lastMessageTime = realtime;
538 conn->timeout = realtime + net_messagetimeout.value;
539 conn->receiveSequence++;
540 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
541 conn->receiveMessageLength += length;
542 if (flags & NETFLAG_EOM)
544 reliableMessagesReceived++;
545 length = conn->receiveMessageLength;
546 conn->receiveMessageLength = 0;
549 SZ_Clear(&net_message);
550 SZ_Write(&net_message, conn->receiveMessage, length);
557 receivedDuplicateCount++;
565 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
567 cls.netcon = NetConn_Open(mysocket, peeraddress);
568 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
571 cls.connect_trying = false;
572 cls.demonum = -1; // not in the demo loop now
573 cls.state = ca_connected;
574 cls.signon = 0; // need all the signon messages before playing
579 int NetConn_IsLocalGame(void)
582 if (cls.state == ca_connected && sv.active/* && LHNETADDRESS_GetAddressType(cl.netcon->peeraddress) == LHNETADDRESSTYPE_LOOP*/)
584 // make sure there are no other connected clients
585 for (i = 1;i < MAX_SCOREBOARD;i++)
586 if (svs.connectedclients[i])
596 lhnetaddress_t peeraddress;
598 pingcache[HOSTCACHESIZE];
600 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
603 lhnetaddress_t svaddress;
605 char *string, addressstring2[128], cname[128], ipstring[32];
606 char stringbuf[16384];
608 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
610 // received a command string - strip off the packaging and put it
611 // into our string buffer with NULL termination
614 length = min(length, (int)sizeof(stringbuf) - 1);
615 memcpy(stringbuf, data, length);
616 stringbuf[length] = 0;
619 if (developer.integer)
621 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
622 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
623 Com_HexDumpToConsole(data, length);
626 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
628 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
629 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
630 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
633 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
635 NetConn_ConnectionEstablished(mysocket, peeraddress);
638 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
640 cls.connect_trying = false;
642 length = max(length - 7, (int)sizeof(m_return_reason) - 1);
643 memcpy(m_return_reason, string, length);
644 m_return_reason[length] = 0;
645 Con_Printf("%s\n", m_return_reason);
648 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
650 int i, j, c, n, users, maxusers;
651 char game[32], mod[32], map[32], name[128];
655 // hostcache only uses text addresses
656 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
657 // search the cache for this server
658 for (n = 0; n < hostCacheCount; n++)
659 if (!strcmp(cname, hostcache[n].cname))
661 // add it or update it
662 if (n == hostCacheCount)
664 // if cache is full replace highest ping server (the list is
665 // kept sorted so this is always the last, and if this server
666 // is good it will be sorted into an early part of the list)
667 if (hostCacheCount >= HOSTCACHESIZE)
668 n = hostCacheCount - 1;
672 if ((s = SearchInfostring(string, "gamename" )) != NULL) strncpy(game, s, sizeof(game) - 1);else game[0] = 0;
673 if ((s = SearchInfostring(string, "modname" )) != NULL) strncpy(mod , s, sizeof(mod ) - 1);else mod[0] = 0;
674 if ((s = SearchInfostring(string, "mapname" )) != NULL) strncpy(map , s, sizeof(map ) - 1);else map[0] = 0;
675 if ((s = SearchInfostring(string, "hostname" )) != NULL) strncpy(name, s, sizeof(name) - 1);else name[0] = 0;
676 if ((s = SearchInfostring(string, "protocol" )) != NULL) c = atoi(s);else c = -1;
677 if ((s = SearchInfostring(string, "clients" )) != NULL) users = atoi(s);else users = 0;
678 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) maxusers = atoi(s);else maxusers = 0;
680 for (i = 0;i < HOSTCACHESIZE;i++)
681 if (!LHNETADDRESS_Compare(peeraddress, &pingcache[i].peeraddress))
682 pingtime = (int)(realtime - pingcache[i].senttime);
683 pingtime = bound(0, pingtime, 9999);
684 memset(&hostcache[n], 0, sizeof(hostcache[n]));
685 // store the data the engine cares about (address and ping)
686 strcpy(hostcache[n].cname, cname);
687 hostcache[n].ping = pingtime;
688 // build description strings for the things users care about
689 snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, c != NET_PROTOCOL_VERSION ? '*' : ' ', users, maxusers, name);
690 snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", cname, game, mod, map);
691 // if ping is especially high, display it as such
694 // orange numbers (lower block)
695 for (i = 0;i < 5;i++)
696 if (hostcache[n].line1[i] != ' ')
697 hostcache[n].line1[i] += 128;
699 else if (pingtime >= 200)
701 // yellow numbers (in upper block)
702 for (i = 0;i < 5;i++)
703 if (hostcache[n].line1[i] != ' ')
704 hostcache[n].line1[i] -= 30;
706 // if not in the slist menu we should print the server to console
707 if (m_state != m_slist)
708 Con_Printf("%s\n%s\n", hostcache[n].line1, hostcache[n].line2);
709 // and finally, re-sort the list
710 for (i = 0;i < hostCacheCount;i++)
712 for (j = i + 1;j < hostCacheCount;j++)
714 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
715 if (hostcache[i].ping > hostcache[j].ping)
717 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
718 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
719 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
725 if (!strncmp(string, "getserversResponse\\", 19) && hostCacheCount < HOSTCACHESIZE)
729 // Extract the IP addresses
732 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
734 sprintf(ipstring, "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
735 if (developer.integer)
736 Con_Printf("Requesting info from server %s\n", ipstring);
737 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
738 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
739 // replace oldest or matching entry in ping cache
740 // we scan this later when getting a reply to see how long it took
743 for (i = 0;i < HOSTCACHESIZE;i++)
745 if (!LHNETADDRESS_Compare(&svaddress, &pingcache[i].peeraddress))
750 if (besttime > pingcache[i].senttime)
752 besttime = pingcache[i].senttime;
754 // if ping cache isn't full yet we can skip out early
759 pingcache[best].peeraddress = svaddress;
760 pingcache[best].senttime = realtime;
761 // move on to next address in packet
768 if (!strncmp(string, "ping", 4))
770 if (developer.integer)
771 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
772 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
775 if (!strncmp(string, "ack", 3))
778 // we may not have liked the packet, but it was a command packet, so
779 // we're done processing this packet now
782 // netquake control packets, supported for compatibility only
783 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
788 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
792 if (developer.integer)
793 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
794 if (cls.connect_trying)
796 lhnetaddress_t clientportaddress;
797 clientportaddress = *peeraddress;
800 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
803 LHNETADDRESS_SetPort(&clientportaddress, port);
805 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
809 if (developer.integer)
810 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
811 Con_Printf("%s\n", data);
812 strncpy(m_return_reason, data, sizeof(m_return_reason) - 1);
815 case CCREP_SERVER_INFO:
816 if (developer.integer)
817 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
818 if (cls.state != ca_dedicated)
820 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
821 // string we just ignore it and keep the real address
823 // hostcache only uses text addresses
824 cname = UDP_AddrToString(readaddr);
825 // search the cache for this server
826 for (n = 0; n < hostCacheCount; n++)
827 if (!strcmp(cname, hostcache[n].cname))
830 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
833 memset(&hostcache[n], 0, sizeof(hostcache[n]));
834 strcpy(hostcache[n].name, MSG_ReadString());
835 strcpy(hostcache[n].map, MSG_ReadString());
836 hostcache[n].users = MSG_ReadByte();
837 hostcache[n].maxusers = MSG_ReadByte();
839 if (c != NET_PROTOCOL_VERSION)
841 strncpy(hostcache[n].cname, hostcache[n].name, sizeof(hostcache[n].cname) - 1);
842 hostcache[n].cname[sizeof(hostcache[n].cname) - 1] = 0;
843 strcpy(hostcache[n].name, "*");
844 strncat(hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name) - 1);
845 hostcache[n].name[sizeof(hostcache[n].name) - 1] = 0;
847 strcpy(hostcache[n].cname, cname);
851 case CCREP_PLAYER_INFO:
852 // we got a CCREP_PLAYER_INFO??
853 //if (developer.integer)
854 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
856 case CCREP_RULE_INFO:
857 // we got a CCREP_RULE_INFO??
858 //if (developer.integer)
859 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
865 // we may not have liked the packet, but it was a valid control
866 // packet, so we're done processing this packet now
870 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)
871 CL_ParseServerMessage();
875 void NetConn_ClientFrame(void)
878 lhnetaddress_t peeraddress;
880 NetConn_UpdateServerStuff();
881 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
883 if (cls.connect_remainingtries == 0)
885 cls.connect_trying = false;
886 Host_Error("Connect failed\n");
889 if (cls.connect_nextsendtime)
890 Con_Printf("Still trying...\n");
892 Con_Printf("Trying...\n");
893 cls.connect_nextsendtime = realtime + 1;
894 cls.connect_remainingtries--;
895 // try challenge first (newer server)
896 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
897 // then try netquake as a fallback (old server, or netquake)
898 SZ_Clear(&net_message);
899 // save space for the header, filled in later
900 MSG_WriteLong(&net_message, 0);
901 MSG_WriteByte(&net_message, CCREQ_CONNECT);
902 MSG_WriteString(&net_message, "QUAKE");
903 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
904 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
905 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
906 SZ_Clear(&net_message);
908 for (i = 0;i < cl_numsockets;i++)
909 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
910 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
911 if (cls.netcon && realtime > cls.netcon->timeout)
913 Con_Printf("Connection timed out\n");
916 for (conn = netconn_list;conn;conn = conn->next)
917 NetConn_ReSendMessage(conn);
920 #define MAX_CHALLENGES 128
923 lhnetaddress_t address;
927 challenge[MAX_CHALLENGES];
929 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
933 for (i = 0;i < bufferlength - 1;i++)
937 c = rand () % (127 - 33) + 33;
938 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
944 extern void SV_ConnectClient(int clientnum, netconn_t *netconnection);
945 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
947 int i, n, ret, clientnum, responselength, best, clientcount;
951 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
955 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
957 // received a command string - strip off the packaging and put it
958 // into our string buffer with NULL termination
961 length = min(length, (int)sizeof(stringbuf) - 1);
962 memcpy(stringbuf, data, length);
963 stringbuf[length] = 0;
966 if (developer.integer)
968 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
969 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
970 Com_HexDumpToConsole(data, length);
973 if (length >= 12 && !memcmp(string, "getchallenge", 12))
975 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
977 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
979 if (besttime > challenge[i].time)
980 besttime = challenge[best = i].time;
982 // if we did not find an exact match, choose the oldest and
983 // update address and string
984 if (i == MAX_CHALLENGES)
987 challenge[i].address = *peeraddress;
988 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
990 challenge[i].time = realtime;
991 // send the challenge
992 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
995 if (length > 8 && !memcmp(string, "connect\\", 8))
999 if ((s = SearchInfostring(string, "challenge")))
1001 // validate the challenge
1002 for (i = 0;i < MAX_CHALLENGES;i++)
1003 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1005 if (i < MAX_CHALLENGES)
1007 // check engine protocol
1008 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1010 if (developer.integer)
1011 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1012 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1016 // see if this is a duplicate connection request
1017 for (clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1018 if ((client = svs.connectedclients[clientnum]) && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1020 if (clientnum < MAX_SCOREBOARD)
1022 // duplicate connection request
1023 if (realtime - client->netconnection->connecttime < 2.0)
1025 // client is still trying to connect,
1026 // so we send a duplicate reply
1027 if (developer.integer)
1028 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1029 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1031 // only kick if old connection seems dead
1032 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1034 // kick off connection and await retry
1035 client->deadsocket = true;
1040 // this is a new client, find a slot
1041 for (clientcount = 0, clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1042 if (svs.connectedclients[clientnum])
1044 for (clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1045 if (!svs.connectedclients[clientnum])
1047 if (clientcount < max(1, sv_maxplayers.integer) && clientnum < MAX_SCOREBOARD)
1049 // allocate and prepare the client struct
1050 if ((client = Mem_Alloc(sv_clients_mempool, sizeof(client_t))))
1052 if ((client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_clients_mempool)))
1054 if ((conn = NetConn_Open(mysocket, peeraddress)))
1056 // allocated connection
1057 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1058 if (developer.integer)
1059 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1060 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1061 // now set up the client struct
1062 svs.connectedclients[clientnum] = client;
1063 SV_ConnectClient(clientnum, conn);
1064 NetConn_Heartbeat(1);
1068 EntityFrame4_FreeDatabase(client->entitydatabase4);
1079 if (developer.integer)
1080 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1081 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1089 if (length >= 7 && !memcmp(string, "getinfo", 7))
1091 const char *challenge = NULL;
1092 // If there was a challenge in the getinfo message
1093 if (length > 8 && string[7] == ' ')
1094 challenge = string + 8;
1095 for (i = 0, n = 0;i < MAX_SCOREBOARD;i++)
1096 if (svs.connectedclients[i])
1098 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1099 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1100 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1101 gamename, com_modname, min(sv_maxplayers.integer, MAX_SCOREBOARD), n,
1102 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1103 // does it fit in the buffer?
1104 if (responselength < (int)sizeof(response))
1106 if (developer.integer)
1107 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1108 NetConn_WriteString(mysocket, response, peeraddress);
1113 if (!strncmp(string, "ping", 4))
1115 if (developer.integer)
1116 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1117 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1120 if (!strncmp(string, "ack", 3))
1123 // we may not have liked the packet, but it was a command packet, so
1124 // we're done processing this packet now
1127 // LordHavoc: disabled netquake control packet support in server
1131 // netquake control packets, supported for compatibility only
1132 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1137 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1141 //if (developer.integer)
1142 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1143 if (length >= (int)strlen("QUAKE") + 1 + 1)
1145 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1147 if (developer.integer)
1148 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1149 SZ_Clear(&net_message);
1150 // save space for the header, filled in later
1151 MSG_WriteLong(&net_message, 0);
1152 MSG_WriteByte(&net_message, CCREP_REJECT);
1153 MSG_WriteString(&net_message, "Incompatible version.\n");
1154 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1155 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1156 SZ_Clear(&net_message);
1160 // see if this is a duplicate connection request
1161 for (clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1162 if ((client = svs.connectedclients[clientnum]) && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1164 if (clientnum < MAX_SCOREBOARD)
1166 // duplicate connection request
1167 if (realtime - client->netconnection->connecttime < 2.0)
1169 // client is still trying to connect,
1170 // so we send a duplicate reply
1171 if (developer.integer)
1172 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1173 SZ_Clear(&net_message);
1174 // save space for the header, filled in later
1175 MSG_WriteLong(&net_message, 0);
1176 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1177 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1178 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1179 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1180 SZ_Clear(&net_message);
1182 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1184 // the old client hasn't sent us anything
1185 // in quite a while, so kick off and let
1186 // the retry take care of it...
1187 client->deadsocket = true;
1192 // this is a new client, find a slot
1193 for (clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1194 if (!(client = svs.connectedclients[clientnum]))
1196 // WARNING: this is broken code
1197 if (clientnum < MAX_SCOREBOARD && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1199 // connect to the client
1200 // everything is allocated, just fill in the details
1201 strcpy(conn->address, addressstring2);
1202 if (developer.integer)
1203 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1204 // send back the info about the server connection
1205 SZ_Clear(&net_message);
1206 // save space for the header, filled in later
1207 MSG_WriteLong(&net_message, 0);
1208 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1209 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1210 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1211 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1212 SZ_Clear(&net_message);
1213 // now set up the client struct
1214 SV_ConnectClient(clientnum, conn);
1215 NetConn_Heartbeat(1);
1219 //if (developer.integer)
1220 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1221 // no room; try to let player know
1222 SZ_Clear(&net_message);
1223 // save space for the header, filled in later
1224 MSG_WriteLong(&net_message, 0);
1225 MSG_WriteByte(&net_message, CCREP_REJECT);
1226 MSG_WriteString(&net_message, "Server is full.\n");
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);
1236 case CCREQ_SERVER_INFO:
1237 if (developer.integer)
1238 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1239 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1241 if (developer.integer)
1242 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1243 SZ_Clear(&net_message);
1244 // save space for the header, filled in later
1245 MSG_WriteLong(&net_message, 0);
1246 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1247 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1248 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1249 MSG_WriteString(&net_message, hostname.string);
1250 MSG_WriteString(&net_message, sv.name);
1251 MSG_WriteByte(&net_message, net_activeconnections);
1252 MSG_WriteByte(&net_message, min(sv_maxplayers.integer, MAX_SCOREBOARD));
1253 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1254 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1255 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1256 SZ_Clear(&net_message);
1259 case CCREQ_PLAYER_INFO:
1260 if (developer.integer)
1261 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1264 int playerNumber, activeNumber, clientNumber;
1267 playerNumber = MSG_ReadByte();
1269 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1270 if (client->active && ++activeNumber == playerNumber)
1272 if (clientNumber != svs.maxclients)
1274 SZ_Clear(&net_message);
1275 // save space for the header, filled in later
1276 MSG_WriteLong(&net_message, 0);
1277 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1278 MSG_WriteByte(&net_message, playerNumber);
1279 MSG_WriteString(&net_message, client->name);
1280 MSG_WriteLong(&net_message, client->colors);
1281 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1282 MSG_WriteLong(&net_message, (int)(realtime - client->netconnection->connecttime));
1283 MSG_WriteString(&net_message, client->netconnection->address);
1284 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1285 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1286 SZ_Clear(&net_message);
1290 case CCREQ_RULE_INFO:
1291 if (developer.integer)
1292 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1298 // find the search start location
1299 prevCvarName = MSG_ReadString();
1300 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1302 // send the response
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_RULE_INFO);
1309 MSG_WriteString(&net_message, var->name);
1310 MSG_WriteString(&net_message, var->string);
1312 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1313 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1314 SZ_Clear(&net_message);
1321 // we may not have liked the packet, but it was a valid control
1322 // packet, so we're done processing this packet now
1327 for (i = 0;i < MAX_SCOREBOARD;i++)
1329 if ((host_client = svs.connectedclients[i]))
1331 if (host_client->netconnection)
1333 if (host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1335 sv_player = host_client->edict;
1336 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1337 SV_ReadClientMessage();
1343 Con_Printf("Removing client with no netconnection!\n");
1344 SV_DropClient(true);
1352 void NetConn_ServerFrame(void)
1355 lhnetaddress_t peeraddress;
1357 NetConn_UpdateServerStuff();
1358 for (i = 0;i < sv_numsockets;i++)
1359 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1360 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1361 for (i = 0;i < MAX_SCOREBOARD;i++)
1363 if ((host_client = svs.connectedclients[i]) && realtime > host_client->netconnection->timeout)
1365 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1366 sv_player = host_client->edict;
1367 SV_DropClient(false);
1370 for (conn = netconn_list;conn;conn = conn->next)
1371 NetConn_ReSendMessage(conn);
1374 void NetConn_QueryMasters(void)
1378 lhnetaddress_t masteraddress;
1381 if (hostCacheCount >= HOSTCACHESIZE)
1384 for (i = 0;i < cl_numsockets;i++)
1391 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1393 SZ_Clear(&net_message);
1394 // save space for the header, filled in later
1395 MSG_WriteLong(&net_message, 0);
1396 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1397 MSG_WriteString(&net_message, "QUAKE");
1398 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1399 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1400 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1401 SZ_Clear(&net_message);
1405 // build the getservers
1406 snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1409 for (masternum = 0;sv_masters[masternum].name;masternum++)
1410 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1411 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1416 void NetConn_Heartbeat(int priority)
1418 lhnetaddress_t masteraddress;
1420 lhnetsocket_t *mysocket;
1422 // if it's a state change (client connected), limit next heartbeat to no
1423 // more than 30 sec in the future
1424 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1425 nextheartbeattime = realtime + 30.0;
1427 // limit heartbeatperiod to 30 to 270 second range,
1428 // lower limit is to avoid abusing master servers with excess traffic,
1429 // upper limit is to avoid timing out on the master server (which uses
1431 if (sv_heartbeatperiod.value < 30)
1432 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1433 if (sv_heartbeatperiod.value > 270)
1434 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1436 // make advertising optional and don't advertise singleplayer games, and
1437 // only send a heartbeat as often as the admin wants
1438 if (sv.active && sv_public.integer && (!cl.islocalgame || sv_maxplayers.integer >= 2) && (priority > 1 || realtime > nextheartbeattime))
1440 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1441 for (masternum = 0;sv_masters[masternum].name;masternum++)
1442 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1443 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1447 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1450 qbyte sent[MAX_SCOREBOARD];
1452 memset(sent, 0, sizeof(sent));
1454 // simultaneously wait for the first CanSendMessage and send the message,
1455 // then wait for a second CanSendMessage (verifying it was received), or
1456 // the client drops and is no longer counted
1457 // the loop aborts when either it runs out of clients to send to, or a
1459 blocktime += Sys_DoubleTime();
1463 NetConn_ClientFrame();
1464 NetConn_ServerFrame();
1465 for (i = 0;i < MAX_SCOREBOARD;i++)
1467 if ((host_client = svs.connectedclients[i]))
1469 if (NetConn_CanSendMessage(host_client->netconnection))
1472 NetConn_SendReliableMessage(host_client->netconnection, data);
1475 if (!NetConn_CanSendMessage(host_client->netconnection))
1480 while (count && Sys_DoubleTime() < blocktime);
1484 static void Net_Heartbeat_f(void)
1486 NetConn_Heartbeat(2);
1489 void PrintStats(netconn_t *conn)
1491 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1494 void Net_Stats_f(void)
1497 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1498 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1499 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1500 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1501 Con_Printf("packetsSent = %i\n", packetsSent);
1502 Con_Printf("packetsReSent = %i\n", packetsReSent);
1503 Con_Printf("packetsReceived = %i\n", packetsReceived);
1504 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1505 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1506 Con_Printf("connections =\n");
1507 for (conn = netconn_list;conn;conn = conn->next)
1511 void Net_Slist_f(void)
1514 memset(&pingcache, 0, sizeof(pingcache));
1515 if (m_state != m_slist)
1516 Con_Printf("Sending requests to master servers\n");
1517 NetConn_QueryMasters();
1518 if (m_state != m_slist)
1519 Con_Printf("Listening for replies...\n");
1522 void NetConn_Init(void)
1525 netconn_mempool = Mem_AllocPool("Networking");
1526 Cmd_AddCommand("net_stats", Net_Stats_f);
1527 Cmd_AddCommand("net_slist", Net_Slist_f);
1528 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1529 Cvar_RegisterVariable(&net_messagetimeout);
1530 Cvar_RegisterVariable(&net_messagerejointimeout);
1531 Cvar_RegisterVariable(&net_connecttimeout);
1532 Cvar_RegisterVariable(&cl_fakelocalping_min);
1533 Cvar_RegisterVariable(&cl_fakelocalping_max);
1534 Cvar_RegisterVariable(&cl_fakepacketloss_receive);
1535 Cvar_RegisterVariable(&cl_fakepacketloss_send);
1536 Cvar_RegisterVariable(&sv_fakepacketloss_receive);
1537 Cvar_RegisterVariable(&sv_fakepacketloss_send);
1538 Cvar_RegisterVariable(&hostname);
1539 Cvar_RegisterVariable(&developer_networking);
1540 Cvar_RegisterVariable(&cl_netport);
1541 Cvar_RegisterVariable(&cl_netaddress);
1542 Cvar_RegisterVariable(&cl_netaddress_ipv6);
1543 Cvar_RegisterVariable(&sv_netport);
1544 Cvar_RegisterVariable(&sv_netaddress);
1545 Cvar_RegisterVariable(&sv_netaddress_ipv6);
1546 Cvar_RegisterVariable(&sv_public);
1547 Cvar_RegisterVariable(&sv_heartbeatperiod);
1548 for (masternum = 0;sv_masters[masternum].name;masternum++)
1549 Cvar_RegisterVariable(&sv_masters[masternum]);
1552 memset(&pingcache, 0, sizeof(pingcache));
1553 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1557 void NetConn_Shutdown(void)
1559 NetConn_CloseClientPorts();
1560 NetConn_CloseServerPorts();