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", "ghdigital.com"},
38 {0, "sv_masterextra2", "dpmaster.deathmask.net"},
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_netlocalping = {0, "cl_netlocalping","0"};
53 static cvar_t cl_netpacketloss = {0, "cl_netpacketloss","0"};
56 /* statistic counters */
57 static int packetsSent = 0;
58 static int packetsReSent = 0;
59 static int packetsReceived = 0;
60 static int receivedDuplicateCount = 0;
61 static int droppedDatagrams = 0;
63 static int unreliableMessagesSent = 0;
64 static int unreliableMessagesReceived = 0;
65 static int reliableMessagesSent = 0;
66 static int reliableMessagesReceived = 0;
68 double masterquerytime = -1000;
69 int masterquerycount = 0;
70 int masterreplycount = 0;
71 int serverquerycount = 0;
72 int serverreplycount = 0;
74 int hostCacheCount = 0;
75 hostcache_t hostcache[HOSTCACHESIZE];
77 static qbyte sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
78 static qbyte readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
81 lhnetsocket_t *cl_sockets[16];
83 lhnetsocket_t *sv_sockets[16];
85 netconn_t *netconn_list = NULL;
86 mempool_t *netconn_mempool = NULL;
88 cvar_t cl_netport = {0, "cl_port", "0"};
89 cvar_t sv_netport = {0, "port", "26000"};
90 cvar_t net_address = {0, "net_address", "0.0.0.0"};
91 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]"};
93 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
95 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
97 if (cl_netpacketloss.integer)
98 for (i = 0;i < cl_numsockets;i++)
99 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
101 if (developer_networking.integer && length != 0)
103 char addressstring[128], addressstring2[128];
104 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
107 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
108 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
109 Com_HexDumpToConsole(data, length);
112 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
117 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
121 if (cl_netpacketloss.integer)
122 for (i = 0;i < cl_numsockets;i++)
123 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
125 ret = LHNET_Write(mysocket, data, length, peeraddress);
126 if (developer_networking.integer)
128 char addressstring[128], addressstring2[128];
129 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
130 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
131 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
132 Com_HexDumpToConsole(data, length);
137 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
139 // note this does not include the trailing NULL because we add that in the parser
140 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
143 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
145 unsigned int packetLen;
146 unsigned int dataLen;
148 unsigned int *header;
151 if (data->cursize == 0)
152 Sys_Error("Datagram_SendMessage: zero length message\n");
154 if (data->cursize > (int)sizeof(conn->sendMessage))
155 Sys_Error("Datagram_SendMessage: message too big (%u > %u)\n", data->cursize, sizeof(conn->sendMessage));
157 if (conn->canSend == false)
158 Sys_Error("SendMessage: called with canSend == false\n");
161 memcpy(conn->sendMessage, data->data, data->cursize);
162 conn->sendMessageLength = data->cursize;
164 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
166 dataLen = conn->sendMessageLength;
171 dataLen = MAX_PACKETFRAGMENT;
175 packetLen = NET_HEADERSIZE + dataLen;
177 header = (void *)sendbuffer;
178 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
179 header[1] = BigLong(conn->sendSequence);
180 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
182 conn->sendSequence++;
183 conn->canSend = false;
185 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
188 conn->lastSendTime = realtime;
190 reliableMessagesSent++;
194 static void NetConn_SendMessageNext(netconn_t *conn)
196 unsigned int packetLen;
197 unsigned int dataLen;
199 unsigned int *header;
201 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
203 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
205 dataLen = conn->sendMessageLength;
210 dataLen = MAX_PACKETFRAGMENT;
214 packetLen = NET_HEADERSIZE + dataLen;
216 header = (void *)sendbuffer;
217 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
218 header[1] = BigLong(conn->sendSequence);
219 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
221 conn->sendSequence++;
222 conn->sendNext = false;
224 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
227 conn->lastSendTime = realtime;
232 static void NetConn_ReSendMessage(netconn_t *conn)
234 unsigned int packetLen;
235 unsigned int dataLen;
237 unsigned int *header;
239 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
241 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
243 dataLen = conn->sendMessageLength;
248 dataLen = MAX_PACKETFRAGMENT;
252 packetLen = NET_HEADERSIZE + dataLen;
254 header = (void *)sendbuffer;
255 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
256 header[1] = BigLong(conn->sendSequence - 1);
257 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
259 conn->sendNext = false;
261 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
264 conn->lastSendTime = realtime;
269 qboolean NetConn_CanSendMessage(netconn_t *conn)
271 return conn->canSend;
274 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
279 packetLen = NET_HEADERSIZE + data->cursize;
282 if (data->cursize == 0)
283 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
285 if (packetLen > (int)sizeof(sendbuffer))
286 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
289 header = (void *)sendbuffer;
290 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
291 header[1] = BigLong(conn->unreliableSendSequence);
292 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
294 conn->unreliableSendSequence++;
296 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
300 unreliableMessagesSent++;
304 void NetConn_CloseClientPorts(void)
306 for (;cl_numsockets > 0;cl_numsockets--)
307 if (cl_sockets[cl_numsockets - 1])
308 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
311 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
313 lhnetaddress_t address;
315 char addressstring2[1024];
316 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
318 if ((s = LHNET_OpenSocket_Connectionless(&address)))
320 cl_sockets[cl_numsockets++] = s;
321 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
322 Con_Printf("Client opened a socket on address %s\n", addressstring2);
326 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
327 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
331 Con_Printf("Client unable to parse address %s\n", addressstring);
334 void NetConn_OpenClientPorts(void)
337 NetConn_CloseClientPorts();
338 port = bound(0, cl_netport.integer, 65535);
339 if (cl_netport.integer != port)
340 Cvar_SetValueQuick(&cl_netport, port);
341 Con_Printf("Client using port %i\n", port);
342 NetConn_OpenClientPort("local:2", 0);
343 NetConn_OpenClientPort(net_address.string, port);
344 //NetConn_OpenClientPort(net_address_ipv6.string, port);
347 void NetConn_CloseServerPorts(void)
349 for (;sv_numsockets > 0;sv_numsockets--)
350 if (sv_sockets[sv_numsockets - 1])
351 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
354 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
356 lhnetaddress_t address;
358 char addressstring2[1024];
359 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
361 if ((s = LHNET_OpenSocket_Connectionless(&address)))
363 sv_sockets[sv_numsockets++] = s;
364 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
365 Con_Printf("Server listening on address %s\n", addressstring2);
369 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
370 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
374 Con_Printf("Server unable to parse address %s\n", addressstring);
377 void NetConn_OpenServerPorts(int opennetports)
380 NetConn_CloseServerPorts();
381 port = bound(0, sv_netport.integer, 65535);
384 Con_Printf("Server using port %i\n", port);
385 if (sv_netport.integer != port)
386 Cvar_SetValueQuick(&sv_netport, port);
387 if (cls.state != ca_dedicated)
388 NetConn_OpenServerPort("local:1", 0);
391 NetConn_OpenServerPort(net_address.string, port);
392 //NetConn_OpenServerPort(net_address_ipv6.string, port);
394 if (sv_numsockets == 0)
395 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
398 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
400 int i, a = LHNETADDRESS_GetAddressType(address);
401 for (i = 0;i < cl_numsockets;i++)
402 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
403 return cl_sockets[i];
407 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
409 int i, a = LHNETADDRESS_GetAddressType(address);
410 for (i = 0;i < sv_numsockets;i++)
411 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
412 return sv_sockets[i];
416 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
419 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
420 conn->mysocket = mysocket;
421 conn->peeraddress = *peeraddress;
422 // updated by receiving "rate" command from client
423 conn->rate = NET_MINRATE;
424 // no limits for local player
425 if (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP)
426 conn->rate = 1000000000;
427 conn->canSend = true;
428 conn->connecttime = realtime;
429 conn->lastMessageTime = realtime;
430 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
431 // reduce effectiveness of connection request floods
432 conn->timeout = realtime + net_connecttimeout.value;
433 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
434 conn->next = netconn_list;
439 void NetConn_Close(netconn_t *conn)
442 // remove connection from list
443 if (conn == netconn_list)
444 netconn_list = conn->next;
447 for (c = netconn_list;c;c = c->next)
451 c->next = conn->next;
455 // not found in list, we'll avoid crashing here...
463 static int clientport = -1;
464 static int clientport2 = -1;
465 static int hostport = -1;
466 static void NetConn_UpdateServerStuff(void)
468 if (cls.state != ca_dedicated)
470 if (clientport2 != cl_netport.integer)
472 clientport2 = cl_netport.integer;
473 if (cls.state == ca_connected)
474 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
476 if (cls.state == ca_disconnected && clientport != clientport2)
478 clientport = clientport2;
479 NetConn_CloseClientPorts();
481 if (cl_numsockets == 0)
482 NetConn_OpenClientPorts();
485 if (hostport != sv_netport.integer)
487 hostport = sv_netport.integer;
489 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
493 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
497 unsigned int sequence;
501 length = BigLong(((int *)data)[0]);
502 flags = length & ~NETFLAG_LENGTH_MASK;
503 length &= NETFLAG_LENGTH_MASK;
504 // control packets were already handled
505 if (!(flags & NETFLAG_CTL))
507 sequence = BigLong(((int *)data)[1]);
511 if (flags & NETFLAG_UNRELIABLE)
513 if (sequence >= conn->unreliableReceiveSequence)
515 if (sequence > conn->unreliableReceiveSequence)
517 count = sequence - conn->unreliableReceiveSequence;
518 droppedDatagrams += count;
519 Con_DPrintf("Dropped %u datagram(s)\n", count);
521 conn->unreliableReceiveSequence = sequence + 1;
522 conn->lastMessageTime = realtime;
523 conn->timeout = realtime + net_messagetimeout.value;
524 unreliableMessagesReceived++;
527 SZ_Clear(&net_message);
528 SZ_Write(&net_message, data, length);
534 Con_DPrint("Got a stale datagram\n");
537 else if (flags & NETFLAG_ACK)
539 if (sequence == (conn->sendSequence - 1))
541 if (sequence == conn->ackSequence)
544 if (conn->ackSequence != conn->sendSequence)
545 Con_DPrint("ack sequencing error\n");
546 conn->lastMessageTime = realtime;
547 conn->timeout = realtime + net_messagetimeout.value;
548 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
549 if (conn->sendMessageLength > 0)
551 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
552 conn->sendNext = true;
553 NetConn_SendMessageNext(conn);
557 conn->sendMessageLength = 0;
558 conn->canSend = true;
562 Con_DPrint("Duplicate ACK received\n");
565 Con_DPrint("Stale ACK received\n");
568 else if (flags & NETFLAG_DATA)
570 unsigned int temppacket[2];
571 temppacket[0] = BigLong(8 | NETFLAG_ACK);
572 temppacket[1] = BigLong(sequence);
573 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
574 if (sequence == conn->receiveSequence)
576 conn->lastMessageTime = realtime;
577 conn->timeout = realtime + net_messagetimeout.value;
578 conn->receiveSequence++;
579 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
580 conn->receiveMessageLength += length;
581 if (flags & NETFLAG_EOM)
583 reliableMessagesReceived++;
584 length = conn->receiveMessageLength;
585 conn->receiveMessageLength = 0;
588 SZ_Clear(&net_message);
589 SZ_Write(&net_message, conn->receiveMessage, length);
596 receivedDuplicateCount++;
604 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
606 cls.connect_trying = false;
607 M_Update_Return_Reason("");
608 // the connection request succeeded, stop current connection and set up a new connection
610 cls.netcon = NetConn_Open(mysocket, peeraddress);
611 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
614 cls.demonum = -1; // not in the demo loop now
615 cls.state = ca_connected;
616 cls.signon = 0; // need all the signon messages before playing
618 SCR_BeginLoadingPlaque();
621 int NetConn_IsLocalGame(void)
623 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
631 lhnetaddress_t peeraddress;
633 pingcache[HOSTCACHESIZE];
635 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
638 lhnetaddress_t svaddress;
640 char *string, addressstring2[128], cname[128], ipstring[32];
641 char stringbuf[16384];
643 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
645 // received a command string - strip off the packaging and put it
646 // into our string buffer with NULL termination
649 length = min(length, (int)sizeof(stringbuf) - 1);
650 memcpy(stringbuf, data, length);
651 stringbuf[length] = 0;
654 if (developer.integer)
656 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
657 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
658 Com_HexDumpToConsole(data, length);
661 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
663 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
664 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
665 M_Update_Return_Reason("Got challenge response");
666 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
669 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
671 M_Update_Return_Reason("Accepted");
672 NetConn_ConnectionEstablished(mysocket, peeraddress);
675 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
677 char rejectreason[32];
678 cls.connect_trying = false;
680 length = max(length - 7, (int)sizeof(rejectreason) - 1);
681 memcpy(rejectreason, string, length);
682 rejectreason[length] = 0;
683 M_Update_Return_Reason(rejectreason);
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_Print("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 strlcpy (hostcache[n].line1, "?", sizeof (hostcache[n].line1));
798 strlcpy (hostcache[n].line2, ipstring, sizeof (hostcache[n].line2));
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 M_Update_Return_Reason("Accepted");
863 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
867 if (developer.integer)
868 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
869 cls.connect_trying = false;
870 M_Update_Return_Reason(data);
873 case CCREP_SERVER_INFO:
874 if (developer.integer)
875 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
876 if (cls.state != ca_dedicated)
878 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
879 // string we just ignore it and keep the real address
881 // hostcache only uses text addresses
882 cname = UDP_AddrToString(readaddr);
883 // search the cache for this server
884 for (n = 0; n < hostCacheCount; n++)
885 if (!strcmp(cname, hostcache[n].cname))
888 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
891 memset(&hostcache[n], 0, sizeof(hostcache[n]));
892 strlcpy (hostcache[n].name, MSG_ReadString(), sizeof (hostcache[n].name));
893 strlcpy (hostcache[n].map, MSG_ReadString(), sizeof (hostcache[n].map));
894 hostcache[n].users = MSG_ReadByte();
895 hostcache[n].maxusers = MSG_ReadByte();
897 if (c != NET_PROTOCOL_VERSION)
899 strlcpy (hostcache[n].cname, hostcache[n].name, sizeof (hostcache[n].cname));
900 strcpy(hostcache[n].name, "*");
901 strlcat (hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name));
903 strlcpy (hostcache[n].cname, cname, sizeof (hostcache[n].cname));
907 case CCREP_PLAYER_INFO:
908 // we got a CCREP_PLAYER_INFO??
909 //if (developer.integer)
910 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
912 case CCREP_RULE_INFO:
913 // we got a CCREP_RULE_INFO??
914 //if (developer.integer)
915 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
921 // we may not have liked the packet, but it was a valid control
922 // packet, so we're done processing this packet now
926 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)
927 CL_ParseServerMessage();
931 void NetConn_ClientFrame(void)
934 lhnetaddress_t peeraddress;
936 NetConn_UpdateServerStuff();
937 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
939 if (cls.connect_remainingtries == 0)
941 cls.connect_trying = false;
942 M_Update_Return_Reason("Connect: Failed");
945 cls.connect_nextsendtime = realtime + 1;
946 cls.connect_remainingtries--;
947 // try challenge first (newer server)
948 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
949 // then try netquake as a fallback (old server, or netquake)
950 SZ_Clear(&net_message);
951 // save space for the header, filled in later
952 MSG_WriteLong(&net_message, 0);
953 MSG_WriteByte(&net_message, CCREQ_CONNECT);
954 MSG_WriteString(&net_message, "QUAKE");
955 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
956 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
957 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
958 SZ_Clear(&net_message);
960 for (i = 0;i < cl_numsockets;i++)
961 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
962 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
963 if (cls.netcon && realtime > cls.netcon->timeout)
965 Con_Print("Connection timed out\n");
967 Host_ShutdownServer (false);
969 for (conn = netconn_list;conn;conn = conn->next)
970 NetConn_ReSendMessage(conn);
973 #define MAX_CHALLENGES 128
976 lhnetaddress_t address;
980 challenge[MAX_CHALLENGES];
982 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
986 for (i = 0;i < bufferlength - 1;i++)
990 c = rand () % (127 - 33) + 33;
991 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
997 extern void SV_ConnectClient(int clientnum, netconn_t *netconnection);
998 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1000 int i, n, ret, clientnum, responselength, best;
1004 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1008 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1010 // received a command string - strip off the packaging and put it
1011 // into our string buffer with NULL termination
1014 length = min(length, (int)sizeof(stringbuf) - 1);
1015 memcpy(stringbuf, data, length);
1016 stringbuf[length] = 0;
1019 if (developer.integer)
1021 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1022 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1023 Com_HexDumpToConsole(data, length);
1026 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1028 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1030 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1032 if (besttime > challenge[i].time)
1033 besttime = challenge[best = i].time;
1035 // if we did not find an exact match, choose the oldest and
1036 // update address and string
1037 if (i == MAX_CHALLENGES)
1040 challenge[i].address = *peeraddress;
1041 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1043 challenge[i].time = realtime;
1044 // send the challenge
1045 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1048 if (length > 8 && !memcmp(string, "connect\\", 8))
1052 if ((s = SearchInfostring(string, "challenge")))
1054 // validate the challenge
1055 for (i = 0;i < MAX_CHALLENGES;i++)
1056 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1058 if (i < MAX_CHALLENGES)
1060 // check engine protocol
1061 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1063 if (developer.integer)
1064 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1065 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1069 // see if this is a duplicate connection request
1070 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1071 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1073 if (clientnum < svs.maxclients)
1075 // duplicate connection request
1076 if (realtime - client->netconnection->connecttime < 2.0)
1078 // client is still trying to connect,
1079 // so we send a duplicate reply
1080 if (developer.integer)
1081 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1082 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1084 // only kick if old connection seems dead
1085 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1087 // kick off connection and await retry
1088 client->deadsocket = true;
1093 // this is a new client, find a slot
1094 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1095 if (!client->active)
1097 if (clientnum < svs.maxclients)
1099 // prepare the client struct
1100 if ((conn = NetConn_Open(mysocket, peeraddress)))
1102 // allocated connection
1103 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1104 if (developer.integer)
1105 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1106 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1107 // now set up the client
1108 SV_ConnectClient(clientnum, conn);
1109 NetConn_Heartbeat(1);
1115 if (developer.integer)
1116 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1117 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1125 if (length >= 7 && !memcmp(string, "getinfo", 7))
1127 const char *challenge = NULL;
1128 // If there was a challenge in the getinfo message
1129 if (length > 8 && string[7] == ' ')
1130 challenge = string + 8;
1131 for (i = 0, n = 0;i < svs.maxclients;i++)
1132 if (svs.clients[i].active)
1134 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1135 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1136 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1137 gamename, com_modname, svs.maxclients, n,
1138 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1139 // does it fit in the buffer?
1140 if (responselength < (int)sizeof(response))
1142 if (developer.integer)
1143 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1144 NetConn_WriteString(mysocket, response, peeraddress);
1149 if (!strncmp(string, "ping", 4))
1151 if (developer.integer)
1152 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1153 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1156 if (!strncmp(string, "ack", 3))
1159 // we may not have liked the packet, but it was a command packet, so
1160 // we're done processing this packet now
1163 // LordHavoc: disabled netquake control packet support in server
1167 // netquake control packets, supported for compatibility only
1168 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1173 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1177 //if (developer.integer)
1178 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1179 if (length >= (int)strlen("QUAKE") + 1 + 1)
1181 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1183 if (developer.integer)
1184 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1185 SZ_Clear(&net_message);
1186 // save space for the header, filled in later
1187 MSG_WriteLong(&net_message, 0);
1188 MSG_WriteByte(&net_message, CCREP_REJECT);
1189 MSG_WriteString(&net_message, "Incompatible version.\n");
1190 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1191 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1192 SZ_Clear(&net_message);
1196 // see if this is a duplicate connection request
1197 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1198 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1200 if (clientnum < svs.maxclients)
1202 // duplicate connection request
1203 if (realtime - client->netconnection->connecttime < 2.0)
1205 // client is still trying to connect,
1206 // so we send a duplicate reply
1207 if (developer.integer)
1208 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1209 SZ_Clear(&net_message);
1210 // save space for the header, filled in later
1211 MSG_WriteLong(&net_message, 0);
1212 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1213 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1214 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1215 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1216 SZ_Clear(&net_message);
1218 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1220 // the old client hasn't sent us anything
1221 // in quite a while, so kick off and let
1222 // the retry take care of it...
1223 client->deadsocket = true;
1228 // this is a new client, find a slot
1229 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1230 if (!client->active)
1232 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1234 // connect to the client
1235 // everything is allocated, just fill in the details
1236 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1237 if (developer.integer)
1238 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1239 // send back the info about the server connection
1240 SZ_Clear(&net_message);
1241 // save space for the header, filled in later
1242 MSG_WriteLong(&net_message, 0);
1243 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1244 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1245 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1246 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1247 SZ_Clear(&net_message);
1248 // now set up the client struct
1249 SV_ConnectClient(clientnum, conn);
1250 NetConn_Heartbeat(1);
1254 //if (developer.integer)
1255 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1256 // no room; try to let player know
1257 SZ_Clear(&net_message);
1258 // save space for the header, filled in later
1259 MSG_WriteLong(&net_message, 0);
1260 MSG_WriteByte(&net_message, CCREP_REJECT);
1261 MSG_WriteString(&net_message, "Server is full.\n");
1262 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1263 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1264 SZ_Clear(&net_message);
1271 case CCREQ_SERVER_INFO:
1272 if (developer.integer)
1273 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1274 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1276 if (developer.integer)
1277 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1278 SZ_Clear(&net_message);
1279 // save space for the header, filled in later
1280 MSG_WriteLong(&net_message, 0);
1281 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1282 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1283 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1284 MSG_WriteString(&net_message, hostname.string);
1285 MSG_WriteString(&net_message, sv.name);
1286 MSG_WriteByte(&net_message, net_activeconnections);
1287 MSG_WriteByte(&net_message, svs.maxclients);
1288 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1289 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1290 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1291 SZ_Clear(&net_message);
1294 case CCREQ_PLAYER_INFO:
1295 if (developer.integer)
1296 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1299 int playerNumber, activeNumber, clientNumber;
1302 playerNumber = MSG_ReadByte();
1304 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1305 if (client->active && ++activeNumber == playerNumber)
1307 if (clientNumber != svs.maxclients)
1309 SZ_Clear(&net_message);
1310 // save space for the header, filled in later
1311 MSG_WriteLong(&net_message, 0);
1312 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1313 MSG_WriteByte(&net_message, playerNumber);
1314 MSG_WriteString(&net_message, client->name);
1315 MSG_WriteLong(&net_message, client->colors);
1316 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1317 MSG_WriteLong(&net_message, (int)(realtime - client->netconnection->connecttime));
1318 MSG_WriteString(&net_message, client->netconnection->address);
1319 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1320 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1321 SZ_Clear(&net_message);
1325 case CCREQ_RULE_INFO:
1326 if (developer.integer)
1327 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1333 // find the search start location
1334 prevCvarName = MSG_ReadString();
1335 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1337 // send the response
1338 SZ_Clear(&net_message);
1339 // save space for the header, filled in later
1340 MSG_WriteLong(&net_message, 0);
1341 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1344 MSG_WriteString(&net_message, var->name);
1345 MSG_WriteString(&net_message, var->string);
1347 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1348 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1349 SZ_Clear(&net_message);
1356 // we may not have liked the packet, but it was a valid control
1357 // packet, so we're done processing this packet now
1362 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1364 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1366 sv_player = host_client->edict;
1367 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1368 SV_ReadClientMessage();
1376 void NetConn_ServerFrame(void)
1379 lhnetaddress_t peeraddress;
1381 NetConn_UpdateServerStuff();
1382 for (i = 0;i < sv_numsockets;i++)
1383 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1384 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1385 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1387 // never timeout loopback connections
1388 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(host_client->netconnection->mysocket)) != LHNETADDRESSTYPE_LOOP)
1390 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1391 sv_player = host_client->edict;
1392 SV_DropClient(false);
1395 for (conn = netconn_list;conn;conn = conn->next)
1396 NetConn_ReSendMessage(conn);
1399 void NetConn_QueryMasters(void)
1403 lhnetaddress_t masteraddress;
1406 if (hostCacheCount >= HOSTCACHESIZE)
1409 for (i = 0;i < cl_numsockets;i++)
1416 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1418 SZ_Clear(&net_message);
1419 // save space for the header, filled in later
1420 MSG_WriteLong(&net_message, 0);
1421 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1422 MSG_WriteString(&net_message, "QUAKE");
1423 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1424 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1425 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1426 SZ_Clear(&net_message);
1430 // build the getservers
1431 snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1434 for (masternum = 0;sv_masters[masternum].name;masternum++)
1436 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1439 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1444 if (!masterquerycount)
1446 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1447 M_Update_Return_Reason("No network");
1451 void NetConn_Heartbeat(int priority)
1453 lhnetaddress_t masteraddress;
1455 lhnetsocket_t *mysocket;
1457 // if it's a state change (client connected), limit next heartbeat to no
1458 // more than 30 sec in the future
1459 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1460 nextheartbeattime = realtime + 30.0;
1462 // limit heartbeatperiod to 30 to 270 second range,
1463 // lower limit is to avoid abusing master servers with excess traffic,
1464 // upper limit is to avoid timing out on the master server (which uses
1466 if (sv_heartbeatperiod.value < 30)
1467 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1468 if (sv_heartbeatperiod.value > 270)
1469 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1471 // make advertising optional and don't advertise singleplayer games, and
1472 // only send a heartbeat as often as the admin wants
1473 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1475 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1476 for (masternum = 0;sv_masters[masternum].name;masternum++)
1477 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1478 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1482 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1485 qbyte sent[MAX_SCOREBOARD];
1487 memset(sent, 0, sizeof(sent));
1489 // simultaneously wait for the first CanSendMessage and send the message,
1490 // then wait for a second CanSendMessage (verifying it was received), or
1491 // the client drops and is no longer counted
1492 // the loop aborts when either it runs out of clients to send to, or a
1494 blocktime += Sys_DoubleTime();
1498 NetConn_ClientFrame();
1499 NetConn_ServerFrame();
1500 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1502 if (host_client->netconnection)
1504 if (NetConn_CanSendMessage(host_client->netconnection))
1507 NetConn_SendReliableMessage(host_client->netconnection, data);
1510 if (!NetConn_CanSendMessage(host_client->netconnection))
1515 while (count && Sys_DoubleTime() < blocktime);
1519 static void Net_Heartbeat_f(void)
1522 NetConn_Heartbeat(2);
1524 Con_Print("No server running, can not heartbeat to master server.\n");
1527 void PrintStats(netconn_t *conn)
1529 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1532 void Net_Stats_f(void)
1535 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1536 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1537 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1538 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1539 Con_Printf("packetsSent = %i\n", packetsSent);
1540 Con_Printf("packetsReSent = %i\n", packetsReSent);
1541 Con_Printf("packetsReceived = %i\n", packetsReceived);
1542 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1543 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1544 Con_Print("connections =\n");
1545 for (conn = netconn_list;conn;conn = conn->next)
1549 void Net_Slist_f(void)
1551 masterquerytime = realtime;
1552 masterquerycount = 0;
1553 masterreplycount = 0;
1554 serverquerycount = 0;
1555 serverreplycount = 0;
1557 memset(&pingcache, 0, sizeof(pingcache));
1558 if (m_state != m_slist)
1559 Con_Print("Sending requests to master servers\n");
1560 NetConn_QueryMasters();
1561 if (m_state != m_slist)
1562 Con_Print("Listening for replies...\n");
1565 void NetConn_Init(void)
1568 lhnetaddress_t tempaddress;
1569 netconn_mempool = Mem_AllocPool("Networking", 0, NULL);
1570 Cmd_AddCommand("net_stats", Net_Stats_f);
1571 Cmd_AddCommand("net_slist", Net_Slist_f);
1572 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1573 Cvar_RegisterVariable(&net_messagetimeout);
1574 Cvar_RegisterVariable(&net_messagerejointimeout);
1575 Cvar_RegisterVariable(&net_connecttimeout);
1576 Cvar_RegisterVariable(&cl_netlocalping);
1577 Cvar_RegisterVariable(&cl_netpacketloss);
1578 Cvar_RegisterVariable(&hostname);
1579 Cvar_RegisterVariable(&developer_networking);
1580 Cvar_RegisterVariable(&cl_netport);
1581 Cvar_RegisterVariable(&sv_netport);
1582 Cvar_RegisterVariable(&net_address);
1583 //Cvar_RegisterVariable(&net_address_ipv6);
1584 Cvar_RegisterVariable(&sv_public);
1585 Cvar_RegisterVariable(&sv_heartbeatperiod);
1586 for (i = 0;sv_masters[i].name;i++)
1587 Cvar_RegisterVariable(&sv_masters[i]);
1588 // COMMANDLINEOPTION: Server: -ip <ipaddress> sets the ip address of this machine for purposes of networking (default 0.0.0.0 also known as INADDR_ANY), use only if you have multiple network adapters and need to choose one specifically.
1589 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1591 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1593 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
1594 Cvar_SetQuick(&net_address, com_argv[i + 1]);
1597 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1599 // COMMANDLINEOPTION: Server: -port <portnumber> sets the port to use for a server (default 26000, the same port as QUAKE itself), useful if you host multiple servers on your machine
1600 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1602 i = atoi(com_argv[i + 1]);
1603 if (i >= 0 && i < 65536)
1605 Con_Printf("-port option used, setting port cvar to %i\n", i);
1606 Cvar_SetValueQuick(&sv_netport, i);
1609 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1613 memset(&pingcache, 0, sizeof(pingcache));
1614 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1618 void NetConn_Shutdown(void)
1620 NetConn_CloseClientPorts();
1621 NetConn_CloseServerPorts();