2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 See the GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 #define MASTER_PORT 27950
28 cvar_t sv_public = {0, "sv_public", "0"};
29 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "180"};
31 static cvar_t sv_masters [] =
33 {CVAR_SAVE, "sv_master1", ""},
34 {CVAR_SAVE, "sv_master2", ""},
35 {CVAR_SAVE, "sv_master3", ""},
36 {CVAR_SAVE, "sv_master4", ""},
37 {0, "sv_masterextra1", "198.88.152.4"},
38 {0, "sv_masterextra2", "68.102.242.12"},
42 static double nextheartbeattime = 0;
44 sizebuf_t net_message;
46 cvar_t net_messagetimeout = {0, "net_messagetimeout","300"};
47 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10"};
48 cvar_t net_connecttimeout = {0, "net_connecttimeout","10"};
49 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED"};
50 cvar_t developer_networking = {0, "developer_networking", "0"};
52 cvar_t cl_fakelocalping_min = {0, "cl_fakelocalping_min","0"};
53 cvar_t cl_fakelocalping_max = {0, "cl_fakelocalping_max","0"};
54 static cvar_t cl_fakepacketloss_receive = {0, "cl_fakepacketloss_receive","0"};
55 static cvar_t cl_fakepacketloss_send = {0, "cl_fakepacketloss_send","0"};
56 static cvar_t sv_fakepacketloss_receive = {0, "sv_fakepacketloss_receive","0"};
57 static cvar_t sv_fakepacketloss_send = {0, "sv_fakepacketloss_send","0"};
60 /* statistic counters */
61 static int packetsSent = 0;
62 static int packetsReSent = 0;
63 static int packetsReceived = 0;
64 static int receivedDuplicateCount = 0;
65 static int droppedDatagrams = 0;
67 static int unreliableMessagesSent = 0;
68 static int unreliableMessagesReceived = 0;
69 static int reliableMessagesSent = 0;
70 static int reliableMessagesReceived = 0;
72 int hostCacheCount = 0;
73 hostcache_t hostcache[HOSTCACHESIZE];
75 static qbyte sendbuffer[NET_MAXMESSAGE];
76 static qbyte readbuffer[NET_MAXMESSAGE];
79 lhnetsocket_t *cl_sockets[16];
81 lhnetsocket_t *sv_sockets[16];
83 netconn_t *netconn_list = NULL;
84 mempool_t *netconn_mempool = NULL;
86 cvar_t cl_netport = {0, "cl_port", "0"};
87 cvar_t cl_netaddress = {0, "cl_netaddress", "0.0.0.0"};
88 cvar_t cl_netaddress_ipv6 = {0, "cl_netaddress_ipv6", "[0:0:0:0:0:0:0:0]:0"};
90 cvar_t sv_netport = {0, "port", "26000"};
91 cvar_t sv_netaddress = {0, "sv_netaddress", "0.0.0.0"};
92 cvar_t sv_netaddress_ipv6 = {0, "sv_netaddress_ipv6", "[0:0:0:0:0:0:0:0]:26000"};
94 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
96 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
98 if (cl_fakepacketloss_receive.integer)
99 for (i = 0;i < cl_numsockets;i++)
100 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_fakepacketloss_receive.integer)
102 if (sv_fakepacketloss_receive.integer)
103 for (i = 0;i < cl_numsockets;i++)
104 if (sv_sockets[i] == mysocket && (rand() % 100) < sv_fakepacketloss_receive.integer)
106 if (developer_networking.integer && length != 0)
108 char addressstring[128], addressstring2[128];
109 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
112 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
113 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
114 Com_HexDumpToConsole(data, length);
117 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
122 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
126 if (cl_fakepacketloss_send.integer)
127 for (i = 0;i < cl_numsockets;i++)
128 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_fakepacketloss_send.integer)
130 if (sv_fakepacketloss_send.integer)
131 for (i = 0;i < cl_numsockets;i++)
132 if (sv_sockets[i] == mysocket && (rand() % 100) < sv_fakepacketloss_send.integer)
134 ret = LHNET_Write(mysocket, data, length, peeraddress);
135 if (developer_networking.integer)
137 char addressstring[128], addressstring2[128];
138 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
139 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
140 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
141 Com_HexDumpToConsole(data, length);
146 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
148 // note this does not include the trailing NULL because we add that in the parser
149 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
152 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
154 unsigned int packetLen;
155 unsigned int dataLen;
157 unsigned int *header;
160 if (data->cursize == 0)
161 Sys_Error("Datagram_SendMessage: zero length message\n");
163 if (data->cursize > NET_MAXMESSAGE)
164 Sys_Error("Datagram_SendMessage: message too big %u\n", data->cursize);
166 if (conn->canSend == false)
167 Sys_Error("SendMessage: called with canSend == false\n");
170 memcpy(conn->sendMessage, data->data, data->cursize);
171 conn->sendMessageLength = data->cursize;
173 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
175 dataLen = conn->sendMessageLength;
180 dataLen = MAX_PACKETFRAGMENT;
184 packetLen = NET_HEADERSIZE + dataLen;
186 header = (void *)sendbuffer;
187 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
188 header[1] = BigLong(conn->sendSequence);
189 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
191 conn->sendSequence++;
192 conn->canSend = false;
194 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
197 conn->lastSendTime = realtime;
199 reliableMessagesSent++;
203 static void NetConn_SendMessageNext(netconn_t *conn)
205 unsigned int packetLen;
206 unsigned int dataLen;
208 unsigned int *header;
210 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
212 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
214 dataLen = conn->sendMessageLength;
219 dataLen = MAX_PACKETFRAGMENT;
223 packetLen = NET_HEADERSIZE + dataLen;
225 header = (void *)sendbuffer;
226 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
227 header[1] = BigLong(conn->sendSequence);
228 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
230 conn->sendSequence++;
231 conn->sendNext = false;
233 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
236 conn->lastSendTime = realtime;
241 static void NetConn_ReSendMessage(netconn_t *conn)
243 unsigned int packetLen;
244 unsigned int dataLen;
246 unsigned int *header;
248 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
250 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
252 dataLen = conn->sendMessageLength;
257 dataLen = MAX_PACKETFRAGMENT;
261 packetLen = NET_HEADERSIZE + dataLen;
263 header = (void *)sendbuffer;
264 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
265 header[1] = BigLong(conn->sendSequence - 1);
266 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
268 conn->sendNext = false;
270 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
273 conn->lastSendTime = realtime;
278 qboolean NetConn_CanSendMessage(netconn_t *conn)
280 return conn->canSend;
283 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
289 if (data->cursize == 0)
290 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
292 if (data->cursize > MAX_DATAGRAM)
293 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
296 packetLen = NET_HEADERSIZE + data->cursize;
298 header = (void *)sendbuffer;
299 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
300 header[1] = BigLong(conn->unreliableSendSequence);
301 memcpy(sendbuffer + 8, data->data, data->cursize);
303 conn->unreliableSendSequence++;
305 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
309 unreliableMessagesSent++;
313 void NetConn_CloseClientPorts(void)
315 for (;cl_numsockets > 0;cl_numsockets--)
316 if (cl_sockets[cl_numsockets - 1])
317 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
320 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
322 lhnetaddress_t address;
324 char addressstring2[1024];
325 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
327 if ((s = LHNET_OpenSocket_Connectionless(&address)))
329 cl_sockets[cl_numsockets++] = s;
330 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
331 Con_Printf("Client opened a socket on address %s\n", addressstring2);
335 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
336 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
340 Con_Printf("Client unable to parse address %s\n", addressstring);
343 void NetConn_OpenClientPorts(void)
346 NetConn_CloseClientPorts();
347 port = bound(0, cl_netport.integer, 65535);
348 if (cl_netport.integer != port)
349 Cvar_SetValueQuick(&cl_netport, port);
350 Con_Printf("Client using port %i\n", port);
351 NetConn_OpenClientPort("local", port);
352 NetConn_OpenClientPort(cl_netaddress.string, port);
353 NetConn_OpenClientPort(cl_netaddress_ipv6.string, port);
356 void NetConn_CloseServerPorts(void)
358 for (;sv_numsockets > 0;sv_numsockets--)
359 if (sv_sockets[sv_numsockets - 1])
360 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
363 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
365 lhnetaddress_t address;
367 char addressstring2[1024];
368 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
370 if ((s = LHNET_OpenSocket_Connectionless(&address)))
372 sv_sockets[sv_numsockets++] = s;
373 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
374 Con_Printf("Server listening on address %s\n", addressstring2);
378 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
379 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
383 Con_Printf("Server unable to parse address %s\n", addressstring);
386 void NetConn_OpenServerPorts(int opennetports)
389 NetConn_CloseServerPorts();
390 port = bound(0, sv_netport.integer, 65535);
393 Con_Printf("Server using port %i\n", port);
394 if (sv_netport.integer != port)
395 Cvar_SetValueQuick(&sv_netport, port);
396 if (cls.state != ca_dedicated)
397 NetConn_OpenServerPort("local", port);
400 NetConn_OpenServerPort(sv_netaddress.string, port);
401 NetConn_OpenServerPort(sv_netaddress_ipv6.string, port);
403 if (sv_numsockets == 0)
404 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
407 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
409 int i, a = LHNETADDRESS_GetAddressType(address);
410 for (i = 0;i < cl_numsockets;i++)
411 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
412 return cl_sockets[i];
416 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
418 int i, a = LHNETADDRESS_GetAddressType(address);
419 for (i = 0;i < sv_numsockets;i++)
420 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
421 return sv_sockets[i];
425 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
428 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
429 conn->mysocket = mysocket;
430 conn->peeraddress = *peeraddress;
431 conn->canSend = true;
432 conn->connecttime = realtime;
433 conn->lastMessageTime = realtime;
434 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
435 // reduce effectiveness of connection request floods
436 conn->timeout = realtime + net_connecttimeout.value;
437 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
438 conn->next = netconn_list;
443 void NetConn_Close(netconn_t *conn)
446 // remove connection from list
447 if (conn == netconn_list)
448 netconn_list = conn->next;
451 for (c = netconn_list;c;c = c->next)
455 c->next = conn->next;
459 // not found in list, we'll avoid crashing here...
467 static int clientport = -1;
468 static int clientport2 = -1;
469 static int hostport = -1;
470 static void NetConn_UpdateServerStuff(void)
472 if (clientport2 != cl_netport.integer)
474 clientport2 = cl_netport.integer;
475 if (cls.state == ca_connected)
476 Con_Printf("Changing \"cl_port\" will not take effect until you reconnect.\n");
478 if (cls.state != ca_dedicated)
480 if (cls.state == ca_disconnected && clientport != cl_netport.integer)
482 clientport = cl_netport.integer;
483 NetConn_CloseClientPorts();
485 if (cl_numsockets == 0)
486 NetConn_OpenClientPorts();
489 if (hostport != sv_netport.integer)
491 hostport = sv_netport.integer;
493 Con_Printf("Changing \"port\" will not take effect until \"map\" command is executed.\n");
497 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
501 unsigned int sequence;
505 length = BigLong(((int *)data)[0]);
506 flags = length & ~NETFLAG_LENGTH_MASK;
507 length &= NETFLAG_LENGTH_MASK;
508 // control packets were already handled
509 if (!(flags & NETFLAG_CTL))
511 sequence = BigLong(((int *)data)[1]);
515 if (flags & NETFLAG_UNRELIABLE)
517 if (sequence >= conn->unreliableReceiveSequence)
519 if (sequence > conn->unreliableReceiveSequence)
521 count = sequence - conn->unreliableReceiveSequence;
522 droppedDatagrams += count;
523 Con_DPrintf("Dropped %u datagram(s)\n", count);
525 conn->unreliableReceiveSequence = sequence + 1;
526 conn->lastMessageTime = realtime;
527 conn->timeout = realtime + net_messagetimeout.value;
528 unreliableMessagesReceived++;
531 SZ_Clear(&net_message);
532 SZ_Write(&net_message, data, length);
538 Con_DPrintf("Got a stale datagram\n");
541 else if (flags & NETFLAG_ACK)
543 if (sequence == (conn->sendSequence - 1))
545 if (sequence == conn->ackSequence)
548 if (conn->ackSequence != conn->sendSequence)
549 Con_DPrintf("ack sequencing error\n");
550 conn->lastMessageTime = realtime;
551 conn->timeout = realtime + net_messagetimeout.value;
552 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
553 if (conn->sendMessageLength > 0)
555 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
556 conn->sendNext = true;
557 NetConn_SendMessageNext(conn);
561 conn->sendMessageLength = 0;
562 conn->canSend = true;
566 Con_DPrintf("Duplicate ACK received\n");
569 Con_DPrintf("Stale ACK received\n");
572 else if (flags & NETFLAG_DATA)
574 unsigned int temppacket[2];
575 temppacket[0] = BigLong(8 | NETFLAG_ACK);
576 temppacket[1] = BigLong(sequence);
577 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
578 if (sequence == conn->receiveSequence)
580 conn->lastMessageTime = realtime;
581 conn->timeout = realtime + net_messagetimeout.value;
582 conn->receiveSequence++;
583 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
584 conn->receiveMessageLength += length;
585 if (flags & NETFLAG_EOM)
587 reliableMessagesReceived++;
588 length = conn->receiveMessageLength;
589 conn->receiveMessageLength = 0;
592 SZ_Clear(&net_message);
593 SZ_Write(&net_message, conn->receiveMessage, length);
600 receivedDuplicateCount++;
608 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
610 cls.netcon = NetConn_Open(mysocket, peeraddress);
611 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
614 cls.connect_trying = false;
615 cls.demonum = -1; // not in the demo loop now
616 cls.state = ca_connected;
617 cls.signon = 0; // need all the signon messages before playing
622 int NetConn_IsLocalGame(void)
625 if (cls.state == ca_connected && sv.active/* && LHNETADDRESS_GetAddressType(cl.netcon->peeraddress) == LHNETADDRESSTYPE_LOOP*/)
627 // make sure there are no other connected clients
628 for (i = 1;i < MAX_SCOREBOARD;i++)
629 if (svs.connectedclients[i])
639 lhnetaddress_t peeraddress;
641 pingcache[HOSTCACHESIZE];
643 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
646 lhnetaddress_t svaddress;
648 char *string, addressstring2[128], cname[128], ipstring[32];
649 char stringbuf[16384];
651 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
653 // received a command string - strip off the packaging and put it
654 // into our string buffer with NULL termination
657 length = min(length, (int)sizeof(stringbuf) - 1);
658 memcpy(stringbuf, data, length);
659 stringbuf[length] = 0;
662 if (developer.integer)
664 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
665 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
666 Com_HexDumpToConsole(data, length);
669 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
671 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
672 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
673 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
676 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
678 NetConn_ConnectionEstablished(mysocket, peeraddress);
681 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
683 cls.connect_trying = false;
685 length = max(length - 7, (int)sizeof(m_return_reason) - 1);
686 memcpy(m_return_reason, string, length);
687 m_return_reason[length] = 0;
688 Con_Printf("%s\n", m_return_reason);
691 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
693 int i, j, c, n, users, maxusers;
694 char game[32], mod[32], map[32], name[128];
698 // hostcache only uses text addresses
699 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
700 // search the cache for this server
701 for (n = 0; n < hostCacheCount; n++)
702 if (!strcmp(cname, hostcache[n].cname))
704 // add it or update it
705 if (n == hostCacheCount)
707 // if cache is full replace highest ping server (the list is
708 // kept sorted so this is always the last, and if this server
709 // is good it will be sorted into an early part of the list)
710 if (hostCacheCount >= HOSTCACHESIZE)
711 n = hostCacheCount - 1;
715 if ((s = SearchInfostring(string, "gamename" )) != NULL) strncpy(game, s, sizeof(game) - 1);else game[0] = 0;
716 if ((s = SearchInfostring(string, "modname" )) != NULL) strncpy(mod , s, sizeof(mod ) - 1);else mod[0] = 0;
717 if ((s = SearchInfostring(string, "mapname" )) != NULL) strncpy(map , s, sizeof(map ) - 1);else map[0] = 0;
718 if ((s = SearchInfostring(string, "hostname" )) != NULL) strncpy(name, s, sizeof(name) - 1);else name[0] = 0;
719 if ((s = SearchInfostring(string, "protocol" )) != NULL) c = atoi(s);else c = -1;
720 if ((s = SearchInfostring(string, "clients" )) != NULL) users = atoi(s);else users = 0;
721 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) maxusers = atoi(s);else maxusers = 0;
723 for (i = 0;i < HOSTCACHESIZE;i++)
724 if (!LHNETADDRESS_Compare(peeraddress, &pingcache[i].peeraddress))
725 pingtime = (int)(realtime - pingcache[i].senttime);
726 pingtime = bound(0, pingtime, 9999);
727 memset(&hostcache[n], 0, sizeof(hostcache[n]));
728 // store the data the engine cares about (address and ping)
729 strcpy(hostcache[n].cname, cname);
730 hostcache[n].ping = pingtime;
731 // build description strings for the things users care about
732 snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, c != NET_PROTOCOL_VERSION ? '*' : ' ', users, maxusers, name);
733 snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", cname, game, mod, map);
734 // if ping is especially high, display it as such
737 // orange numbers (lower block)
738 for (i = 0;i < 5;i++)
739 if (hostcache[n].line1[i] != ' ')
740 hostcache[n].line1[i] += 128;
742 else if (pingtime >= 200)
744 // yellow numbers (in upper block)
745 for (i = 0;i < 5;i++)
746 if (hostcache[n].line1[i] != ' ')
747 hostcache[n].line1[i] -= 30;
749 // if not in the slist menu we should print the server to console
750 if (m_state != m_slist)
751 Con_Printf("%s\n%s\n", hostcache[n].line1, hostcache[n].line2);
752 // and finally, re-sort the list
753 for (i = 0;i < hostCacheCount;i++)
755 for (j = i + 1;j < hostCacheCount;j++)
757 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
758 if (hostcache[i].ping > hostcache[j].ping)
760 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
761 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
762 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
768 if (!strncmp(string, "getserversResponse\\", 19) && hostCacheCount < HOSTCACHESIZE)
772 // Extract the IP addresses
775 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
777 sprintf(ipstring, "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
778 if (developer.integer)
779 Con_Printf("Requesting info from server %s\n", ipstring);
780 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
781 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
782 // replace oldest or matching entry in ping cache
783 // we scan this later when getting a reply to see how long it took
786 for (i = 0;i < HOSTCACHESIZE;i++)
788 if (!LHNETADDRESS_Compare(&svaddress, &pingcache[i].peeraddress))
793 if (besttime > pingcache[i].senttime)
795 besttime = pingcache[i].senttime;
797 // if ping cache isn't full yet we can skip out early
802 pingcache[best].peeraddress = svaddress;
803 pingcache[best].senttime = realtime;
804 // move on to next address in packet
811 if (!strncmp(string, "ping", 4))
813 if (developer.integer)
814 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
815 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
818 if (!strncmp(string, "ack", 3))
821 // we may not have liked the packet, but it was a command packet, so
822 // we're done processing this packet now
825 // netquake control packets, supported for compatibility only
826 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
831 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
835 if (developer.integer)
836 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
837 if (cls.connect_trying)
839 lhnetaddress_t clientportaddress;
840 clientportaddress = *peeraddress;
843 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
846 LHNETADDRESS_SetPort(&clientportaddress, port);
848 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
852 if (developer.integer)
853 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
854 Con_Printf("%s\n", data);
855 strncpy(m_return_reason, data, sizeof(m_return_reason) - 1);
858 case CCREP_SERVER_INFO:
859 if (developer.integer)
860 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
861 if (cls.state != ca_dedicated)
863 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
864 // string we just ignore it and keep the real address
866 // hostcache only uses text addresses
867 cname = UDP_AddrToString(readaddr);
868 // search the cache for this server
869 for (n = 0; n < hostCacheCount; n++)
870 if (!strcmp(cname, hostcache[n].cname))
873 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
876 memset(&hostcache[n], 0, sizeof(hostcache[n]));
877 strcpy(hostcache[n].name, MSG_ReadString());
878 strcpy(hostcache[n].map, MSG_ReadString());
879 hostcache[n].users = MSG_ReadByte();
880 hostcache[n].maxusers = MSG_ReadByte();
882 if (c != NET_PROTOCOL_VERSION)
884 strncpy(hostcache[n].cname, hostcache[n].name, sizeof(hostcache[n].cname) - 1);
885 hostcache[n].cname[sizeof(hostcache[n].cname) - 1] = 0;
886 strcpy(hostcache[n].name, "*");
887 strncat(hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name) - 1);
888 hostcache[n].name[sizeof(hostcache[n].name) - 1] = 0;
890 strcpy(hostcache[n].cname, cname);
894 case CCREP_PLAYER_INFO:
895 // we got a CCREP_PLAYER_INFO??
896 //if (developer.integer)
897 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
899 case CCREP_RULE_INFO:
900 // we got a CCREP_RULE_INFO??
901 //if (developer.integer)
902 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
908 // we may not have liked the packet, but it was a valid control
909 // packet, so we're done processing this packet now
913 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)
914 CL_ParseServerMessage();
918 void NetConn_ClientFrame(void)
921 lhnetaddress_t peeraddress;
923 NetConn_UpdateServerStuff();
924 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
926 if (cls.connect_remainingtries == 0)
928 cls.connect_trying = false;
929 Host_Error("Connect failed\n");
932 if (cls.connect_nextsendtime)
933 Con_Printf("Still trying...\n");
935 Con_Printf("Trying...\n");
936 cls.connect_nextsendtime = realtime + 1;
937 cls.connect_remainingtries--;
938 // try challenge first (newer server)
939 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
940 // then try netquake as a fallback (old server, or netquake)
941 SZ_Clear(&net_message);
942 // save space for the header, filled in later
943 MSG_WriteLong(&net_message, 0);
944 MSG_WriteByte(&net_message, CCREQ_CONNECT);
945 MSG_WriteString(&net_message, "QUAKE");
946 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
947 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
948 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
949 SZ_Clear(&net_message);
951 for (i = 0;i < cl_numsockets;i++)
952 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
953 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
954 if (cls.netcon && realtime > cls.netcon->timeout)
956 Con_Printf("Connection timed out\n");
959 for (conn = netconn_list;conn;conn = conn->next)
960 NetConn_ReSendMessage(conn);
963 #define MAX_CHALLENGES 128
966 lhnetaddress_t address;
970 challenge[MAX_CHALLENGES];
972 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
976 for (i = 0;i < bufferlength - 1;i++)
980 c = rand () % (127 - 33) + 33;
981 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
987 extern void SV_ConnectClient(int clientnum, netconn_t *netconnection);
988 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
990 int i, n, ret, clientnum, responselength, best, clientcount;
994 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
998 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1000 // received a command string - strip off the packaging and put it
1001 // into our string buffer with NULL termination
1004 length = min(length, (int)sizeof(stringbuf) - 1);
1005 memcpy(stringbuf, data, length);
1006 stringbuf[length] = 0;
1009 if (developer.integer)
1011 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1012 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1013 Com_HexDumpToConsole(data, length);
1016 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1018 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1020 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1022 if (besttime > challenge[i].time)
1023 besttime = challenge[best = i].time;
1025 // if we did not find an exact match, choose the oldest and
1026 // update address and string
1027 if (i == MAX_CHALLENGES)
1030 challenge[i].address = *peeraddress;
1031 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1033 challenge[i].time = realtime;
1034 // send the challenge
1035 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1038 if (length > 8 && !memcmp(string, "connect\\", 8))
1042 if ((s = SearchInfostring(string, "challenge")))
1044 // validate the challenge
1045 for (i = 0;i < MAX_CHALLENGES;i++)
1046 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1048 if (i < MAX_CHALLENGES)
1050 // check engine protocol
1051 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1053 if (developer.integer)
1054 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1055 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1059 // see if this is a duplicate connection request
1060 for (clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1061 if ((client = svs.connectedclients[clientnum]) && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1063 if (clientnum < MAX_SCOREBOARD)
1065 // duplicate connection request
1066 if (realtime - client->netconnection->connecttime < 2.0)
1068 // client is still trying to connect,
1069 // so we send a duplicate reply
1070 if (developer.integer)
1071 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1072 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1074 // only kick if old connection seems dead
1075 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1077 // kick off connection and await retry
1078 client->deadsocket = true;
1083 // this is a new client, find a slot
1084 for (clientcount = 0, clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1085 if (svs.connectedclients[clientnum])
1087 for (clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1088 if (!svs.connectedclients[clientnum])
1090 if (clientcount < max(1, sv_maxplayers.integer) && clientnum < MAX_SCOREBOARD)
1092 // allocate and prepare the client struct
1093 if ((client = Mem_Alloc(sv_clients_mempool, sizeof(client_t))))
1095 if ((client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_clients_mempool)))
1097 if ((conn = NetConn_Open(mysocket, peeraddress)))
1099 // allocated connection
1100 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1101 if (developer.integer)
1102 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1103 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1104 // now set up the client struct
1105 svs.connectedclients[clientnum] = client;
1106 SV_ConnectClient(clientnum, conn);
1107 NetConn_Heartbeat(1);
1111 EntityFrame4_FreeDatabase(client->entitydatabase4);
1122 if (developer.integer)
1123 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1124 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1132 if (length >= 7 && !memcmp(string, "getinfo", 7))
1134 const char *challenge = NULL;
1135 // If there was a challenge in the getinfo message
1136 if (length > 8 && string[7] == ' ')
1137 challenge = string + 8;
1138 for (i = 0, n = 0;i < MAX_SCOREBOARD;i++)
1139 if (svs.connectedclients[i])
1141 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1142 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1143 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1144 gamename, com_modname, min(sv_maxplayers.integer, MAX_SCOREBOARD), n,
1145 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1146 // does it fit in the buffer?
1147 if (responselength < (int)sizeof(response))
1149 if (developer.integer)
1150 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1151 NetConn_WriteString(mysocket, response, peeraddress);
1156 if (!strncmp(string, "ping", 4))
1158 if (developer.integer)
1159 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1160 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1163 if (!strncmp(string, "ack", 3))
1166 // we may not have liked the packet, but it was a command packet, so
1167 // we're done processing this packet now
1170 // LordHavoc: disabled netquake control packet support in server
1174 // netquake control packets, supported for compatibility only
1175 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1180 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1184 //if (developer.integer)
1185 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1186 if (length >= (int)strlen("QUAKE") + 1 + 1)
1188 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1190 if (developer.integer)
1191 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1192 SZ_Clear(&net_message);
1193 // save space for the header, filled in later
1194 MSG_WriteLong(&net_message, 0);
1195 MSG_WriteByte(&net_message, CCREP_REJECT);
1196 MSG_WriteString(&net_message, "Incompatible version.\n");
1197 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1198 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1199 SZ_Clear(&net_message);
1203 // see if this is a duplicate connection request
1204 for (clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1205 if ((client = svs.connectedclients[clientnum]) && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1207 if (clientnum < MAX_SCOREBOARD)
1209 // duplicate connection request
1210 if (realtime - client->netconnection->connecttime < 2.0)
1212 // client is still trying to connect,
1213 // so we send a duplicate reply
1214 if (developer.integer)
1215 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1216 SZ_Clear(&net_message);
1217 // save space for the header, filled in later
1218 MSG_WriteLong(&net_message, 0);
1219 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1220 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1221 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1222 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1223 SZ_Clear(&net_message);
1225 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1227 // the old client hasn't sent us anything
1228 // in quite a while, so kick off and let
1229 // the retry take care of it...
1230 client->deadsocket = true;
1235 // this is a new client, find a slot
1236 for (clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1237 if (!(client = svs.connectedclients[clientnum]))
1239 // WARNING: this is broken code
1240 if (clientnum < MAX_SCOREBOARD && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1242 // connect to the client
1243 // everything is allocated, just fill in the details
1244 strcpy(conn->address, addressstring2);
1245 if (developer.integer)
1246 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1247 // send back the info about the server connection
1248 SZ_Clear(&net_message);
1249 // save space for the header, filled in later
1250 MSG_WriteLong(&net_message, 0);
1251 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1252 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1253 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1254 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1255 SZ_Clear(&net_message);
1256 // now set up the client struct
1257 SV_ConnectClient(clientnum, conn);
1258 NetConn_Heartbeat(1);
1262 //if (developer.integer)
1263 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1264 // no room; try to let player know
1265 SZ_Clear(&net_message);
1266 // save space for the header, filled in later
1267 MSG_WriteLong(&net_message, 0);
1268 MSG_WriteByte(&net_message, CCREP_REJECT);
1269 MSG_WriteString(&net_message, "Server is full.\n");
1270 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1271 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1272 SZ_Clear(&net_message);
1279 case CCREQ_SERVER_INFO:
1280 if (developer.integer)
1281 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1282 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1284 if (developer.integer)
1285 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1286 SZ_Clear(&net_message);
1287 // save space for the header, filled in later
1288 MSG_WriteLong(&net_message, 0);
1289 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1290 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1291 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1292 MSG_WriteString(&net_message, hostname.string);
1293 MSG_WriteString(&net_message, sv.name);
1294 MSG_WriteByte(&net_message, net_activeconnections);
1295 MSG_WriteByte(&net_message, min(sv_maxplayers.integer, MAX_SCOREBOARD));
1296 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1297 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1298 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1299 SZ_Clear(&net_message);
1302 case CCREQ_PLAYER_INFO:
1303 if (developer.integer)
1304 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1307 int playerNumber, activeNumber, clientNumber;
1310 playerNumber = MSG_ReadByte();
1312 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1313 if (client->active && ++activeNumber == playerNumber)
1315 if (clientNumber != svs.maxclients)
1317 SZ_Clear(&net_message);
1318 // save space for the header, filled in later
1319 MSG_WriteLong(&net_message, 0);
1320 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1321 MSG_WriteByte(&net_message, playerNumber);
1322 MSG_WriteString(&net_message, client->name);
1323 MSG_WriteLong(&net_message, client->colors);
1324 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1325 MSG_WriteLong(&net_message, (int)(realtime - client->netconnection->connecttime));
1326 MSG_WriteString(&net_message, client->netconnection->address);
1327 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1328 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1329 SZ_Clear(&net_message);
1333 case CCREQ_RULE_INFO:
1334 if (developer.integer)
1335 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1341 // find the search start location
1342 prevCvarName = MSG_ReadString();
1343 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1345 // send the response
1346 SZ_Clear(&net_message);
1347 // save space for the header, filled in later
1348 MSG_WriteLong(&net_message, 0);
1349 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1352 MSG_WriteString(&net_message, var->name);
1353 MSG_WriteString(&net_message, var->string);
1355 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1356 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1357 SZ_Clear(&net_message);
1364 // we may not have liked the packet, but it was a valid control
1365 // packet, so we're done processing this packet now
1370 for (i = 0;i < MAX_SCOREBOARD;i++)
1372 if ((host_client = svs.connectedclients[i]))
1374 if (host_client->netconnection)
1376 if (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();
1386 Con_Printf("Removing client with no netconnection!\n");
1387 SV_DropClient(true);
1395 void NetConn_ServerFrame(void)
1398 lhnetaddress_t peeraddress;
1400 NetConn_UpdateServerStuff();
1401 for (i = 0;i < sv_numsockets;i++)
1402 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1403 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1404 for (i = 0;i < MAX_SCOREBOARD;i++)
1406 if ((host_client = svs.connectedclients[i]) && realtime > host_client->netconnection->timeout)
1408 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1409 sv_player = host_client->edict;
1410 SV_DropClient(false);
1413 for (conn = netconn_list;conn;conn = conn->next)
1414 NetConn_ReSendMessage(conn);
1417 void NetConn_QueryMasters(void)
1421 lhnetaddress_t masteraddress;
1424 if (hostCacheCount >= HOSTCACHESIZE)
1427 for (i = 0;i < cl_numsockets;i++)
1434 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1436 SZ_Clear(&net_message);
1437 // save space for the header, filled in later
1438 MSG_WriteLong(&net_message, 0);
1439 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1440 MSG_WriteString(&net_message, "QUAKE");
1441 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1442 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1443 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1444 SZ_Clear(&net_message);
1448 // build the getservers
1449 snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1452 for (masternum = 0;sv_masters[masternum].name;masternum++)
1453 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1454 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1459 void NetConn_Heartbeat(int priority)
1461 lhnetaddress_t masteraddress;
1463 lhnetsocket_t *mysocket;
1465 // if it's a state change (client connected), limit next heartbeat to no
1466 // more than 30 sec in the future
1467 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1468 nextheartbeattime = realtime + 30.0;
1470 // limit heartbeatperiod to 30 to 270 second range,
1471 // lower limit is to avoid abusing master servers with excess traffic,
1472 // upper limit is to avoid timing out on the master server (which uses
1474 if (sv_heartbeatperiod.value < 30)
1475 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1476 if (sv_heartbeatperiod.value > 270)
1477 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1479 // make advertising optional and don't advertise singleplayer games, and
1480 // only send a heartbeat as often as the admin wants
1481 if (sv.active && sv_public.integer && (!cl.islocalgame || sv_maxplayers.integer >= 2) && (priority > 1 || realtime > nextheartbeattime))
1483 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1484 for (masternum = 0;sv_masters[masternum].name;masternum++)
1485 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1486 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1490 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1493 qbyte sent[MAX_SCOREBOARD];
1495 memset(sent, 0, sizeof(sent));
1497 // simultaneously wait for the first CanSendMessage and send the message,
1498 // then wait for a second CanSendMessage (verifying it was received), or
1499 // the client drops and is no longer counted
1500 // the loop aborts when either it runs out of clients to send to, or a
1502 blocktime += Sys_DoubleTime();
1506 NetConn_ClientFrame();
1507 NetConn_ServerFrame();
1508 for (i = 0;i < MAX_SCOREBOARD;i++)
1510 if ((host_client = svs.connectedclients[i]))
1512 if (NetConn_CanSendMessage(host_client->netconnection))
1515 NetConn_SendReliableMessage(host_client->netconnection, data);
1518 if (!NetConn_CanSendMessage(host_client->netconnection))
1523 while (count && Sys_DoubleTime() < blocktime);
1527 static void Net_Heartbeat_f(void)
1529 NetConn_Heartbeat(2);
1532 void PrintStats(netconn_t *conn)
1534 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1537 void Net_Stats_f(void)
1540 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1541 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1542 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1543 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1544 Con_Printf("packetsSent = %i\n", packetsSent);
1545 Con_Printf("packetsReSent = %i\n", packetsReSent);
1546 Con_Printf("packetsReceived = %i\n", packetsReceived);
1547 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1548 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1549 Con_Printf("connections =\n");
1550 for (conn = netconn_list;conn;conn = conn->next)
1554 void Net_Slist_f(void)
1557 memset(&pingcache, 0, sizeof(pingcache));
1558 if (m_state != m_slist)
1559 Con_Printf("Sending requests to master servers\n");
1560 NetConn_QueryMasters();
1561 if (m_state != m_slist)
1562 Con_Printf("Listening for replies...\n");
1565 void NetConn_Init(void)
1568 lhnetaddress_t tempaddress;
1569 netconn_mempool = Mem_AllocPool("Networking");
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_fakelocalping_min);
1577 Cvar_RegisterVariable(&cl_fakelocalping_max);
1578 Cvar_RegisterVariable(&cl_fakepacketloss_receive);
1579 Cvar_RegisterVariable(&cl_fakepacketloss_send);
1580 Cvar_RegisterVariable(&sv_fakepacketloss_receive);
1581 Cvar_RegisterVariable(&sv_fakepacketloss_send);
1582 Cvar_RegisterVariable(&hostname);
1583 Cvar_RegisterVariable(&developer_networking);
1584 Cvar_RegisterVariable(&cl_netport);
1585 Cvar_RegisterVariable(&cl_netaddress);
1586 Cvar_RegisterVariable(&cl_netaddress_ipv6);
1587 Cvar_RegisterVariable(&sv_netport);
1588 Cvar_RegisterVariable(&sv_netaddress);
1589 Cvar_RegisterVariable(&sv_netaddress_ipv6);
1590 Cvar_RegisterVariable(&sv_public);
1591 Cvar_RegisterVariable(&sv_heartbeatperiod);
1592 for (i = 0;sv_masters[i].name;i++)
1593 Cvar_RegisterVariable(&sv_masters[i]);
1594 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1596 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1598 Con_Printf("-ip option used, setting cl_netaddress and sv_netaddress to address \"%s\"\n");
1599 Cvar_SetQuick(&cl_netaddress, com_argv[i + 1]);
1600 Cvar_SetQuick(&sv_netaddress, com_argv[i + 1]);
1603 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1605 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1607 i = atoi(com_argv[i + 1]);
1608 if (i >= 0 && i < 65536)
1610 Con_Printf("-port option used, setting port cvar to %i\n", i);
1611 Cvar_SetValueQuick(&sv_netport, i);
1614 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1618 memset(&pingcache, 0, sizeof(pingcache));
1619 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1623 void NetConn_Shutdown(void)
1625 NetConn_CloseClientPorts();
1626 NetConn_CloseServerPorts();