2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 See the GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 #define MASTER_PORT 27950
28 cvar_t sv_public = {0, "sv_public", "0"};
29 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "180"};
31 static cvar_t sv_masters [] =
33 {CVAR_SAVE, "sv_master1", ""},
34 {CVAR_SAVE, "sv_master2", ""},
35 {CVAR_SAVE, "sv_master3", ""},
36 {CVAR_SAVE, "sv_master4", ""},
37 {0, "sv_masterextra1", "69.59.212.88"},
41 static double nextheartbeattime = 0;
43 sizebuf_t net_message;
45 cvar_t net_messagetimeout = {0, "net_messagetimeout","300"};
46 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10"};
47 cvar_t net_connecttimeout = {0, "net_connecttimeout","10"};
48 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED"};
49 cvar_t developer_networking = {0, "developer_networking", "0"};
51 cvar_t cl_fakelocalping_min = {0, "cl_fakelocalping_min","0"};
52 cvar_t cl_fakelocalping_max = {0, "cl_fakelocalping_max","0"};
53 static cvar_t cl_fakepacketloss_receive = {0, "cl_fakepacketloss_receive","0"};
54 static cvar_t cl_fakepacketloss_send = {0, "cl_fakepacketloss_send","0"};
55 static cvar_t sv_fakepacketloss_receive = {0, "sv_fakepacketloss_receive","0"};
56 static cvar_t sv_fakepacketloss_send = {0, "sv_fakepacketloss_send","0"};
59 /* statistic counters */
60 static int packetsSent = 0;
61 static int packetsReSent = 0;
62 static int packetsReceived = 0;
63 static int receivedDuplicateCount = 0;
64 static int droppedDatagrams = 0;
66 static int unreliableMessagesSent = 0;
67 static int unreliableMessagesReceived = 0;
68 static int reliableMessagesSent = 0;
69 static int reliableMessagesReceived = 0;
71 double masterquerytime = -1000;
72 int masterquerycount = 0;
73 int masterreplycount = 0;
74 int serverquerycount = 0;
75 int serverreplycount = 0;
77 int hostCacheCount = 0;
78 hostcache_t hostcache[HOSTCACHESIZE];
80 static qbyte sendbuffer[NET_MAXMESSAGE];
81 static qbyte readbuffer[NET_MAXMESSAGE];
84 lhnetsocket_t *cl_sockets[16];
86 lhnetsocket_t *sv_sockets[16];
88 netconn_t *netconn_list = NULL;
89 mempool_t *netconn_mempool = NULL;
91 cvar_t cl_netport = {0, "cl_port", "0"};
92 cvar_t cl_netaddress = {0, "cl_netaddress", "0.0.0.0"};
93 cvar_t cl_netaddress_ipv6 = {0, "cl_netaddress_ipv6", "[0:0:0:0:0:0:0:0]:0"};
95 cvar_t sv_netport = {0, "port", "26000"};
96 cvar_t sv_netaddress = {0, "sv_netaddress", "0.0.0.0"};
97 cvar_t sv_netaddress_ipv6 = {0, "sv_netaddress_ipv6", "[0:0:0:0:0:0:0:0]:26000"};
99 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
101 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
103 if (cl_fakepacketloss_receive.integer)
104 for (i = 0;i < cl_numsockets;i++)
105 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_fakepacketloss_receive.integer)
107 if (sv_fakepacketloss_receive.integer)
108 for (i = 0;i < cl_numsockets;i++)
109 if (sv_sockets[i] == mysocket && (rand() % 100) < sv_fakepacketloss_receive.integer)
111 if (developer_networking.integer && length != 0)
113 char addressstring[128], addressstring2[128];
114 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
117 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
118 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
119 Com_HexDumpToConsole(data, length);
122 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
127 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
131 if (cl_fakepacketloss_send.integer)
132 for (i = 0;i < cl_numsockets;i++)
133 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_fakepacketloss_send.integer)
135 if (sv_fakepacketloss_send.integer)
136 for (i = 0;i < cl_numsockets;i++)
137 if (sv_sockets[i] == mysocket && (rand() % 100) < sv_fakepacketloss_send.integer)
139 ret = LHNET_Write(mysocket, data, length, peeraddress);
140 if (developer_networking.integer)
142 char addressstring[128], addressstring2[128];
143 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
144 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
145 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
146 Com_HexDumpToConsole(data, length);
151 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
153 // note this does not include the trailing NULL because we add that in the parser
154 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
157 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
159 unsigned int packetLen;
160 unsigned int dataLen;
162 unsigned int *header;
165 if (data->cursize == 0)
166 Sys_Error("Datagram_SendMessage: zero length message\n");
168 if (data->cursize > NET_MAXMESSAGE)
169 Sys_Error("Datagram_SendMessage: message too big %u\n", data->cursize);
171 if (conn->canSend == false)
172 Sys_Error("SendMessage: called with canSend == false\n");
175 memcpy(conn->sendMessage, data->data, data->cursize);
176 conn->sendMessageLength = data->cursize;
178 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
180 dataLen = conn->sendMessageLength;
185 dataLen = MAX_PACKETFRAGMENT;
189 packetLen = NET_HEADERSIZE + dataLen;
191 header = (void *)sendbuffer;
192 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
193 header[1] = BigLong(conn->sendSequence);
194 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
196 conn->sendSequence++;
197 conn->canSend = false;
199 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
202 conn->lastSendTime = realtime;
204 reliableMessagesSent++;
208 static void NetConn_SendMessageNext(netconn_t *conn)
210 unsigned int packetLen;
211 unsigned int dataLen;
213 unsigned int *header;
215 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
217 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
219 dataLen = conn->sendMessageLength;
224 dataLen = MAX_PACKETFRAGMENT;
228 packetLen = NET_HEADERSIZE + dataLen;
230 header = (void *)sendbuffer;
231 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
232 header[1] = BigLong(conn->sendSequence);
233 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
235 conn->sendSequence++;
236 conn->sendNext = false;
238 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
241 conn->lastSendTime = realtime;
246 static void NetConn_ReSendMessage(netconn_t *conn)
248 unsigned int packetLen;
249 unsigned int dataLen;
251 unsigned int *header;
253 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
255 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
257 dataLen = conn->sendMessageLength;
262 dataLen = MAX_PACKETFRAGMENT;
266 packetLen = NET_HEADERSIZE + dataLen;
268 header = (void *)sendbuffer;
269 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
270 header[1] = BigLong(conn->sendSequence - 1);
271 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
273 conn->sendNext = false;
275 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
278 conn->lastSendTime = realtime;
283 qboolean NetConn_CanSendMessage(netconn_t *conn)
285 return conn->canSend;
288 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
294 if (data->cursize == 0)
295 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
297 if (data->cursize > MAX_DATAGRAM)
298 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
301 packetLen = NET_HEADERSIZE + data->cursize;
303 header = (void *)sendbuffer;
304 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
305 header[1] = BigLong(conn->unreliableSendSequence);
306 memcpy(sendbuffer + 8, data->data, data->cursize);
308 conn->unreliableSendSequence++;
310 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
314 unreliableMessagesSent++;
318 void NetConn_CloseClientPorts(void)
320 for (;cl_numsockets > 0;cl_numsockets--)
321 if (cl_sockets[cl_numsockets - 1])
322 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
325 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
327 lhnetaddress_t address;
329 char addressstring2[1024];
330 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
332 if ((s = LHNET_OpenSocket_Connectionless(&address)))
334 cl_sockets[cl_numsockets++] = s;
335 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
336 Con_Printf("Client opened a socket on address %s\n", addressstring2);
340 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
341 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
345 Con_Printf("Client unable to parse address %s\n", addressstring);
348 void NetConn_OpenClientPorts(void)
351 NetConn_CloseClientPorts();
352 port = bound(0, cl_netport.integer, 65535);
353 if (cl_netport.integer != port)
354 Cvar_SetValueQuick(&cl_netport, port);
355 Con_Printf("Client using port %i\n", port);
356 NetConn_OpenClientPort("local", port);
357 NetConn_OpenClientPort(cl_netaddress.string, port);
358 NetConn_OpenClientPort(cl_netaddress_ipv6.string, port);
361 void NetConn_CloseServerPorts(void)
363 for (;sv_numsockets > 0;sv_numsockets--)
364 if (sv_sockets[sv_numsockets - 1])
365 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
368 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
370 lhnetaddress_t address;
372 char addressstring2[1024];
373 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
375 if ((s = LHNET_OpenSocket_Connectionless(&address)))
377 sv_sockets[sv_numsockets++] = s;
378 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
379 Con_Printf("Server listening on address %s\n", addressstring2);
383 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
384 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
388 Con_Printf("Server unable to parse address %s\n", addressstring);
391 void NetConn_OpenServerPorts(int opennetports)
394 NetConn_CloseServerPorts();
395 port = bound(0, sv_netport.integer, 65535);
398 Con_Printf("Server using port %i\n", port);
399 if (sv_netport.integer != port)
400 Cvar_SetValueQuick(&sv_netport, port);
401 if (cls.state != ca_dedicated)
402 NetConn_OpenServerPort("local", port);
405 NetConn_OpenServerPort(sv_netaddress.string, port);
406 NetConn_OpenServerPort(sv_netaddress_ipv6.string, port);
408 if (sv_numsockets == 0)
409 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
412 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
414 int i, a = LHNETADDRESS_GetAddressType(address);
415 for (i = 0;i < cl_numsockets;i++)
416 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
417 return cl_sockets[i];
421 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
423 int i, a = LHNETADDRESS_GetAddressType(address);
424 for (i = 0;i < sv_numsockets;i++)
425 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
426 return sv_sockets[i];
430 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
433 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
434 conn->mysocket = mysocket;
435 conn->peeraddress = *peeraddress;
436 conn->canSend = true;
437 conn->connecttime = realtime;
438 conn->lastMessageTime = realtime;
439 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
440 // reduce effectiveness of connection request floods
441 conn->timeout = realtime + net_connecttimeout.value;
442 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
443 conn->next = netconn_list;
448 void NetConn_Close(netconn_t *conn)
451 // remove connection from list
452 if (conn == netconn_list)
453 netconn_list = conn->next;
456 for (c = netconn_list;c;c = c->next)
460 c->next = conn->next;
464 // not found in list, we'll avoid crashing here...
472 static int clientport = -1;
473 static int clientport2 = -1;
474 static int hostport = -1;
475 static void NetConn_UpdateServerStuff(void)
477 if (cls.state != ca_dedicated)
479 if (clientport2 != cl_netport.integer)
481 clientport2 = cl_netport.integer;
482 if (cls.state == ca_connected)
483 Con_Printf("Changing \"cl_port\" will not take effect until you reconnect.\n");
485 if (cls.state == ca_disconnected && clientport != clientport2)
487 clientport = clientport2;
488 NetConn_CloseClientPorts();
490 if (cl_numsockets == 0)
491 NetConn_OpenClientPorts();
494 if (hostport != sv_netport.integer)
496 hostport = sv_netport.integer;
498 Con_Printf("Changing \"port\" will not take effect until \"map\" command is executed.\n");
502 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
506 unsigned int sequence;
510 length = BigLong(((int *)data)[0]);
511 flags = length & ~NETFLAG_LENGTH_MASK;
512 length &= NETFLAG_LENGTH_MASK;
513 // control packets were already handled
514 if (!(flags & NETFLAG_CTL))
516 sequence = BigLong(((int *)data)[1]);
520 if (flags & NETFLAG_UNRELIABLE)
522 if (sequence >= conn->unreliableReceiveSequence)
524 if (sequence > conn->unreliableReceiveSequence)
526 count = sequence - conn->unreliableReceiveSequence;
527 droppedDatagrams += count;
528 Con_DPrintf("Dropped %u datagram(s)\n", count);
530 conn->unreliableReceiveSequence = sequence + 1;
531 conn->lastMessageTime = realtime;
532 conn->timeout = realtime + net_messagetimeout.value;
533 unreliableMessagesReceived++;
536 SZ_Clear(&net_message);
537 SZ_Write(&net_message, data, length);
543 Con_DPrintf("Got a stale datagram\n");
546 else if (flags & NETFLAG_ACK)
548 if (sequence == (conn->sendSequence - 1))
550 if (sequence == conn->ackSequence)
553 if (conn->ackSequence != conn->sendSequence)
554 Con_DPrintf("ack sequencing error\n");
555 conn->lastMessageTime = realtime;
556 conn->timeout = realtime + net_messagetimeout.value;
557 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
558 if (conn->sendMessageLength > 0)
560 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
561 conn->sendNext = true;
562 NetConn_SendMessageNext(conn);
566 conn->sendMessageLength = 0;
567 conn->canSend = true;
571 Con_DPrintf("Duplicate ACK received\n");
574 Con_DPrintf("Stale ACK received\n");
577 else if (flags & NETFLAG_DATA)
579 unsigned int temppacket[2];
580 temppacket[0] = BigLong(8 | NETFLAG_ACK);
581 temppacket[1] = BigLong(sequence);
582 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
583 if (sequence == conn->receiveSequence)
585 conn->lastMessageTime = realtime;
586 conn->timeout = realtime + net_messagetimeout.value;
587 conn->receiveSequence++;
588 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
589 conn->receiveMessageLength += length;
590 if (flags & NETFLAG_EOM)
592 reliableMessagesReceived++;
593 length = conn->receiveMessageLength;
594 conn->receiveMessageLength = 0;
597 SZ_Clear(&net_message);
598 SZ_Write(&net_message, conn->receiveMessage, length);
605 receivedDuplicateCount++;
613 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
615 cls.netcon = NetConn_Open(mysocket, peeraddress);
616 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
619 cls.connect_trying = false;
620 cls.demonum = -1; // not in the demo loop now
621 cls.state = ca_connected;
622 cls.signon = 0; // need all the signon messages before playing
627 int NetConn_IsLocalGame(void)
629 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
637 lhnetaddress_t peeraddress;
639 pingcache[HOSTCACHESIZE];
641 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
644 lhnetaddress_t svaddress;
646 char *string, addressstring2[128], cname[128], ipstring[32];
647 char stringbuf[16384];
649 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
651 // received a command string - strip off the packaging and put it
652 // into our string buffer with NULL termination
655 length = min(length, (int)sizeof(stringbuf) - 1);
656 memcpy(stringbuf, data, length);
657 stringbuf[length] = 0;
660 if (developer.integer)
662 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
663 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
664 Com_HexDumpToConsole(data, length);
667 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
669 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
670 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
671 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
674 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
676 NetConn_ConnectionEstablished(mysocket, peeraddress);
679 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
681 cls.connect_trying = false;
683 length = max(length - 7, (int)sizeof(m_return_reason) - 1);
684 memcpy(m_return_reason, string, length);
685 m_return_reason[length] = 0;
686 Con_Printf("%s\n", m_return_reason);
689 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
691 int i, j, c, n, users, maxusers;
692 char game[32], mod[32], map[32], name[128];
696 // hostcache only uses text addresses
697 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
698 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(game, s, sizeof (game));else game[0] = 0;
699 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(mod , s, sizeof (mod ));else mod[0] = 0;
700 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(map , s, sizeof (map ));else map[0] = 0;
701 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(name, s, sizeof (name));else name[0] = 0;
702 if ((s = SearchInfostring(string, "protocol" )) != NULL) c = atoi(s);else c = -1;
703 if ((s = SearchInfostring(string, "clients" )) != NULL) users = atoi(s);else users = 0;
704 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) maxusers = atoi(s);else maxusers = 0;
705 // search the cache for this server and update it
706 for (n = 0; n < hostCacheCount; n++)
708 if (!strcmp(cname, hostcache[n].cname))
710 if (hostcache[n].ping == 100000)
712 pingtime = (int)((realtime - hostcache[n].querytime) * 1000.0);
713 pingtime = bound(0, pingtime, 9999);
715 hostcache[n].ping = pingtime;
716 // build description strings for the things users care about
717 snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, c != NET_PROTOCOL_VERSION ? '*' : ' ', users, maxusers, name);
718 snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", cname, game, mod, map);
719 // if ping is especially high, display it as such
722 // orange numbers (lower block)
723 for (i = 0;i < 5;i++)
724 if (hostcache[n].line1[i] != ' ')
725 hostcache[n].line1[i] += 128;
727 else if (pingtime >= 200)
729 // yellow numbers (in upper block)
730 for (i = 0;i < 5;i++)
731 if (hostcache[n].line1[i] != ' ')
732 hostcache[n].line1[i] -= 30;
734 // if not in the slist menu we should print the server to console
735 if (m_state != m_slist)
736 Con_Printf("%s\n%s\n", hostcache[n].line1, hostcache[n].line2);
737 // and finally, re-sort the list
738 for (i = 0;i < hostCacheCount;i++)
740 for (j = i + 1;j < hostCacheCount;j++)
742 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
743 if (hostcache[i].ping > hostcache[j].ping)
745 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
746 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
747 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
756 if (!strncmp(string, "getserversResponse\\", 19) && hostCacheCount < HOSTCACHESIZE)
760 // Extract the IP addresses
764 if (m_state != m_slist)
765 Con_Printf("received server list...\n");
766 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
768 snprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
769 if (developer.integer)
770 Con_Printf("Requesting info from server %s\n", ipstring);
771 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
772 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
775 // add to slist (hostCache)
776 // search the cache for this server
777 for (n = 0; n < hostCacheCount; n++)
778 if (!strcmp(ipstring, hostcache[n].cname))
780 // add it or update it
781 if (n == hostCacheCount)
783 // if cache is full replace highest ping server (the list is
784 // kept sorted so this is always the last, and if this server
785 // is good it will be sorted into an early part of the list)
786 if (hostCacheCount >= HOSTCACHESIZE)
787 n = hostCacheCount - 1;
794 memset(&hostcache[n], 0, sizeof(hostcache[n]));
795 // store the data the engine cares about (address and ping)
796 strlcpy (hostcache[n].cname, ipstring, sizeof (hostcache[n].cname));
797 hostcache[n].ping = 100000;
798 hostcache[n].querytime = realtime;
799 // build description strings for the things users care about
800 snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "?");
801 snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%s", ipstring);
802 // if not in the slist menu we should print the server to console
803 if (m_state != m_slist)
804 Con_Printf("querying %s\n", ipstring);
805 // and finally, re-sort the list
806 for (i = 0;i < hostCacheCount;i++)
808 for (j = i + 1;j < hostCacheCount;j++)
810 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
811 if (hostcache[i].ping > hostcache[j].ping)
813 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
814 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
815 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
821 // move on to next address in packet
828 if (!strncmp(string, "ping", 4))
830 if (developer.integer)
831 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
832 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
835 if (!strncmp(string, "ack", 3))
838 // we may not have liked the packet, but it was a command packet, so
839 // we're done processing this packet now
842 // netquake control packets, supported for compatibility only
843 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
848 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
852 if (developer.integer)
853 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
854 if (cls.connect_trying)
856 lhnetaddress_t clientportaddress;
857 clientportaddress = *peeraddress;
860 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
863 LHNETADDRESS_SetPort(&clientportaddress, port);
865 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
869 if (developer.integer)
870 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
871 Con_Printf("%s\n", data);
872 strlcpy (m_return_reason, data, sizeof (m_return_reason));
875 case CCREP_SERVER_INFO:
876 if (developer.integer)
877 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
878 if (cls.state != ca_dedicated)
880 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
881 // string we just ignore it and keep the real address
883 // hostcache only uses text addresses
884 cname = UDP_AddrToString(readaddr);
885 // search the cache for this server
886 for (n = 0; n < hostCacheCount; n++)
887 if (!strcmp(cname, hostcache[n].cname))
890 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
893 memset(&hostcache[n], 0, sizeof(hostcache[n]));
894 strlcpy (hostcache[n].name, MSG_ReadString(), sizeof (hostcache[n].name));
895 strlcpy (hostcache[n].map, MSG_ReadString(), sizeof (hostcache[n].map));
896 hostcache[n].users = MSG_ReadByte();
897 hostcache[n].maxusers = MSG_ReadByte();
899 if (c != NET_PROTOCOL_VERSION)
901 strlcpy (hostcache[n].cname, hostcache[n].name, sizeof (hostcache[n].cname));
902 strcpy(hostcache[n].name, "*");
903 strlcat (hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name));
905 strlcpy (hostcache[n].cname, cname, sizeof (hostcache[n].cname));
909 case CCREP_PLAYER_INFO:
910 // we got a CCREP_PLAYER_INFO??
911 //if (developer.integer)
912 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
914 case CCREP_RULE_INFO:
915 // we got a CCREP_RULE_INFO??
916 //if (developer.integer)
917 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
923 // we may not have liked the packet, but it was a valid control
924 // packet, so we're done processing this packet now
928 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)
929 CL_ParseServerMessage();
933 void NetConn_ClientFrame(void)
936 lhnetaddress_t peeraddress;
938 NetConn_UpdateServerStuff();
939 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
941 if (cls.connect_remainingtries == 0)
943 cls.connect_trying = false;
944 if (m_state == m_slist)
945 strcpy (m_return_reason, "Connect: Failed");
947 Con_Printf("Connect failed\n");
950 if (cls.connect_nextsendtime)
952 if (m_state == m_slist)
953 strcpy (m_return_reason, "Connect: Still trying");
955 Con_Printf("Still trying...\n");
959 if (m_state == m_slist)
960 strcpy (m_return_reason, "Connect: Trying");
962 Con_Printf("Trying...\n");
964 cls.connect_nextsendtime = realtime + 1;
965 cls.connect_remainingtries--;
966 // try challenge first (newer server)
967 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
968 // then try netquake as a fallback (old server, or netquake)
969 SZ_Clear(&net_message);
970 // save space for the header, filled in later
971 MSG_WriteLong(&net_message, 0);
972 MSG_WriteByte(&net_message, CCREQ_CONNECT);
973 MSG_WriteString(&net_message, "QUAKE");
974 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
975 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
976 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
977 SZ_Clear(&net_message);
979 for (i = 0;i < cl_numsockets;i++)
980 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
981 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
982 if (cls.netcon && realtime > cls.netcon->timeout)
984 Con_Printf("Connection timed out\n");
987 for (conn = netconn_list;conn;conn = conn->next)
988 NetConn_ReSendMessage(conn);
991 #define MAX_CHALLENGES 128
994 lhnetaddress_t address;
998 challenge[MAX_CHALLENGES];
1000 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1004 for (i = 0;i < bufferlength - 1;i++)
1008 c = rand () % (127 - 33) + 33;
1009 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1015 extern void SV_ConnectClient(int clientnum, netconn_t *netconnection);
1016 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1018 int i, n, ret, clientnum, responselength, best;
1022 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1026 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1028 // received a command string - strip off the packaging and put it
1029 // into our string buffer with NULL termination
1032 length = min(length, (int)sizeof(stringbuf) - 1);
1033 memcpy(stringbuf, data, length);
1034 stringbuf[length] = 0;
1037 if (developer.integer)
1039 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1040 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1041 Com_HexDumpToConsole(data, length);
1044 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1046 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1048 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1050 if (besttime > challenge[i].time)
1051 besttime = challenge[best = i].time;
1053 // if we did not find an exact match, choose the oldest and
1054 // update address and string
1055 if (i == MAX_CHALLENGES)
1058 challenge[i].address = *peeraddress;
1059 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1061 challenge[i].time = realtime;
1062 // send the challenge
1063 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1066 if (length > 8 && !memcmp(string, "connect\\", 8))
1070 if ((s = SearchInfostring(string, "challenge")))
1072 // validate the challenge
1073 for (i = 0;i < MAX_CHALLENGES;i++)
1074 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1076 if (i < MAX_CHALLENGES)
1078 // check engine protocol
1079 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1081 if (developer.integer)
1082 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1083 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1087 // see if this is a duplicate connection request
1088 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1089 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1091 if (clientnum < svs.maxclients)
1093 // duplicate connection request
1094 if (realtime - client->netconnection->connecttime < 2.0)
1096 // client is still trying to connect,
1097 // so we send a duplicate reply
1098 if (developer.integer)
1099 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1100 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1102 // only kick if old connection seems dead
1103 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1105 // kick off connection and await retry
1106 client->deadsocket = true;
1111 // this is a new client, find a slot
1112 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1113 if (!client->active)
1115 if (clientnum < svs.maxclients)
1117 // prepare the client struct
1118 if ((client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_clients_mempool)))
1120 if ((conn = NetConn_Open(mysocket, peeraddress)))
1122 // allocated connection
1123 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1124 if (developer.integer)
1125 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1126 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1127 // now set up the client
1128 SV_ConnectClient(clientnum, conn);
1129 NetConn_Heartbeat(1);
1132 EntityFrame4_FreeDatabase(client->entitydatabase4);
1138 if (developer.integer)
1139 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1140 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1148 if (length >= 7 && !memcmp(string, "getinfo", 7))
1150 const char *challenge = NULL;
1151 // If there was a challenge in the getinfo message
1152 if (length > 8 && string[7] == ' ')
1153 challenge = string + 8;
1154 for (i = 0, n = 0;i < svs.maxclients;i++)
1155 if (svs.clients[i].active)
1157 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1158 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1159 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1160 gamename, com_modname, svs.maxclients, n,
1161 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1162 // does it fit in the buffer?
1163 if (responselength < (int)sizeof(response))
1165 if (developer.integer)
1166 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1167 NetConn_WriteString(mysocket, response, peeraddress);
1172 if (!strncmp(string, "ping", 4))
1174 if (developer.integer)
1175 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1176 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1179 if (!strncmp(string, "ack", 3))
1182 // we may not have liked the packet, but it was a command packet, so
1183 // we're done processing this packet now
1186 // LordHavoc: disabled netquake control packet support in server
1190 // netquake control packets, supported for compatibility only
1191 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1196 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1200 //if (developer.integer)
1201 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1202 if (length >= (int)strlen("QUAKE") + 1 + 1)
1204 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1206 if (developer.integer)
1207 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1208 SZ_Clear(&net_message);
1209 // save space for the header, filled in later
1210 MSG_WriteLong(&net_message, 0);
1211 MSG_WriteByte(&net_message, CCREP_REJECT);
1212 MSG_WriteString(&net_message, "Incompatible version.\n");
1213 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1214 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1215 SZ_Clear(&net_message);
1219 // see if this is a duplicate connection request
1220 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1221 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1223 if (clientnum < svs.maxclients)
1225 // duplicate connection request
1226 if (realtime - client->netconnection->connecttime < 2.0)
1228 // client is still trying to connect,
1229 // so we send a duplicate reply
1230 if (developer.integer)
1231 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1232 SZ_Clear(&net_message);
1233 // save space for the header, filled in later
1234 MSG_WriteLong(&net_message, 0);
1235 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1236 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1237 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1238 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1239 SZ_Clear(&net_message);
1241 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1243 // the old client hasn't sent us anything
1244 // in quite a while, so kick off and let
1245 // the retry take care of it...
1246 client->deadsocket = true;
1251 // this is a new client, find a slot
1252 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1253 if (!client->active)
1255 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1257 // connect to the client
1258 // everything is allocated, just fill in the details
1259 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1260 if (developer.integer)
1261 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1262 // send back the info about the server connection
1263 SZ_Clear(&net_message);
1264 // save space for the header, filled in later
1265 MSG_WriteLong(&net_message, 0);
1266 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1267 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1268 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1269 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1270 SZ_Clear(&net_message);
1271 // now set up the client struct
1272 SV_ConnectClient(clientnum, conn);
1273 NetConn_Heartbeat(1);
1277 //if (developer.integer)
1278 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1279 // no room; try to let player know
1280 SZ_Clear(&net_message);
1281 // save space for the header, filled in later
1282 MSG_WriteLong(&net_message, 0);
1283 MSG_WriteByte(&net_message, CCREP_REJECT);
1284 MSG_WriteString(&net_message, "Server is full.\n");
1285 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1286 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1287 SZ_Clear(&net_message);
1294 case CCREQ_SERVER_INFO:
1295 if (developer.integer)
1296 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1297 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1299 if (developer.integer)
1300 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1301 SZ_Clear(&net_message);
1302 // save space for the header, filled in later
1303 MSG_WriteLong(&net_message, 0);
1304 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1305 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1306 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1307 MSG_WriteString(&net_message, hostname.string);
1308 MSG_WriteString(&net_message, sv.name);
1309 MSG_WriteByte(&net_message, net_activeconnections);
1310 MSG_WriteByte(&net_message, svs.maxclients);
1311 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1312 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1313 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1314 SZ_Clear(&net_message);
1317 case CCREQ_PLAYER_INFO:
1318 if (developer.integer)
1319 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1322 int playerNumber, activeNumber, clientNumber;
1325 playerNumber = MSG_ReadByte();
1327 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1328 if (client->active && ++activeNumber == playerNumber)
1330 if (clientNumber != svs.maxclients)
1332 SZ_Clear(&net_message);
1333 // save space for the header, filled in later
1334 MSG_WriteLong(&net_message, 0);
1335 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1336 MSG_WriteByte(&net_message, playerNumber);
1337 MSG_WriteString(&net_message, client->name);
1338 MSG_WriteLong(&net_message, client->colors);
1339 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1340 MSG_WriteLong(&net_message, (int)(realtime - client->netconnection->connecttime));
1341 MSG_WriteString(&net_message, client->netconnection->address);
1342 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1343 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1344 SZ_Clear(&net_message);
1348 case CCREQ_RULE_INFO:
1349 if (developer.integer)
1350 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1356 // find the search start location
1357 prevCvarName = MSG_ReadString();
1358 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1360 // send the response
1361 SZ_Clear(&net_message);
1362 // save space for the header, filled in later
1363 MSG_WriteLong(&net_message, 0);
1364 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1367 MSG_WriteString(&net_message, var->name);
1368 MSG_WriteString(&net_message, var->string);
1370 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1371 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1372 SZ_Clear(&net_message);
1379 // we may not have liked the packet, but it was a valid control
1380 // packet, so we're done processing this packet now
1385 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1387 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1389 sv_player = host_client->edict;
1390 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1391 SV_ReadClientMessage();
1399 void NetConn_ServerFrame(void)
1402 lhnetaddress_t peeraddress;
1404 NetConn_UpdateServerStuff();
1405 for (i = 0;i < sv_numsockets;i++)
1406 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1407 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1408 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1410 // never timeout loopback connections
1411 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(host_client->netconnection->mysocket)) != LHNETADDRESSTYPE_LOOP)
1413 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1414 sv_player = host_client->edict;
1415 SV_DropClient(false);
1418 for (conn = netconn_list;conn;conn = conn->next)
1419 NetConn_ReSendMessage(conn);
1422 void NetConn_QueryMasters(void)
1426 lhnetaddress_t masteraddress;
1429 if (hostCacheCount >= HOSTCACHESIZE)
1432 for (i = 0;i < cl_numsockets;i++)
1439 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1441 SZ_Clear(&net_message);
1442 // save space for the header, filled in later
1443 MSG_WriteLong(&net_message, 0);
1444 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1445 MSG_WriteString(&net_message, "QUAKE");
1446 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1447 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1448 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1449 SZ_Clear(&net_message);
1453 // build the getservers
1454 snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1457 for (masternum = 0;sv_masters[masternum].name;masternum++)
1459 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1462 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1467 if (!masterquerycount)
1469 Con_Printf("Unable to query master servers, no suitable network sockets active.\n");
1470 strcpy(m_return_reason, "No network");
1474 void NetConn_Heartbeat(int priority)
1476 lhnetaddress_t masteraddress;
1478 lhnetsocket_t *mysocket;
1480 // if it's a state change (client connected), limit next heartbeat to no
1481 // more than 30 sec in the future
1482 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1483 nextheartbeattime = realtime + 30.0;
1485 // limit heartbeatperiod to 30 to 270 second range,
1486 // lower limit is to avoid abusing master servers with excess traffic,
1487 // upper limit is to avoid timing out on the master server (which uses
1489 if (sv_heartbeatperiod.value < 30)
1490 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1491 if (sv_heartbeatperiod.value > 270)
1492 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1494 // make advertising optional and don't advertise singleplayer games, and
1495 // only send a heartbeat as often as the admin wants
1496 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1498 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1499 for (masternum = 0;sv_masters[masternum].name;masternum++)
1500 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1501 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1505 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1508 qbyte sent[MAX_SCOREBOARD];
1510 memset(sent, 0, sizeof(sent));
1512 // simultaneously wait for the first CanSendMessage and send the message,
1513 // then wait for a second CanSendMessage (verifying it was received), or
1514 // the client drops and is no longer counted
1515 // the loop aborts when either it runs out of clients to send to, or a
1517 blocktime += Sys_DoubleTime();
1521 NetConn_ClientFrame();
1522 NetConn_ServerFrame();
1523 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1525 if (host_client->netconnection)
1527 if (NetConn_CanSendMessage(host_client->netconnection))
1530 NetConn_SendReliableMessage(host_client->netconnection, data);
1533 if (!NetConn_CanSendMessage(host_client->netconnection))
1538 while (count && Sys_DoubleTime() < blocktime);
1542 static void Net_Heartbeat_f(void)
1545 NetConn_Heartbeat(2);
1547 Con_Printf("No server running, can not heartbeat to master server.\n");
1550 void PrintStats(netconn_t *conn)
1552 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1555 void Net_Stats_f(void)
1558 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1559 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1560 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1561 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1562 Con_Printf("packetsSent = %i\n", packetsSent);
1563 Con_Printf("packetsReSent = %i\n", packetsReSent);
1564 Con_Printf("packetsReceived = %i\n", packetsReceived);
1565 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1566 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1567 Con_Printf("connections =\n");
1568 for (conn = netconn_list;conn;conn = conn->next)
1572 void Net_Slist_f(void)
1574 masterquerytime = realtime;
1575 masterquerycount = 0;
1576 masterreplycount = 0;
1577 serverquerycount = 0;
1578 serverreplycount = 0;
1580 memset(&pingcache, 0, sizeof(pingcache));
1581 if (m_state != m_slist)
1582 Con_Printf("Sending requests to master servers\n");
1583 NetConn_QueryMasters();
1584 if (m_state != m_slist)
1585 Con_Printf("Listening for replies...\n");
1588 void NetConn_Init(void)
1591 lhnetaddress_t tempaddress;
1592 netconn_mempool = Mem_AllocPool("Networking");
1593 Cmd_AddCommand("net_stats", Net_Stats_f);
1594 Cmd_AddCommand("net_slist", Net_Slist_f);
1595 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1596 Cvar_RegisterVariable(&net_messagetimeout);
1597 Cvar_RegisterVariable(&net_messagerejointimeout);
1598 Cvar_RegisterVariable(&net_connecttimeout);
1599 Cvar_RegisterVariable(&cl_fakelocalping_min);
1600 Cvar_RegisterVariable(&cl_fakelocalping_max);
1601 Cvar_RegisterVariable(&cl_fakepacketloss_receive);
1602 Cvar_RegisterVariable(&cl_fakepacketloss_send);
1603 Cvar_RegisterVariable(&sv_fakepacketloss_receive);
1604 Cvar_RegisterVariable(&sv_fakepacketloss_send);
1605 Cvar_RegisterVariable(&hostname);
1606 Cvar_RegisterVariable(&developer_networking);
1607 Cvar_RegisterVariable(&cl_netport);
1608 Cvar_RegisterVariable(&cl_netaddress);
1609 Cvar_RegisterVariable(&cl_netaddress_ipv6);
1610 Cvar_RegisterVariable(&sv_netport);
1611 Cvar_RegisterVariable(&sv_netaddress);
1612 Cvar_RegisterVariable(&sv_netaddress_ipv6);
1613 Cvar_RegisterVariable(&sv_public);
1614 Cvar_RegisterVariable(&sv_heartbeatperiod);
1615 for (i = 0;sv_masters[i].name;i++)
1616 Cvar_RegisterVariable(&sv_masters[i]);
1617 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1619 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1621 Con_Printf("-ip option used, setting cl_netaddress and sv_netaddress to address \"%s\"\n");
1622 Cvar_SetQuick(&cl_netaddress, com_argv[i + 1]);
1623 Cvar_SetQuick(&sv_netaddress, com_argv[i + 1]);
1626 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1628 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1630 i = atoi(com_argv[i + 1]);
1631 if (i >= 0 && i < 65536)
1633 Con_Printf("-port option used, setting port cvar to %i\n", i);
1634 Cvar_SetValueQuick(&sv_netport, i);
1637 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1641 memset(&pingcache, 0, sizeof(pingcache));
1642 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1646 void NetConn_Shutdown(void)
1648 NetConn_CloseClientPorts();
1649 NetConn_CloseServerPorts();