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 // the connection request succeeded, stop current connection and set up a new connection
609 cls.netcon = NetConn_Open(mysocket, peeraddress);
610 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
613 cls.demonum = -1; // not in the demo loop now
614 cls.state = ca_connected;
615 cls.signon = 0; // need all the signon messages before playing
617 SCR_BeginLoadingPlaque();
620 int NetConn_IsLocalGame(void)
622 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
630 lhnetaddress_t peeraddress;
632 pingcache[HOSTCACHESIZE];
634 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
637 lhnetaddress_t svaddress;
639 char *string, addressstring2[128], cname[128], ipstring[32];
640 char stringbuf[16384];
642 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
644 // received a command string - strip off the packaging and put it
645 // into our string buffer with NULL termination
648 length = min(length, (int)sizeof(stringbuf) - 1);
649 memcpy(stringbuf, data, length);
650 stringbuf[length] = 0;
653 if (developer.integer)
655 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
656 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
657 Com_HexDumpToConsole(data, length);
660 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
662 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
663 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
664 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
667 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
669 NetConn_ConnectionEstablished(mysocket, peeraddress);
672 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
674 cls.connect_trying = false;
676 length = max(length - 7, (int)sizeof(m_return_reason) - 1);
677 memcpy(m_return_reason, string, length);
678 m_return_reason[length] = 0;
679 Con_Printf("%s\n", m_return_reason);
682 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
684 int i, j, c, n, users, maxusers;
685 char game[32], mod[32], map[32], name[128];
689 // hostcache only uses text addresses
690 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
691 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(game, s, sizeof (game));else game[0] = 0;
692 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(mod , s, sizeof (mod ));else mod[0] = 0;
693 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(map , s, sizeof (map ));else map[0] = 0;
694 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(name, s, sizeof (name));else name[0] = 0;
695 if ((s = SearchInfostring(string, "protocol" )) != NULL) c = atoi(s);else c = -1;
696 if ((s = SearchInfostring(string, "clients" )) != NULL) users = atoi(s);else users = 0;
697 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) maxusers = atoi(s);else maxusers = 0;
698 // search the cache for this server and update it
699 for (n = 0; n < hostCacheCount; n++)
701 if (!strcmp(cname, hostcache[n].cname))
703 if (hostcache[n].ping == 100000)
705 pingtime = (int)((realtime - hostcache[n].querytime) * 1000.0);
706 pingtime = bound(0, pingtime, 9999);
708 hostcache[n].ping = pingtime;
709 // build description strings for the things users care about
710 snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, c != NET_PROTOCOL_VERSION ? '*' : ' ', users, maxusers, name);
711 snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", cname, game, mod, map);
712 // if ping is especially high, display it as such
715 // orange numbers (lower block)
716 for (i = 0;i < 5;i++)
717 if (hostcache[n].line1[i] != ' ')
718 hostcache[n].line1[i] += 128;
720 else if (pingtime >= 200)
722 // yellow numbers (in upper block)
723 for (i = 0;i < 5;i++)
724 if (hostcache[n].line1[i] != ' ')
725 hostcache[n].line1[i] -= 30;
727 // if not in the slist menu we should print the server to console
728 if (m_state != m_slist)
729 Con_Printf("%s\n%s\n", hostcache[n].line1, hostcache[n].line2);
730 // and finally, re-sort the list
731 for (i = 0;i < hostCacheCount;i++)
733 for (j = i + 1;j < hostCacheCount;j++)
735 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
736 if (hostcache[i].ping > hostcache[j].ping)
738 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
739 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
740 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
749 if (!strncmp(string, "getserversResponse\\", 19) && hostCacheCount < HOSTCACHESIZE)
753 // Extract the IP addresses
757 if (m_state != m_slist)
758 Con_Print("received server list...\n");
759 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
761 snprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
762 if (developer.integer)
763 Con_Printf("Requesting info from server %s\n", ipstring);
764 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
765 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
768 // add to slist (hostCache)
769 // search the cache for this server
770 for (n = 0; n < hostCacheCount; n++)
771 if (!strcmp(ipstring, hostcache[n].cname))
773 // add it or update it
774 if (n == hostCacheCount)
776 // if cache is full replace highest ping server (the list is
777 // kept sorted so this is always the last, and if this server
778 // is good it will be sorted into an early part of the list)
779 if (hostCacheCount >= HOSTCACHESIZE)
780 n = hostCacheCount - 1;
787 memset(&hostcache[n], 0, sizeof(hostcache[n]));
788 // store the data the engine cares about (address and ping)
789 strlcpy (hostcache[n].cname, ipstring, sizeof (hostcache[n].cname));
790 hostcache[n].ping = 100000;
791 hostcache[n].querytime = realtime;
792 // build description strings for the things users care about
793 strlcpy (hostcache[n].line1, "?", sizeof (hostcache[n].line1));
794 strlcpy (hostcache[n].line2, ipstring, sizeof (hostcache[n].line2));
795 // if not in the slist menu we should print the server to console
796 if (m_state != m_slist)
797 Con_Printf("querying %s\n", ipstring);
798 // and finally, re-sort the list
799 for (i = 0;i < hostCacheCount;i++)
801 for (j = i + 1;j < hostCacheCount;j++)
803 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
804 if (hostcache[i].ping > hostcache[j].ping)
806 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
807 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
808 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
814 // move on to next address in packet
821 if (!strncmp(string, "ping", 4))
823 if (developer.integer)
824 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
825 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
828 if (!strncmp(string, "ack", 3))
831 // we may not have liked the packet, but it was a command packet, so
832 // we're done processing this packet now
835 // netquake control packets, supported for compatibility only
836 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
841 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
845 if (developer.integer)
846 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
847 if (cls.connect_trying)
849 lhnetaddress_t clientportaddress;
850 clientportaddress = *peeraddress;
853 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
856 LHNETADDRESS_SetPort(&clientportaddress, port);
858 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
862 if (developer.integer)
863 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
864 Con_Printf("%s\n", data);
865 strlcpy (m_return_reason, data, sizeof (m_return_reason));
868 case CCREP_SERVER_INFO:
869 if (developer.integer)
870 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
871 if (cls.state != ca_dedicated)
873 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
874 // string we just ignore it and keep the real address
876 // hostcache only uses text addresses
877 cname = UDP_AddrToString(readaddr);
878 // search the cache for this server
879 for (n = 0; n < hostCacheCount; n++)
880 if (!strcmp(cname, hostcache[n].cname))
883 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
886 memset(&hostcache[n], 0, sizeof(hostcache[n]));
887 strlcpy (hostcache[n].name, MSG_ReadString(), sizeof (hostcache[n].name));
888 strlcpy (hostcache[n].map, MSG_ReadString(), sizeof (hostcache[n].map));
889 hostcache[n].users = MSG_ReadByte();
890 hostcache[n].maxusers = MSG_ReadByte();
892 if (c != NET_PROTOCOL_VERSION)
894 strlcpy (hostcache[n].cname, hostcache[n].name, sizeof (hostcache[n].cname));
895 strcpy(hostcache[n].name, "*");
896 strlcat (hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name));
898 strlcpy (hostcache[n].cname, cname, sizeof (hostcache[n].cname));
902 case CCREP_PLAYER_INFO:
903 // we got a CCREP_PLAYER_INFO??
904 //if (developer.integer)
905 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
907 case CCREP_RULE_INFO:
908 // we got a CCREP_RULE_INFO??
909 //if (developer.integer)
910 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
916 // we may not have liked the packet, but it was a valid control
917 // packet, so we're done processing this packet now
921 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)
922 CL_ParseServerMessage();
926 void NetConn_ClientFrame(void)
929 lhnetaddress_t peeraddress;
931 NetConn_UpdateServerStuff();
932 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
934 if (cls.connect_remainingtries == 0)
936 cls.connect_trying = false;
937 if (m_state == m_slist)
938 strcpy (m_return_reason, "Connect: Failed");
940 Con_Print("Connect failed\n");
943 if (cls.connect_nextsendtime)
945 if (m_state == m_slist)
946 strcpy (m_return_reason, "Connect: Still trying");
948 Con_Print("Still trying...\n");
952 if (m_state == m_slist)
953 strcpy (m_return_reason, "Connect: Trying");
955 Con_Print("Trying...\n");
957 cls.connect_nextsendtime = realtime + 1;
958 cls.connect_remainingtries--;
959 // try challenge first (newer server)
960 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
961 // then try netquake as a fallback (old server, or netquake)
962 SZ_Clear(&net_message);
963 // save space for the header, filled in later
964 MSG_WriteLong(&net_message, 0);
965 MSG_WriteByte(&net_message, CCREQ_CONNECT);
966 MSG_WriteString(&net_message, "QUAKE");
967 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
968 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
969 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
970 SZ_Clear(&net_message);
972 for (i = 0;i < cl_numsockets;i++)
973 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
974 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
975 if (cls.netcon && realtime > cls.netcon->timeout)
977 Con_Print("Connection timed out\n");
979 Host_ShutdownServer (false);
981 for (conn = netconn_list;conn;conn = conn->next)
982 NetConn_ReSendMessage(conn);
985 #define MAX_CHALLENGES 128
988 lhnetaddress_t address;
992 challenge[MAX_CHALLENGES];
994 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
998 for (i = 0;i < bufferlength - 1;i++)
1002 c = rand () % (127 - 33) + 33;
1003 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1009 extern void SV_ConnectClient(int clientnum, netconn_t *netconnection);
1010 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1012 int i, n, ret, clientnum, responselength, best;
1016 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1020 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1022 // received a command string - strip off the packaging and put it
1023 // into our string buffer with NULL termination
1026 length = min(length, (int)sizeof(stringbuf) - 1);
1027 memcpy(stringbuf, data, length);
1028 stringbuf[length] = 0;
1031 if (developer.integer)
1033 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1034 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1035 Com_HexDumpToConsole(data, length);
1038 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1040 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1042 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1044 if (besttime > challenge[i].time)
1045 besttime = challenge[best = i].time;
1047 // if we did not find an exact match, choose the oldest and
1048 // update address and string
1049 if (i == MAX_CHALLENGES)
1052 challenge[i].address = *peeraddress;
1053 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1055 challenge[i].time = realtime;
1056 // send the challenge
1057 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1060 if (length > 8 && !memcmp(string, "connect\\", 8))
1064 if ((s = SearchInfostring(string, "challenge")))
1066 // validate the challenge
1067 for (i = 0;i < MAX_CHALLENGES;i++)
1068 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1070 if (i < MAX_CHALLENGES)
1072 // check engine protocol
1073 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1075 if (developer.integer)
1076 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1077 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1081 // see if this is a duplicate connection request
1082 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1083 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1085 if (clientnum < svs.maxclients)
1087 // duplicate connection request
1088 if (realtime - client->netconnection->connecttime < 2.0)
1090 // client is still trying to connect,
1091 // so we send a duplicate reply
1092 if (developer.integer)
1093 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1094 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1096 // only kick if old connection seems dead
1097 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1099 // kick off connection and await retry
1100 client->deadsocket = true;
1105 // this is a new client, find a slot
1106 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1107 if (!client->active)
1109 if (clientnum < svs.maxclients)
1111 // prepare the client struct
1112 if ((conn = NetConn_Open(mysocket, peeraddress)))
1114 // allocated connection
1115 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1116 if (developer.integer)
1117 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1118 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1119 // now set up the client
1120 SV_ConnectClient(clientnum, conn);
1121 NetConn_Heartbeat(1);
1127 if (developer.integer)
1128 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1129 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1137 if (length >= 7 && !memcmp(string, "getinfo", 7))
1139 const char *challenge = NULL;
1140 // If there was a challenge in the getinfo message
1141 if (length > 8 && string[7] == ' ')
1142 challenge = string + 8;
1143 for (i = 0, n = 0;i < svs.maxclients;i++)
1144 if (svs.clients[i].active)
1146 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1147 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1148 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1149 gamename, com_modname, svs.maxclients, n,
1150 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1151 // does it fit in the buffer?
1152 if (responselength < (int)sizeof(response))
1154 if (developer.integer)
1155 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1156 NetConn_WriteString(mysocket, response, peeraddress);
1161 if (!strncmp(string, "ping", 4))
1163 if (developer.integer)
1164 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1165 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1168 if (!strncmp(string, "ack", 3))
1171 // we may not have liked the packet, but it was a command packet, so
1172 // we're done processing this packet now
1175 // LordHavoc: disabled netquake control packet support in server
1179 // netquake control packets, supported for compatibility only
1180 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1185 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1189 //if (developer.integer)
1190 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1191 if (length >= (int)strlen("QUAKE") + 1 + 1)
1193 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1195 if (developer.integer)
1196 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1197 SZ_Clear(&net_message);
1198 // save space for the header, filled in later
1199 MSG_WriteLong(&net_message, 0);
1200 MSG_WriteByte(&net_message, CCREP_REJECT);
1201 MSG_WriteString(&net_message, "Incompatible version.\n");
1202 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1203 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1204 SZ_Clear(&net_message);
1208 // see if this is a duplicate connection request
1209 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1210 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1212 if (clientnum < svs.maxclients)
1214 // duplicate connection request
1215 if (realtime - client->netconnection->connecttime < 2.0)
1217 // client is still trying to connect,
1218 // so we send a duplicate reply
1219 if (developer.integer)
1220 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1221 SZ_Clear(&net_message);
1222 // save space for the header, filled in later
1223 MSG_WriteLong(&net_message, 0);
1224 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1225 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1226 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1227 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1228 SZ_Clear(&net_message);
1230 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1232 // the old client hasn't sent us anything
1233 // in quite a while, so kick off and let
1234 // the retry take care of it...
1235 client->deadsocket = true;
1240 // this is a new client, find a slot
1241 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1242 if (!client->active)
1244 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1246 // connect to the client
1247 // everything is allocated, just fill in the details
1248 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1249 if (developer.integer)
1250 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1251 // send back the info about the server connection
1252 SZ_Clear(&net_message);
1253 // save space for the header, filled in later
1254 MSG_WriteLong(&net_message, 0);
1255 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1256 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1257 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1258 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1259 SZ_Clear(&net_message);
1260 // now set up the client struct
1261 SV_ConnectClient(clientnum, conn);
1262 NetConn_Heartbeat(1);
1266 //if (developer.integer)
1267 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1268 // no room; try to let player know
1269 SZ_Clear(&net_message);
1270 // save space for the header, filled in later
1271 MSG_WriteLong(&net_message, 0);
1272 MSG_WriteByte(&net_message, CCREP_REJECT);
1273 MSG_WriteString(&net_message, "Server is full.\n");
1274 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1275 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1276 SZ_Clear(&net_message);
1283 case CCREQ_SERVER_INFO:
1284 if (developer.integer)
1285 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1286 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1288 if (developer.integer)
1289 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1290 SZ_Clear(&net_message);
1291 // save space for the header, filled in later
1292 MSG_WriteLong(&net_message, 0);
1293 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1294 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1295 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1296 MSG_WriteString(&net_message, hostname.string);
1297 MSG_WriteString(&net_message, sv.name);
1298 MSG_WriteByte(&net_message, net_activeconnections);
1299 MSG_WriteByte(&net_message, svs.maxclients);
1300 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1301 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1302 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1303 SZ_Clear(&net_message);
1306 case CCREQ_PLAYER_INFO:
1307 if (developer.integer)
1308 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1311 int playerNumber, activeNumber, clientNumber;
1314 playerNumber = MSG_ReadByte();
1316 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1317 if (client->active && ++activeNumber == playerNumber)
1319 if (clientNumber != svs.maxclients)
1321 SZ_Clear(&net_message);
1322 // save space for the header, filled in later
1323 MSG_WriteLong(&net_message, 0);
1324 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1325 MSG_WriteByte(&net_message, playerNumber);
1326 MSG_WriteString(&net_message, client->name);
1327 MSG_WriteLong(&net_message, client->colors);
1328 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1329 MSG_WriteLong(&net_message, (int)(realtime - client->netconnection->connecttime));
1330 MSG_WriteString(&net_message, client->netconnection->address);
1331 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1332 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1333 SZ_Clear(&net_message);
1337 case CCREQ_RULE_INFO:
1338 if (developer.integer)
1339 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1345 // find the search start location
1346 prevCvarName = MSG_ReadString();
1347 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1349 // send the response
1350 SZ_Clear(&net_message);
1351 // save space for the header, filled in later
1352 MSG_WriteLong(&net_message, 0);
1353 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1356 MSG_WriteString(&net_message, var->name);
1357 MSG_WriteString(&net_message, var->string);
1359 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1360 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1361 SZ_Clear(&net_message);
1368 // we may not have liked the packet, but it was a valid control
1369 // packet, so we're done processing this packet now
1374 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1376 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1378 sv_player = host_client->edict;
1379 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1380 SV_ReadClientMessage();
1388 void NetConn_ServerFrame(void)
1391 lhnetaddress_t peeraddress;
1393 NetConn_UpdateServerStuff();
1394 for (i = 0;i < sv_numsockets;i++)
1395 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1396 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1397 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1399 // never timeout loopback connections
1400 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(host_client->netconnection->mysocket)) != LHNETADDRESSTYPE_LOOP)
1402 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1403 sv_player = host_client->edict;
1404 SV_DropClient(false);
1407 for (conn = netconn_list;conn;conn = conn->next)
1408 NetConn_ReSendMessage(conn);
1411 void NetConn_QueryMasters(void)
1415 lhnetaddress_t masteraddress;
1418 if (hostCacheCount >= HOSTCACHESIZE)
1421 for (i = 0;i < cl_numsockets;i++)
1428 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1430 SZ_Clear(&net_message);
1431 // save space for the header, filled in later
1432 MSG_WriteLong(&net_message, 0);
1433 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1434 MSG_WriteString(&net_message, "QUAKE");
1435 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1436 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1437 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1438 SZ_Clear(&net_message);
1442 // build the getservers
1443 snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1446 for (masternum = 0;sv_masters[masternum].name;masternum++)
1448 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1451 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1456 if (!masterquerycount)
1458 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1459 strcpy(m_return_reason, "No network");
1463 void NetConn_Heartbeat(int priority)
1465 lhnetaddress_t masteraddress;
1467 lhnetsocket_t *mysocket;
1469 // if it's a state change (client connected), limit next heartbeat to no
1470 // more than 30 sec in the future
1471 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1472 nextheartbeattime = realtime + 30.0;
1474 // limit heartbeatperiod to 30 to 270 second range,
1475 // lower limit is to avoid abusing master servers with excess traffic,
1476 // upper limit is to avoid timing out on the master server (which uses
1478 if (sv_heartbeatperiod.value < 30)
1479 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1480 if (sv_heartbeatperiod.value > 270)
1481 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1483 // make advertising optional and don't advertise singleplayer games, and
1484 // only send a heartbeat as often as the admin wants
1485 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1487 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1488 for (masternum = 0;sv_masters[masternum].name;masternum++)
1489 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1490 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1494 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1497 qbyte sent[MAX_SCOREBOARD];
1499 memset(sent, 0, sizeof(sent));
1501 // simultaneously wait for the first CanSendMessage and send the message,
1502 // then wait for a second CanSendMessage (verifying it was received), or
1503 // the client drops and is no longer counted
1504 // the loop aborts when either it runs out of clients to send to, or a
1506 blocktime += Sys_DoubleTime();
1510 NetConn_ClientFrame();
1511 NetConn_ServerFrame();
1512 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1514 if (host_client->netconnection)
1516 if (NetConn_CanSendMessage(host_client->netconnection))
1519 NetConn_SendReliableMessage(host_client->netconnection, data);
1522 if (!NetConn_CanSendMessage(host_client->netconnection))
1527 while (count && Sys_DoubleTime() < blocktime);
1531 static void Net_Heartbeat_f(void)
1534 NetConn_Heartbeat(2);
1536 Con_Print("No server running, can not heartbeat to master server.\n");
1539 void PrintStats(netconn_t *conn)
1541 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1544 void Net_Stats_f(void)
1547 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1548 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1549 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1550 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1551 Con_Printf("packetsSent = %i\n", packetsSent);
1552 Con_Printf("packetsReSent = %i\n", packetsReSent);
1553 Con_Printf("packetsReceived = %i\n", packetsReceived);
1554 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1555 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1556 Con_Print("connections =\n");
1557 for (conn = netconn_list;conn;conn = conn->next)
1561 void Net_Slist_f(void)
1563 masterquerytime = realtime;
1564 masterquerycount = 0;
1565 masterreplycount = 0;
1566 serverquerycount = 0;
1567 serverreplycount = 0;
1569 memset(&pingcache, 0, sizeof(pingcache));
1570 if (m_state != m_slist)
1571 Con_Print("Sending requests to master servers\n");
1572 NetConn_QueryMasters();
1573 if (m_state != m_slist)
1574 Con_Print("Listening for replies...\n");
1577 void NetConn_Init(void)
1580 lhnetaddress_t tempaddress;
1581 netconn_mempool = Mem_AllocPool("Networking", 0, NULL);
1582 Cmd_AddCommand("net_stats", Net_Stats_f);
1583 Cmd_AddCommand("net_slist", Net_Slist_f);
1584 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1585 Cvar_RegisterVariable(&net_messagetimeout);
1586 Cvar_RegisterVariable(&net_messagerejointimeout);
1587 Cvar_RegisterVariable(&net_connecttimeout);
1588 Cvar_RegisterVariable(&cl_netlocalping);
1589 Cvar_RegisterVariable(&cl_netpacketloss);
1590 Cvar_RegisterVariable(&hostname);
1591 Cvar_RegisterVariable(&developer_networking);
1592 Cvar_RegisterVariable(&cl_netport);
1593 Cvar_RegisterVariable(&sv_netport);
1594 Cvar_RegisterVariable(&net_address);
1595 //Cvar_RegisterVariable(&net_address_ipv6);
1596 Cvar_RegisterVariable(&sv_public);
1597 Cvar_RegisterVariable(&sv_heartbeatperiod);
1598 for (i = 0;sv_masters[i].name;i++)
1599 Cvar_RegisterVariable(&sv_masters[i]);
1600 // 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.
1601 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1603 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1605 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
1606 Cvar_SetQuick(&net_address, com_argv[i + 1]);
1609 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1611 // 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
1612 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1614 i = atoi(com_argv[i + 1]);
1615 if (i >= 0 && i < 65536)
1617 Con_Printf("-port option used, setting port cvar to %i\n", i);
1618 Cvar_SetValueQuick(&sv_netport, i);
1621 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1625 memset(&pingcache, 0, sizeof(pingcache));
1626 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1630 void NetConn_Shutdown(void)
1632 NetConn_CloseClientPorts();
1633 NetConn_CloseServerPorts();