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", "69.59.212.88"},
41 static double nextheartbeattime = 0;
43 sizebuf_t net_message;
45 cvar_t net_messagetimeout = {0, "net_messagetimeout","300"};
46 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10"};
47 cvar_t net_connecttimeout = {0, "net_connecttimeout","10"};
48 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED"};
49 cvar_t developer_networking = {0, "developer_networking", "0"};
51 cvar_t cl_fakelocalping_min = {0, "cl_fakelocalping_min","0"};
52 cvar_t cl_fakelocalping_max = {0, "cl_fakelocalping_max","0"};
53 static cvar_t cl_fakepacketloss_receive = {0, "cl_fakepacketloss_receive","0"};
54 static cvar_t cl_fakepacketloss_send = {0, "cl_fakepacketloss_send","0"};
55 static cvar_t sv_fakepacketloss_receive = {0, "sv_fakepacketloss_receive","0"};
56 static cvar_t sv_fakepacketloss_send = {0, "sv_fakepacketloss_send","0"};
59 /* statistic counters */
60 static int packetsSent = 0;
61 static int packetsReSent = 0;
62 static int packetsReceived = 0;
63 static int receivedDuplicateCount = 0;
64 static int droppedDatagrams = 0;
66 static int unreliableMessagesSent = 0;
67 static int unreliableMessagesReceived = 0;
68 static int reliableMessagesSent = 0;
69 static int reliableMessagesReceived = 0;
71 double masterquerytime = -1000;
72 int masterquerycount = 0;
73 int masterreplycount = 0;
74 int serverquerycount = 0;
75 int serverreplycount = 0;
77 int hostCacheCount = 0;
78 hostcache_t hostcache[HOSTCACHESIZE];
80 static qbyte sendbuffer[NET_MAXMESSAGE];
81 static qbyte readbuffer[NET_MAXMESSAGE];
84 lhnetsocket_t *cl_sockets[16];
86 lhnetsocket_t *sv_sockets[16];
88 netconn_t *netconn_list = NULL;
89 mempool_t *netconn_mempool = NULL;
91 cvar_t cl_netport = {0, "cl_port", "0"};
92 cvar_t sv_netport = {0, "port", "26000"};
93 cvar_t net_address = {0, "net_address", "0.0.0.0"};
94 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]"};
96 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
98 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
100 if (cl_fakepacketloss_receive.integer)
101 for (i = 0;i < cl_numsockets;i++)
102 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_fakepacketloss_receive.integer)
104 if (sv_fakepacketloss_receive.integer)
105 for (i = 0;i < cl_numsockets;i++)
106 if (sv_sockets[i] == mysocket && (rand() % 100) < sv_fakepacketloss_receive.integer)
108 if (developer_networking.integer && length != 0)
110 char addressstring[128], addressstring2[128];
111 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
114 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
115 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
116 Com_HexDumpToConsole(data, length);
119 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
124 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
128 if (cl_fakepacketloss_send.integer)
129 for (i = 0;i < cl_numsockets;i++)
130 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_fakepacketloss_send.integer)
132 if (sv_fakepacketloss_send.integer)
133 for (i = 0;i < cl_numsockets;i++)
134 if (sv_sockets[i] == mysocket && (rand() % 100) < sv_fakepacketloss_send.integer)
136 ret = LHNET_Write(mysocket, data, length, peeraddress);
137 if (developer_networking.integer)
139 char addressstring[128], addressstring2[128];
140 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
141 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
142 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
143 Com_HexDumpToConsole(data, length);
148 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
150 // note this does not include the trailing NULL because we add that in the parser
151 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
154 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
156 unsigned int packetLen;
157 unsigned int dataLen;
159 unsigned int *header;
162 if (data->cursize == 0)
163 Sys_Error("Datagram_SendMessage: zero length message\n");
165 if (data->cursize > NET_MAXMESSAGE)
166 Sys_Error("Datagram_SendMessage: message too big %u\n", data->cursize);
168 if (conn->canSend == false)
169 Sys_Error("SendMessage: called with canSend == false\n");
172 memcpy(conn->sendMessage, data->data, data->cursize);
173 conn->sendMessageLength = data->cursize;
175 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
177 dataLen = conn->sendMessageLength;
182 dataLen = MAX_PACKETFRAGMENT;
186 packetLen = NET_HEADERSIZE + dataLen;
188 header = (void *)sendbuffer;
189 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
190 header[1] = BigLong(conn->sendSequence);
191 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
193 conn->sendSequence++;
194 conn->canSend = false;
196 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
199 conn->lastSendTime = realtime;
201 reliableMessagesSent++;
205 static void NetConn_SendMessageNext(netconn_t *conn)
207 unsigned int packetLen;
208 unsigned int dataLen;
210 unsigned int *header;
212 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
214 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
216 dataLen = conn->sendMessageLength;
221 dataLen = MAX_PACKETFRAGMENT;
225 packetLen = NET_HEADERSIZE + dataLen;
227 header = (void *)sendbuffer;
228 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
229 header[1] = BigLong(conn->sendSequence);
230 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
232 conn->sendSequence++;
233 conn->sendNext = false;
235 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
238 conn->lastSendTime = realtime;
243 static void NetConn_ReSendMessage(netconn_t *conn)
245 unsigned int packetLen;
246 unsigned int dataLen;
248 unsigned int *header;
250 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
252 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
254 dataLen = conn->sendMessageLength;
259 dataLen = MAX_PACKETFRAGMENT;
263 packetLen = NET_HEADERSIZE + dataLen;
265 header = (void *)sendbuffer;
266 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
267 header[1] = BigLong(conn->sendSequence - 1);
268 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
270 conn->sendNext = false;
272 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
275 conn->lastSendTime = realtime;
280 qboolean NetConn_CanSendMessage(netconn_t *conn)
282 return conn->canSend;
285 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
291 if (data->cursize == 0)
292 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
294 if (data->cursize > MAX_DATAGRAM)
295 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
298 packetLen = NET_HEADERSIZE + data->cursize;
300 header = (void *)sendbuffer;
301 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
302 header[1] = BigLong(conn->unreliableSendSequence);
303 memcpy(sendbuffer + 8, data->data, data->cursize);
305 conn->unreliableSendSequence++;
307 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
311 unreliableMessagesSent++;
315 void NetConn_CloseClientPorts(void)
317 for (;cl_numsockets > 0;cl_numsockets--)
318 if (cl_sockets[cl_numsockets - 1])
319 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
322 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
324 lhnetaddress_t address;
326 char addressstring2[1024];
327 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
329 if ((s = LHNET_OpenSocket_Connectionless(&address)))
331 cl_sockets[cl_numsockets++] = s;
332 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
333 Con_Printf("Client opened a socket on address %s\n", addressstring2);
337 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
338 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
342 Con_Printf("Client unable to parse address %s\n", addressstring);
345 void NetConn_OpenClientPorts(void)
348 NetConn_CloseClientPorts();
349 port = bound(0, cl_netport.integer, 65535);
350 if (cl_netport.integer != port)
351 Cvar_SetValueQuick(&cl_netport, port);
352 Con_Printf("Client using port %i\n", port);
353 NetConn_OpenClientPort("local:2", 0);
354 NetConn_OpenClientPort(net_address.string, port);
355 //NetConn_OpenClientPort(net_address_ipv6.string, port);
358 void NetConn_CloseServerPorts(void)
360 for (;sv_numsockets > 0;sv_numsockets--)
361 if (sv_sockets[sv_numsockets - 1])
362 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
365 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
367 lhnetaddress_t address;
369 char addressstring2[1024];
370 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
372 if ((s = LHNET_OpenSocket_Connectionless(&address)))
374 sv_sockets[sv_numsockets++] = s;
375 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
376 Con_Printf("Server listening on address %s\n", addressstring2);
380 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
381 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
385 Con_Printf("Server unable to parse address %s\n", addressstring);
388 void NetConn_OpenServerPorts(int opennetports)
391 NetConn_CloseServerPorts();
392 port = bound(0, sv_netport.integer, 65535);
395 Con_Printf("Server using port %i\n", port);
396 if (sv_netport.integer != port)
397 Cvar_SetValueQuick(&sv_netport, port);
398 if (cls.state != ca_dedicated)
399 NetConn_OpenServerPort("local:1", 0);
402 NetConn_OpenServerPort(net_address.string, port);
403 //NetConn_OpenServerPort(net_address_ipv6.string, port);
405 if (sv_numsockets == 0)
406 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
409 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
411 int i, a = LHNETADDRESS_GetAddressType(address);
412 for (i = 0;i < cl_numsockets;i++)
413 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
414 return cl_sockets[i];
418 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
420 int i, a = LHNETADDRESS_GetAddressType(address);
421 for (i = 0;i < sv_numsockets;i++)
422 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
423 return sv_sockets[i];
427 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
430 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
431 conn->mysocket = mysocket;
432 conn->peeraddress = *peeraddress;
433 conn->canSend = true;
434 conn->connecttime = realtime;
435 conn->lastMessageTime = realtime;
436 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
437 // reduce effectiveness of connection request floods
438 conn->timeout = realtime + net_connecttimeout.value;
439 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
440 conn->next = netconn_list;
445 void NetConn_Close(netconn_t *conn)
448 // remove connection from list
449 if (conn == netconn_list)
450 netconn_list = conn->next;
453 for (c = netconn_list;c;c = c->next)
457 c->next = conn->next;
461 // not found in list, we'll avoid crashing here...
469 static int clientport = -1;
470 static int clientport2 = -1;
471 static int hostport = -1;
472 static void NetConn_UpdateServerStuff(void)
474 if (cls.state != ca_dedicated)
476 if (clientport2 != cl_netport.integer)
478 clientport2 = cl_netport.integer;
479 if (cls.state == ca_connected)
480 Con_Printf("Changing \"cl_port\" will not take effect until you reconnect.\n");
482 if (cls.state == ca_disconnected && clientport != clientport2)
484 clientport = clientport2;
485 NetConn_CloseClientPorts();
487 if (cl_numsockets == 0)
488 NetConn_OpenClientPorts();
491 if (hostport != sv_netport.integer)
493 hostport = sv_netport.integer;
495 Con_Printf("Changing \"port\" will not take effect until \"map\" command is executed.\n");
499 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
503 unsigned int sequence;
507 length = BigLong(((int *)data)[0]);
508 flags = length & ~NETFLAG_LENGTH_MASK;
509 length &= NETFLAG_LENGTH_MASK;
510 // control packets were already handled
511 if (!(flags & NETFLAG_CTL))
513 sequence = BigLong(((int *)data)[1]);
517 if (flags & NETFLAG_UNRELIABLE)
519 if (sequence >= conn->unreliableReceiveSequence)
521 if (sequence > conn->unreliableReceiveSequence)
523 count = sequence - conn->unreliableReceiveSequence;
524 droppedDatagrams += count;
525 Con_DPrintf("Dropped %u datagram(s)\n", count);
527 conn->unreliableReceiveSequence = sequence + 1;
528 conn->lastMessageTime = realtime;
529 conn->timeout = realtime + net_messagetimeout.value;
530 unreliableMessagesReceived++;
533 SZ_Clear(&net_message);
534 SZ_Write(&net_message, data, length);
540 Con_DPrintf("Got a stale datagram\n");
543 else if (flags & NETFLAG_ACK)
545 if (sequence == (conn->sendSequence - 1))
547 if (sequence == conn->ackSequence)
550 if (conn->ackSequence != conn->sendSequence)
551 Con_DPrintf("ack sequencing error\n");
552 conn->lastMessageTime = realtime;
553 conn->timeout = realtime + net_messagetimeout.value;
554 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
555 if (conn->sendMessageLength > 0)
557 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
558 conn->sendNext = true;
559 NetConn_SendMessageNext(conn);
563 conn->sendMessageLength = 0;
564 conn->canSend = true;
568 Con_DPrintf("Duplicate ACK received\n");
571 Con_DPrintf("Stale ACK received\n");
574 else if (flags & NETFLAG_DATA)
576 unsigned int temppacket[2];
577 temppacket[0] = BigLong(8 | NETFLAG_ACK);
578 temppacket[1] = BigLong(sequence);
579 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
580 if (sequence == conn->receiveSequence)
582 conn->lastMessageTime = realtime;
583 conn->timeout = realtime + net_messagetimeout.value;
584 conn->receiveSequence++;
585 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
586 conn->receiveMessageLength += length;
587 if (flags & NETFLAG_EOM)
589 reliableMessagesReceived++;
590 length = conn->receiveMessageLength;
591 conn->receiveMessageLength = 0;
594 SZ_Clear(&net_message);
595 SZ_Write(&net_message, conn->receiveMessage, length);
602 receivedDuplicateCount++;
610 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
612 cls.netcon = NetConn_Open(mysocket, peeraddress);
613 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
616 cls.connect_trying = false;
617 cls.demonum = -1; // not in the demo loop now
618 cls.state = ca_connected;
619 cls.signon = 0; // need all the signon messages before playing
624 int NetConn_IsLocalGame(void)
626 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
634 lhnetaddress_t peeraddress;
636 pingcache[HOSTCACHESIZE];
638 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
641 lhnetaddress_t svaddress;
643 char *string, addressstring2[128], cname[128], ipstring[32];
644 char stringbuf[16384];
646 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
648 // received a command string - strip off the packaging and put it
649 // into our string buffer with NULL termination
652 length = min(length, (int)sizeof(stringbuf) - 1);
653 memcpy(stringbuf, data, length);
654 stringbuf[length] = 0;
657 if (developer.integer)
659 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
660 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
661 Com_HexDumpToConsole(data, length);
664 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
666 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
667 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
668 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
671 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
673 NetConn_ConnectionEstablished(mysocket, peeraddress);
676 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
678 cls.connect_trying = false;
680 length = max(length - 7, (int)sizeof(m_return_reason) - 1);
681 memcpy(m_return_reason, string, length);
682 m_return_reason[length] = 0;
683 Con_Printf("%s\n", m_return_reason);
686 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
688 int i, j, c, n, users, maxusers;
689 char game[32], mod[32], map[32], name[128];
693 // hostcache only uses text addresses
694 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
695 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(game, s, sizeof (game));else game[0] = 0;
696 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(mod , s, sizeof (mod ));else mod[0] = 0;
697 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(map , s, sizeof (map ));else map[0] = 0;
698 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(name, s, sizeof (name));else name[0] = 0;
699 if ((s = SearchInfostring(string, "protocol" )) != NULL) c = atoi(s);else c = -1;
700 if ((s = SearchInfostring(string, "clients" )) != NULL) users = atoi(s);else users = 0;
701 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) maxusers = atoi(s);else maxusers = 0;
702 // search the cache for this server and update it
703 for (n = 0; n < hostCacheCount; n++)
705 if (!strcmp(cname, hostcache[n].cname))
707 if (hostcache[n].ping == 100000)
709 pingtime = (int)((realtime - hostcache[n].querytime) * 1000.0);
710 pingtime = bound(0, pingtime, 9999);
712 hostcache[n].ping = pingtime;
713 // build description strings for the things users care about
714 snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, c != NET_PROTOCOL_VERSION ? '*' : ' ', users, maxusers, name);
715 snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", cname, game, mod, map);
716 // if ping is especially high, display it as such
719 // orange numbers (lower block)
720 for (i = 0;i < 5;i++)
721 if (hostcache[n].line1[i] != ' ')
722 hostcache[n].line1[i] += 128;
724 else if (pingtime >= 200)
726 // yellow numbers (in upper block)
727 for (i = 0;i < 5;i++)
728 if (hostcache[n].line1[i] != ' ')
729 hostcache[n].line1[i] -= 30;
731 // if not in the slist menu we should print the server to console
732 if (m_state != m_slist)
733 Con_Printf("%s\n%s\n", hostcache[n].line1, hostcache[n].line2);
734 // and finally, re-sort the list
735 for (i = 0;i < hostCacheCount;i++)
737 for (j = i + 1;j < hostCacheCount;j++)
739 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
740 if (hostcache[i].ping > hostcache[j].ping)
742 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
743 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
744 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
753 if (!strncmp(string, "getserversResponse\\", 19) && hostCacheCount < HOSTCACHESIZE)
757 // Extract the IP addresses
761 if (m_state != m_slist)
762 Con_Printf("received server list...\n");
763 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
765 snprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
766 if (developer.integer)
767 Con_Printf("Requesting info from server %s\n", ipstring);
768 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
769 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
772 // add to slist (hostCache)
773 // search the cache for this server
774 for (n = 0; n < hostCacheCount; n++)
775 if (!strcmp(ipstring, hostcache[n].cname))
777 // add it or update it
778 if (n == hostCacheCount)
780 // if cache is full replace highest ping server (the list is
781 // kept sorted so this is always the last, and if this server
782 // is good it will be sorted into an early part of the list)
783 if (hostCacheCount >= HOSTCACHESIZE)
784 n = hostCacheCount - 1;
791 memset(&hostcache[n], 0, sizeof(hostcache[n]));
792 // store the data the engine cares about (address and ping)
793 strlcpy (hostcache[n].cname, ipstring, sizeof (hostcache[n].cname));
794 hostcache[n].ping = 100000;
795 hostcache[n].querytime = realtime;
796 // build description strings for the things users care about
797 snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "?");
798 snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%s", ipstring);
799 // if not in the slist menu we should print the server to console
800 if (m_state != m_slist)
801 Con_Printf("querying %s\n", ipstring);
802 // and finally, re-sort the list
803 for (i = 0;i < hostCacheCount;i++)
805 for (j = i + 1;j < hostCacheCount;j++)
807 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
808 if (hostcache[i].ping > hostcache[j].ping)
810 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
811 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
812 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
818 // move on to next address in packet
825 if (!strncmp(string, "ping", 4))
827 if (developer.integer)
828 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
829 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
832 if (!strncmp(string, "ack", 3))
835 // we may not have liked the packet, but it was a command packet, so
836 // we're done processing this packet now
839 // netquake control packets, supported for compatibility only
840 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
845 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
849 if (developer.integer)
850 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
851 if (cls.connect_trying)
853 lhnetaddress_t clientportaddress;
854 clientportaddress = *peeraddress;
857 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
860 LHNETADDRESS_SetPort(&clientportaddress, port);
862 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
866 if (developer.integer)
867 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
868 Con_Printf("%s\n", data);
869 strlcpy (m_return_reason, data, sizeof (m_return_reason));
872 case CCREP_SERVER_INFO:
873 if (developer.integer)
874 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
875 if (cls.state != ca_dedicated)
877 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
878 // string we just ignore it and keep the real address
880 // hostcache only uses text addresses
881 cname = UDP_AddrToString(readaddr);
882 // search the cache for this server
883 for (n = 0; n < hostCacheCount; n++)
884 if (!strcmp(cname, hostcache[n].cname))
887 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
890 memset(&hostcache[n], 0, sizeof(hostcache[n]));
891 strlcpy (hostcache[n].name, MSG_ReadString(), sizeof (hostcache[n].name));
892 strlcpy (hostcache[n].map, MSG_ReadString(), sizeof (hostcache[n].map));
893 hostcache[n].users = MSG_ReadByte();
894 hostcache[n].maxusers = MSG_ReadByte();
896 if (c != NET_PROTOCOL_VERSION)
898 strlcpy (hostcache[n].cname, hostcache[n].name, sizeof (hostcache[n].cname));
899 strcpy(hostcache[n].name, "*");
900 strlcat (hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name));
902 strlcpy (hostcache[n].cname, cname, sizeof (hostcache[n].cname));
906 case CCREP_PLAYER_INFO:
907 // we got a CCREP_PLAYER_INFO??
908 //if (developer.integer)
909 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
911 case CCREP_RULE_INFO:
912 // we got a CCREP_RULE_INFO??
913 //if (developer.integer)
914 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
920 // we may not have liked the packet, but it was a valid control
921 // packet, so we're done processing this packet now
925 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)
926 CL_ParseServerMessage();
930 void NetConn_ClientFrame(void)
933 lhnetaddress_t peeraddress;
935 NetConn_UpdateServerStuff();
936 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
938 if (cls.connect_remainingtries == 0)
940 cls.connect_trying = false;
941 if (m_state == m_slist)
942 strcpy (m_return_reason, "Connect: Failed");
944 Con_Printf("Connect failed\n");
947 if (cls.connect_nextsendtime)
949 if (m_state == m_slist)
950 strcpy (m_return_reason, "Connect: Still trying");
952 Con_Printf("Still trying...\n");
956 if (m_state == m_slist)
957 strcpy (m_return_reason, "Connect: Trying");
959 Con_Printf("Trying...\n");
961 cls.connect_nextsendtime = realtime + 1;
962 cls.connect_remainingtries--;
963 // try challenge first (newer server)
964 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
965 // then try netquake as a fallback (old server, or netquake)
966 SZ_Clear(&net_message);
967 // save space for the header, filled in later
968 MSG_WriteLong(&net_message, 0);
969 MSG_WriteByte(&net_message, CCREQ_CONNECT);
970 MSG_WriteString(&net_message, "QUAKE");
971 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
972 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
973 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
974 SZ_Clear(&net_message);
976 for (i = 0;i < cl_numsockets;i++)
977 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
978 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
979 if (cls.netcon && realtime > cls.netcon->timeout)
981 Con_Printf("Connection timed out\n");
984 for (conn = netconn_list;conn;conn = conn->next)
985 NetConn_ReSendMessage(conn);
988 #define MAX_CHALLENGES 128
991 lhnetaddress_t address;
995 challenge[MAX_CHALLENGES];
997 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1001 for (i = 0;i < bufferlength - 1;i++)
1005 c = rand () % (127 - 33) + 33;
1006 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1012 extern void SV_ConnectClient(int clientnum, netconn_t *netconnection);
1013 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1015 int i, n, ret, clientnum, responselength, best;
1019 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1023 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1025 // received a command string - strip off the packaging and put it
1026 // into our string buffer with NULL termination
1029 length = min(length, (int)sizeof(stringbuf) - 1);
1030 memcpy(stringbuf, data, length);
1031 stringbuf[length] = 0;
1034 if (developer.integer)
1036 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1037 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1038 Com_HexDumpToConsole(data, length);
1041 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1043 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1045 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1047 if (besttime > challenge[i].time)
1048 besttime = challenge[best = i].time;
1050 // if we did not find an exact match, choose the oldest and
1051 // update address and string
1052 if (i == MAX_CHALLENGES)
1055 challenge[i].address = *peeraddress;
1056 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1058 challenge[i].time = realtime;
1059 // send the challenge
1060 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1063 if (length > 8 && !memcmp(string, "connect\\", 8))
1067 if ((s = SearchInfostring(string, "challenge")))
1069 // validate the challenge
1070 for (i = 0;i < MAX_CHALLENGES;i++)
1071 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1073 if (i < MAX_CHALLENGES)
1075 // check engine protocol
1076 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1078 if (developer.integer)
1079 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1080 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1084 // see if this is a duplicate connection request
1085 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1086 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1088 if (clientnum < svs.maxclients)
1090 // duplicate connection request
1091 if (realtime - client->netconnection->connecttime < 2.0)
1093 // client is still trying to connect,
1094 // so we send a duplicate reply
1095 if (developer.integer)
1096 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1097 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1099 // only kick if old connection seems dead
1100 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1102 // kick off connection and await retry
1103 client->deadsocket = true;
1108 // this is a new client, find a slot
1109 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1110 if (!client->active)
1112 if (clientnum < svs.maxclients)
1114 // prepare the client struct
1115 if ((client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_clients_mempool)))
1117 if ((conn = NetConn_Open(mysocket, peeraddress)))
1119 // allocated connection
1120 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1121 if (developer.integer)
1122 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1123 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1124 // now set up the client
1125 SV_ConnectClient(clientnum, conn);
1126 NetConn_Heartbeat(1);
1129 EntityFrame4_FreeDatabase(client->entitydatabase4);
1135 if (developer.integer)
1136 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1137 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1145 if (length >= 7 && !memcmp(string, "getinfo", 7))
1147 const char *challenge = NULL;
1148 // If there was a challenge in the getinfo message
1149 if (length > 8 && string[7] == ' ')
1150 challenge = string + 8;
1151 for (i = 0, n = 0;i < svs.maxclients;i++)
1152 if (svs.clients[i].active)
1154 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1155 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1156 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1157 gamename, com_modname, svs.maxclients, n,
1158 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1159 // does it fit in the buffer?
1160 if (responselength < (int)sizeof(response))
1162 if (developer.integer)
1163 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1164 NetConn_WriteString(mysocket, response, peeraddress);
1169 if (!strncmp(string, "ping", 4))
1171 if (developer.integer)
1172 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1173 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1176 if (!strncmp(string, "ack", 3))
1179 // we may not have liked the packet, but it was a command packet, so
1180 // we're done processing this packet now
1183 // LordHavoc: disabled netquake control packet support in server
1187 // netquake control packets, supported for compatibility only
1188 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1193 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1197 //if (developer.integer)
1198 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1199 if (length >= (int)strlen("QUAKE") + 1 + 1)
1201 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1203 if (developer.integer)
1204 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
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_REJECT);
1209 MSG_WriteString(&net_message, "Incompatible version.\n");
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);
1216 // see if this is a duplicate connection request
1217 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1218 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1220 if (clientnum < svs.maxclients)
1222 // duplicate connection request
1223 if (realtime - client->netconnection->connecttime < 2.0)
1225 // client is still trying to connect,
1226 // so we send a duplicate reply
1227 if (developer.integer)
1228 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1229 SZ_Clear(&net_message);
1230 // save space for the header, filled in later
1231 MSG_WriteLong(&net_message, 0);
1232 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1233 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1234 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1235 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1236 SZ_Clear(&net_message);
1238 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1240 // the old client hasn't sent us anything
1241 // in quite a while, so kick off and let
1242 // the retry take care of it...
1243 client->deadsocket = true;
1248 // this is a new client, find a slot
1249 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1250 if (!client->active)
1252 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1254 // connect to the client
1255 // everything is allocated, just fill in the details
1256 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1257 if (developer.integer)
1258 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1259 // send back the info about the server connection
1260 SZ_Clear(&net_message);
1261 // save space for the header, filled in later
1262 MSG_WriteLong(&net_message, 0);
1263 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1264 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1265 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1266 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1267 SZ_Clear(&net_message);
1268 // now set up the client struct
1269 SV_ConnectClient(clientnum, conn);
1270 NetConn_Heartbeat(1);
1274 //if (developer.integer)
1275 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1276 // no room; try to let player know
1277 SZ_Clear(&net_message);
1278 // save space for the header, filled in later
1279 MSG_WriteLong(&net_message, 0);
1280 MSG_WriteByte(&net_message, CCREP_REJECT);
1281 MSG_WriteString(&net_message, "Server is full.\n");
1282 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1283 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1284 SZ_Clear(&net_message);
1291 case CCREQ_SERVER_INFO:
1292 if (developer.integer)
1293 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1294 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1296 if (developer.integer)
1297 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1298 SZ_Clear(&net_message);
1299 // save space for the header, filled in later
1300 MSG_WriteLong(&net_message, 0);
1301 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1302 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1303 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1304 MSG_WriteString(&net_message, hostname.string);
1305 MSG_WriteString(&net_message, sv.name);
1306 MSG_WriteByte(&net_message, net_activeconnections);
1307 MSG_WriteByte(&net_message, svs.maxclients);
1308 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1309 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1310 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1311 SZ_Clear(&net_message);
1314 case CCREQ_PLAYER_INFO:
1315 if (developer.integer)
1316 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1319 int playerNumber, activeNumber, clientNumber;
1322 playerNumber = MSG_ReadByte();
1324 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1325 if (client->active && ++activeNumber == playerNumber)
1327 if (clientNumber != svs.maxclients)
1329 SZ_Clear(&net_message);
1330 // save space for the header, filled in later
1331 MSG_WriteLong(&net_message, 0);
1332 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1333 MSG_WriteByte(&net_message, playerNumber);
1334 MSG_WriteString(&net_message, client->name);
1335 MSG_WriteLong(&net_message, client->colors);
1336 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1337 MSG_WriteLong(&net_message, (int)(realtime - client->netconnection->connecttime));
1338 MSG_WriteString(&net_message, client->netconnection->address);
1339 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1340 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1341 SZ_Clear(&net_message);
1345 case CCREQ_RULE_INFO:
1346 if (developer.integer)
1347 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1353 // find the search start location
1354 prevCvarName = MSG_ReadString();
1355 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1357 // send the response
1358 SZ_Clear(&net_message);
1359 // save space for the header, filled in later
1360 MSG_WriteLong(&net_message, 0);
1361 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1364 MSG_WriteString(&net_message, var->name);
1365 MSG_WriteString(&net_message, var->string);
1367 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1368 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1369 SZ_Clear(&net_message);
1376 // we may not have liked the packet, but it was a valid control
1377 // packet, so we're done processing this packet now
1382 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1384 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1386 sv_player = host_client->edict;
1387 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1388 SV_ReadClientMessage();
1396 void NetConn_ServerFrame(void)
1399 lhnetaddress_t peeraddress;
1401 NetConn_UpdateServerStuff();
1402 for (i = 0;i < sv_numsockets;i++)
1403 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1404 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1405 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1407 // never timeout loopback connections
1408 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(host_client->netconnection->mysocket)) != LHNETADDRESSTYPE_LOOP)
1410 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1411 sv_player = host_client->edict;
1412 SV_DropClient(false);
1415 for (conn = netconn_list;conn;conn = conn->next)
1416 NetConn_ReSendMessage(conn);
1419 void NetConn_QueryMasters(void)
1423 lhnetaddress_t masteraddress;
1426 if (hostCacheCount >= HOSTCACHESIZE)
1429 for (i = 0;i < cl_numsockets;i++)
1436 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1438 SZ_Clear(&net_message);
1439 // save space for the header, filled in later
1440 MSG_WriteLong(&net_message, 0);
1441 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1442 MSG_WriteString(&net_message, "QUAKE");
1443 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1444 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1445 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1446 SZ_Clear(&net_message);
1450 // build the getservers
1451 snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1454 for (masternum = 0;sv_masters[masternum].name;masternum++)
1456 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1459 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1464 if (!masterquerycount)
1466 Con_Printf("Unable to query master servers, no suitable network sockets active.\n");
1467 strcpy(m_return_reason, "No network");
1471 void NetConn_Heartbeat(int priority)
1473 lhnetaddress_t masteraddress;
1475 lhnetsocket_t *mysocket;
1477 // if it's a state change (client connected), limit next heartbeat to no
1478 // more than 30 sec in the future
1479 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1480 nextheartbeattime = realtime + 30.0;
1482 // limit heartbeatperiod to 30 to 270 second range,
1483 // lower limit is to avoid abusing master servers with excess traffic,
1484 // upper limit is to avoid timing out on the master server (which uses
1486 if (sv_heartbeatperiod.value < 30)
1487 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1488 if (sv_heartbeatperiod.value > 270)
1489 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1491 // make advertising optional and don't advertise singleplayer games, and
1492 // only send a heartbeat as often as the admin wants
1493 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1495 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1496 for (masternum = 0;sv_masters[masternum].name;masternum++)
1497 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1498 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1502 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1505 qbyte sent[MAX_SCOREBOARD];
1507 memset(sent, 0, sizeof(sent));
1509 // simultaneously wait for the first CanSendMessage and send the message,
1510 // then wait for a second CanSendMessage (verifying it was received), or
1511 // the client drops and is no longer counted
1512 // the loop aborts when either it runs out of clients to send to, or a
1514 blocktime += Sys_DoubleTime();
1518 NetConn_ClientFrame();
1519 NetConn_ServerFrame();
1520 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1522 if (host_client->netconnection)
1524 if (NetConn_CanSendMessage(host_client->netconnection))
1527 NetConn_SendReliableMessage(host_client->netconnection, data);
1530 if (!NetConn_CanSendMessage(host_client->netconnection))
1535 while (count && Sys_DoubleTime() < blocktime);
1539 static void Net_Heartbeat_f(void)
1542 NetConn_Heartbeat(2);
1544 Con_Printf("No server running, can not heartbeat to master server.\n");
1547 void PrintStats(netconn_t *conn)
1549 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1552 void Net_Stats_f(void)
1555 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1556 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1557 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1558 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1559 Con_Printf("packetsSent = %i\n", packetsSent);
1560 Con_Printf("packetsReSent = %i\n", packetsReSent);
1561 Con_Printf("packetsReceived = %i\n", packetsReceived);
1562 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1563 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1564 Con_Printf("connections =\n");
1565 for (conn = netconn_list;conn;conn = conn->next)
1569 void Net_Slist_f(void)
1571 masterquerytime = realtime;
1572 masterquerycount = 0;
1573 masterreplycount = 0;
1574 serverquerycount = 0;
1575 serverreplycount = 0;
1577 memset(&pingcache, 0, sizeof(pingcache));
1578 if (m_state != m_slist)
1579 Con_Printf("Sending requests to master servers\n");
1580 NetConn_QueryMasters();
1581 if (m_state != m_slist)
1582 Con_Printf("Listening for replies...\n");
1585 void NetConn_Init(void)
1588 lhnetaddress_t tempaddress;
1589 netconn_mempool = Mem_AllocPool("Networking");
1590 Cmd_AddCommand("net_stats", Net_Stats_f);
1591 Cmd_AddCommand("net_slist", Net_Slist_f);
1592 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1593 Cvar_RegisterVariable(&net_messagetimeout);
1594 Cvar_RegisterVariable(&net_messagerejointimeout);
1595 Cvar_RegisterVariable(&net_connecttimeout);
1596 Cvar_RegisterVariable(&cl_fakelocalping_min);
1597 Cvar_RegisterVariable(&cl_fakelocalping_max);
1598 Cvar_RegisterVariable(&cl_fakepacketloss_receive);
1599 Cvar_RegisterVariable(&cl_fakepacketloss_send);
1600 Cvar_RegisterVariable(&sv_fakepacketloss_receive);
1601 Cvar_RegisterVariable(&sv_fakepacketloss_send);
1602 Cvar_RegisterVariable(&hostname);
1603 Cvar_RegisterVariable(&developer_networking);
1604 Cvar_RegisterVariable(&cl_netport);
1605 Cvar_RegisterVariable(&sv_netport);
1606 Cvar_RegisterVariable(&net_address);
1607 //Cvar_RegisterVariable(&net_address_ipv6);
1608 Cvar_RegisterVariable(&sv_public);
1609 Cvar_RegisterVariable(&sv_heartbeatperiod);
1610 for (i = 0;sv_masters[i].name;i++)
1611 Cvar_RegisterVariable(&sv_masters[i]);
1612 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1614 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1616 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
1617 Cvar_SetQuick(&net_address, com_argv[i + 1]);
1620 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1622 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1624 i = atoi(com_argv[i + 1]);
1625 if (i >= 0 && i < 65536)
1627 Con_Printf("-port option used, setting port cvar to %i\n", i);
1628 Cvar_SetValueQuick(&sv_netport, i);
1631 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1635 memset(&pingcache, 0, sizeof(pingcache));
1636 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1640 void NetConn_Shutdown(void)
1642 NetConn_CloseClientPorts();
1643 NetConn_CloseServerPorts();