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"},
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) strncpy(game, s, sizeof(game) - 1);else game[0] = 0;
699 if ((s = SearchInfostring(string, "modname" )) != NULL) strncpy(mod , s, sizeof(mod ) - 1);else mod[0] = 0;
700 if ((s = SearchInfostring(string, "mapname" )) != NULL) strncpy(map , s, sizeof(map ) - 1);else map[0] = 0;
701 if ((s = SearchInfostring(string, "hostname" )) != NULL) strncpy(name, s, sizeof(name) - 1);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 sprintf(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 strcpy(hostcache[n].cname, ipstring);
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 strncpy(m_return_reason, data, sizeof(m_return_reason) - 1);
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 strcpy(hostcache[n].name, MSG_ReadString());
895 strcpy(hostcache[n].map, MSG_ReadString());
896 hostcache[n].users = MSG_ReadByte();
897 hostcache[n].maxusers = MSG_ReadByte();
899 if (c != NET_PROTOCOL_VERSION)
901 strncpy(hostcache[n].cname, hostcache[n].name, sizeof(hostcache[n].cname) - 1);
902 hostcache[n].cname[sizeof(hostcache[n].cname) - 1] = 0;
903 strcpy(hostcache[n].name, "*");
904 strncat(hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name) - 1);
905 hostcache[n].name[sizeof(hostcache[n].name) - 1] = 0;
907 strcpy(hostcache[n].cname, cname);
911 case CCREP_PLAYER_INFO:
912 // we got a CCREP_PLAYER_INFO??
913 //if (developer.integer)
914 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
916 case CCREP_RULE_INFO:
917 // we got a CCREP_RULE_INFO??
918 //if (developer.integer)
919 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
925 // we may not have liked the packet, but it was a valid control
926 // packet, so we're done processing this packet now
930 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)
931 CL_ParseServerMessage();
935 void NetConn_ClientFrame(void)
938 lhnetaddress_t peeraddress;
940 NetConn_UpdateServerStuff();
941 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
943 if (cls.connect_remainingtries == 0)
945 cls.connect_trying = false;
946 if (m_state == m_slist)
947 strcpy(m_return_reason, "Connect: Failed");
949 Con_Printf("Connect failed\n");
952 if (cls.connect_nextsendtime)
954 if (m_state == m_slist)
955 strcpy(m_return_reason, "Connect: Still trying");
957 Con_Printf("Still trying...\n");
961 if (m_state == m_slist)
962 strcpy(m_return_reason, "Connect: Trying");
964 Con_Printf("Trying...\n");
966 cls.connect_nextsendtime = realtime + 1;
967 cls.connect_remainingtries--;
968 // try challenge first (newer server)
969 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
970 // then try netquake as a fallback (old server, or netquake)
971 SZ_Clear(&net_message);
972 // save space for the header, filled in later
973 MSG_WriteLong(&net_message, 0);
974 MSG_WriteByte(&net_message, CCREQ_CONNECT);
975 MSG_WriteString(&net_message, "QUAKE");
976 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
977 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
978 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
979 SZ_Clear(&net_message);
981 for (i = 0;i < cl_numsockets;i++)
982 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
983 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
984 if (cls.netcon && realtime > cls.netcon->timeout)
986 Con_Printf("Connection timed out\n");
989 for (conn = netconn_list;conn;conn = conn->next)
990 NetConn_ReSendMessage(conn);
993 #define MAX_CHALLENGES 128
996 lhnetaddress_t address;
1000 challenge[MAX_CHALLENGES];
1002 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1006 for (i = 0;i < bufferlength - 1;i++)
1010 c = rand () % (127 - 33) + 33;
1011 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1017 extern void SV_ConnectClient(int clientnum, netconn_t *netconnection);
1018 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1020 int i, n, ret, clientnum, responselength, best;
1024 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1028 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1030 // received a command string - strip off the packaging and put it
1031 // into our string buffer with NULL termination
1034 length = min(length, (int)sizeof(stringbuf) - 1);
1035 memcpy(stringbuf, data, length);
1036 stringbuf[length] = 0;
1039 if (developer.integer)
1041 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1042 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1043 Com_HexDumpToConsole(data, length);
1046 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1048 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1050 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1052 if (besttime > challenge[i].time)
1053 besttime = challenge[best = i].time;
1055 // if we did not find an exact match, choose the oldest and
1056 // update address and string
1057 if (i == MAX_CHALLENGES)
1060 challenge[i].address = *peeraddress;
1061 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1063 challenge[i].time = realtime;
1064 // send the challenge
1065 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1068 if (length > 8 && !memcmp(string, "connect\\", 8))
1072 if ((s = SearchInfostring(string, "challenge")))
1074 // validate the challenge
1075 for (i = 0;i < MAX_CHALLENGES;i++)
1076 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1078 if (i < MAX_CHALLENGES)
1080 // check engine protocol
1081 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1083 if (developer.integer)
1084 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1085 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1089 // see if this is a duplicate connection request
1090 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1091 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1093 if (clientnum < svs.maxclients)
1095 // duplicate connection request
1096 if (realtime - client->netconnection->connecttime < 2.0)
1098 // client is still trying to connect,
1099 // so we send a duplicate reply
1100 if (developer.integer)
1101 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1102 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1104 // only kick if old connection seems dead
1105 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1107 // kick off connection and await retry
1108 client->deadsocket = true;
1113 // this is a new client, find a slot
1114 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1115 if (!client->active)
1117 if (clientnum < svs.maxclients)
1119 // prepare the client struct
1120 if ((client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_clients_mempool)))
1122 if ((conn = NetConn_Open(mysocket, peeraddress)))
1124 // allocated connection
1125 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1126 if (developer.integer)
1127 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1128 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1129 // now set up the client
1130 SV_ConnectClient(clientnum, conn);
1131 NetConn_Heartbeat(1);
1134 EntityFrame4_FreeDatabase(client->entitydatabase4);
1140 if (developer.integer)
1141 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1142 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1150 if (length >= 7 && !memcmp(string, "getinfo", 7))
1152 const char *challenge = NULL;
1153 // If there was a challenge in the getinfo message
1154 if (length > 8 && string[7] == ' ')
1155 challenge = string + 8;
1156 for (i = 0, n = 0;i < svs.maxclients;i++)
1157 if (svs.clients[i].active)
1159 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1160 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1161 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1162 gamename, com_modname, svs.maxclients, n,
1163 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1164 // does it fit in the buffer?
1165 if (responselength < (int)sizeof(response))
1167 if (developer.integer)
1168 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1169 NetConn_WriteString(mysocket, response, peeraddress);
1174 if (!strncmp(string, "ping", 4))
1176 if (developer.integer)
1177 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1178 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1181 if (!strncmp(string, "ack", 3))
1184 // we may not have liked the packet, but it was a command packet, so
1185 // we're done processing this packet now
1188 // LordHavoc: disabled netquake control packet support in server
1192 // netquake control packets, supported for compatibility only
1193 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1198 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1202 //if (developer.integer)
1203 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1204 if (length >= (int)strlen("QUAKE") + 1 + 1)
1206 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1208 if (developer.integer)
1209 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1210 SZ_Clear(&net_message);
1211 // save space for the header, filled in later
1212 MSG_WriteLong(&net_message, 0);
1213 MSG_WriteByte(&net_message, CCREP_REJECT);
1214 MSG_WriteString(&net_message, "Incompatible version.\n");
1215 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1216 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1217 SZ_Clear(&net_message);
1221 // see if this is a duplicate connection request
1222 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1223 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1225 if (clientnum < svs.maxclients)
1227 // duplicate connection request
1228 if (realtime - client->netconnection->connecttime < 2.0)
1230 // client is still trying to connect,
1231 // so we send a duplicate reply
1232 if (developer.integer)
1233 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1234 SZ_Clear(&net_message);
1235 // save space for the header, filled in later
1236 MSG_WriteLong(&net_message, 0);
1237 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1238 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1239 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1240 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1241 SZ_Clear(&net_message);
1243 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1245 // the old client hasn't sent us anything
1246 // in quite a while, so kick off and let
1247 // the retry take care of it...
1248 client->deadsocket = true;
1253 // this is a new client, find a slot
1254 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1255 if (!client->active)
1257 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1259 // connect to the client
1260 // everything is allocated, just fill in the details
1261 strcpy(conn->address, addressstring2);
1262 if (developer.integer)
1263 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1264 // send back the info about the server connection
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_ACCEPT);
1269 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
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);
1273 // now set up the client struct
1274 SV_ConnectClient(clientnum, conn);
1275 NetConn_Heartbeat(1);
1279 //if (developer.integer)
1280 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1281 // no room; try to let player know
1282 SZ_Clear(&net_message);
1283 // save space for the header, filled in later
1284 MSG_WriteLong(&net_message, 0);
1285 MSG_WriteByte(&net_message, CCREP_REJECT);
1286 MSG_WriteString(&net_message, "Server is full.\n");
1287 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1288 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1289 SZ_Clear(&net_message);
1296 case CCREQ_SERVER_INFO:
1297 if (developer.integer)
1298 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1299 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1301 if (developer.integer)
1302 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1303 SZ_Clear(&net_message);
1304 // save space for the header, filled in later
1305 MSG_WriteLong(&net_message, 0);
1306 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1307 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1308 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1309 MSG_WriteString(&net_message, hostname.string);
1310 MSG_WriteString(&net_message, sv.name);
1311 MSG_WriteByte(&net_message, net_activeconnections);
1312 MSG_WriteByte(&net_message, svs.maxclients);
1313 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1314 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1315 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1316 SZ_Clear(&net_message);
1319 case CCREQ_PLAYER_INFO:
1320 if (developer.integer)
1321 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1324 int playerNumber, activeNumber, clientNumber;
1327 playerNumber = MSG_ReadByte();
1329 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1330 if (client->active && ++activeNumber == playerNumber)
1332 if (clientNumber != svs.maxclients)
1334 SZ_Clear(&net_message);
1335 // save space for the header, filled in later
1336 MSG_WriteLong(&net_message, 0);
1337 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1338 MSG_WriteByte(&net_message, playerNumber);
1339 MSG_WriteString(&net_message, client->name);
1340 MSG_WriteLong(&net_message, client->colors);
1341 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1342 MSG_WriteLong(&net_message, (int)(realtime - client->netconnection->connecttime));
1343 MSG_WriteString(&net_message, client->netconnection->address);
1344 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1345 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1346 SZ_Clear(&net_message);
1350 case CCREQ_RULE_INFO:
1351 if (developer.integer)
1352 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1358 // find the search start location
1359 prevCvarName = MSG_ReadString();
1360 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1362 // send the response
1363 SZ_Clear(&net_message);
1364 // save space for the header, filled in later
1365 MSG_WriteLong(&net_message, 0);
1366 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1369 MSG_WriteString(&net_message, var->name);
1370 MSG_WriteString(&net_message, var->string);
1372 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1373 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1374 SZ_Clear(&net_message);
1381 // we may not have liked the packet, but it was a valid control
1382 // packet, so we're done processing this packet now
1387 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1389 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1391 sv_player = host_client->edict;
1392 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1393 SV_ReadClientMessage();
1401 void NetConn_ServerFrame(void)
1404 lhnetaddress_t peeraddress;
1406 NetConn_UpdateServerStuff();
1407 for (i = 0;i < sv_numsockets;i++)
1408 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1409 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1410 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1412 // never timeout loopback connections
1413 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(host_client->netconnection->mysocket)) != LHNETADDRESSTYPE_LOOP)
1415 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1416 sv_player = host_client->edict;
1417 SV_DropClient(false);
1420 for (conn = netconn_list;conn;conn = conn->next)
1421 NetConn_ReSendMessage(conn);
1424 void NetConn_QueryMasters(void)
1428 lhnetaddress_t masteraddress;
1431 if (hostCacheCount >= HOSTCACHESIZE)
1434 for (i = 0;i < cl_numsockets;i++)
1441 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1443 SZ_Clear(&net_message);
1444 // save space for the header, filled in later
1445 MSG_WriteLong(&net_message, 0);
1446 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1447 MSG_WriteString(&net_message, "QUAKE");
1448 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1449 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1450 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1451 SZ_Clear(&net_message);
1455 // build the getservers
1456 snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1459 for (masternum = 0;sv_masters[masternum].name;masternum++)
1461 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1464 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1469 if (!masterquerycount)
1471 Con_Printf("Unable to query master servers, no suitable network sockets active.\n");
1472 strcpy(m_return_reason, "No network");
1476 void NetConn_Heartbeat(int priority)
1478 lhnetaddress_t masteraddress;
1480 lhnetsocket_t *mysocket;
1482 // if it's a state change (client connected), limit next heartbeat to no
1483 // more than 30 sec in the future
1484 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1485 nextheartbeattime = realtime + 30.0;
1487 // limit heartbeatperiod to 30 to 270 second range,
1488 // lower limit is to avoid abusing master servers with excess traffic,
1489 // upper limit is to avoid timing out on the master server (which uses
1491 if (sv_heartbeatperiod.value < 30)
1492 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1493 if (sv_heartbeatperiod.value > 270)
1494 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1496 // make advertising optional and don't advertise singleplayer games, and
1497 // only send a heartbeat as often as the admin wants
1498 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1500 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1501 for (masternum = 0;sv_masters[masternum].name;masternum++)
1502 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1503 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1507 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1510 qbyte sent[MAX_SCOREBOARD];
1512 memset(sent, 0, sizeof(sent));
1514 // simultaneously wait for the first CanSendMessage and send the message,
1515 // then wait for a second CanSendMessage (verifying it was received), or
1516 // the client drops and is no longer counted
1517 // the loop aborts when either it runs out of clients to send to, or a
1519 blocktime += Sys_DoubleTime();
1523 NetConn_ClientFrame();
1524 NetConn_ServerFrame();
1525 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1527 if (host_client->netconnection)
1529 if (NetConn_CanSendMessage(host_client->netconnection))
1532 NetConn_SendReliableMessage(host_client->netconnection, data);
1535 if (!NetConn_CanSendMessage(host_client->netconnection))
1540 while (count && Sys_DoubleTime() < blocktime);
1544 static void Net_Heartbeat_f(void)
1547 NetConn_Heartbeat(2);
1549 Con_Printf("No server running, can not heartbeat to master server.\n");
1552 void PrintStats(netconn_t *conn)
1554 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1557 void Net_Stats_f(void)
1560 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1561 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1562 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1563 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1564 Con_Printf("packetsSent = %i\n", packetsSent);
1565 Con_Printf("packetsReSent = %i\n", packetsReSent);
1566 Con_Printf("packetsReceived = %i\n", packetsReceived);
1567 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1568 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1569 Con_Printf("connections =\n");
1570 for (conn = netconn_list;conn;conn = conn->next)
1574 void Net_Slist_f(void)
1576 masterquerytime = realtime;
1577 masterquerycount = 0;
1578 masterreplycount = 0;
1579 serverquerycount = 0;
1580 serverreplycount = 0;
1582 memset(&pingcache, 0, sizeof(pingcache));
1583 if (m_state != m_slist)
1584 Con_Printf("Sending requests to master servers\n");
1585 NetConn_QueryMasters();
1586 if (m_state != m_slist)
1587 Con_Printf("Listening for replies...\n");
1590 void NetConn_Init(void)
1593 lhnetaddress_t tempaddress;
1594 netconn_mempool = Mem_AllocPool("Networking");
1595 Cmd_AddCommand("net_stats", Net_Stats_f);
1596 Cmd_AddCommand("net_slist", Net_Slist_f);
1597 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1598 Cvar_RegisterVariable(&net_messagetimeout);
1599 Cvar_RegisterVariable(&net_messagerejointimeout);
1600 Cvar_RegisterVariable(&net_connecttimeout);
1601 Cvar_RegisterVariable(&cl_fakelocalping_min);
1602 Cvar_RegisterVariable(&cl_fakelocalping_max);
1603 Cvar_RegisterVariable(&cl_fakepacketloss_receive);
1604 Cvar_RegisterVariable(&cl_fakepacketloss_send);
1605 Cvar_RegisterVariable(&sv_fakepacketloss_receive);
1606 Cvar_RegisterVariable(&sv_fakepacketloss_send);
1607 Cvar_RegisterVariable(&hostname);
1608 Cvar_RegisterVariable(&developer_networking);
1609 Cvar_RegisterVariable(&cl_netport);
1610 Cvar_RegisterVariable(&cl_netaddress);
1611 Cvar_RegisterVariable(&cl_netaddress_ipv6);
1612 Cvar_RegisterVariable(&sv_netport);
1613 Cvar_RegisterVariable(&sv_netaddress);
1614 Cvar_RegisterVariable(&sv_netaddress_ipv6);
1615 Cvar_RegisterVariable(&sv_public);
1616 Cvar_RegisterVariable(&sv_heartbeatperiod);
1617 for (i = 0;sv_masters[i].name;i++)
1618 Cvar_RegisterVariable(&sv_masters[i]);
1619 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1621 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1623 Con_Printf("-ip option used, setting cl_netaddress and sv_netaddress to address \"%s\"\n");
1624 Cvar_SetQuick(&cl_netaddress, com_argv[i + 1]);
1625 Cvar_SetQuick(&sv_netaddress, com_argv[i + 1]);
1628 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1630 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1632 i = atoi(com_argv[i + 1]);
1633 if (i >= 0 && i < 65536)
1635 Con_Printf("-port option used, setting port cvar to %i\n", i);
1636 Cvar_SetValueQuick(&sv_netport, i);
1639 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1643 memset(&pingcache, 0, sizeof(pingcache));
1644 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1648 void NetConn_Shutdown(void)
1650 NetConn_CloseClientPorts();
1651 NetConn_CloseServerPorts();