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 int hostCacheCount = 0;
72 hostcache_t hostcache[HOSTCACHESIZE];
74 static qbyte sendbuffer[NET_MAXMESSAGE];
75 static qbyte readbuffer[NET_MAXMESSAGE];
78 lhnetsocket_t *cl_sockets[16];
80 lhnetsocket_t *sv_sockets[16];
82 netconn_t *netconn_list = NULL;
83 mempool_t *netconn_mempool = NULL;
85 cvar_t cl_netport = {0, "cl_port", "0"};
86 cvar_t cl_netaddress = {0, "cl_netaddress", "0.0.0.0"};
87 cvar_t cl_netaddress_ipv6 = {0, "cl_netaddress_ipv6", "[0:0:0:0:0:0:0:0]:0"};
89 cvar_t sv_netport = {0, "port", "26000"};
90 cvar_t sv_netaddress = {0, "sv_netaddress", "0.0.0.0"};
91 cvar_t sv_netaddress_ipv6 = {0, "sv_netaddress_ipv6", "[0:0:0:0:0:0:0:0]:26000"};
93 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
95 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
97 if (cl_fakepacketloss_receive.integer)
98 for (i = 0;i < cl_numsockets;i++)
99 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_fakepacketloss_receive.integer)
101 if (sv_fakepacketloss_receive.integer)
102 for (i = 0;i < cl_numsockets;i++)
103 if (sv_sockets[i] == mysocket && (rand() % 100) < sv_fakepacketloss_receive.integer)
105 if (developer_networking.integer && length != 0)
107 char addressstring[128], addressstring2[128];
108 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
111 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
112 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
113 Com_HexDumpToConsole(data, length);
116 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
121 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
125 if (cl_fakepacketloss_send.integer)
126 for (i = 0;i < cl_numsockets;i++)
127 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_fakepacketloss_send.integer)
129 if (sv_fakepacketloss_send.integer)
130 for (i = 0;i < cl_numsockets;i++)
131 if (sv_sockets[i] == mysocket && (rand() % 100) < sv_fakepacketloss_send.integer)
133 ret = LHNET_Write(mysocket, data, length, peeraddress);
134 if (developer_networking.integer)
136 char addressstring[128], addressstring2[128];
137 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
138 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
139 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
140 Com_HexDumpToConsole(data, length);
145 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
147 // note this does not include the trailing NULL because we add that in the parser
148 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
151 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
153 unsigned int packetLen;
154 unsigned int dataLen;
156 unsigned int *header;
159 if (data->cursize == 0)
160 Sys_Error("Datagram_SendMessage: zero length message\n");
162 if (data->cursize > NET_MAXMESSAGE)
163 Sys_Error("Datagram_SendMessage: message too big %u\n", data->cursize);
165 if (conn->canSend == false)
166 Sys_Error("SendMessage: called with canSend == false\n");
169 memcpy(conn->sendMessage, data->data, data->cursize);
170 conn->sendMessageLength = data->cursize;
172 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
174 dataLen = conn->sendMessageLength;
179 dataLen = MAX_PACKETFRAGMENT;
183 packetLen = NET_HEADERSIZE + dataLen;
185 header = (void *)sendbuffer;
186 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
187 header[1] = BigLong(conn->sendSequence);
188 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
190 conn->sendSequence++;
191 conn->canSend = false;
193 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
196 conn->lastSendTime = realtime;
198 reliableMessagesSent++;
202 static void NetConn_SendMessageNext(netconn_t *conn)
204 unsigned int packetLen;
205 unsigned int dataLen;
207 unsigned int *header;
209 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
211 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
213 dataLen = conn->sendMessageLength;
218 dataLen = MAX_PACKETFRAGMENT;
222 packetLen = NET_HEADERSIZE + dataLen;
224 header = (void *)sendbuffer;
225 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
226 header[1] = BigLong(conn->sendSequence);
227 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
229 conn->sendSequence++;
230 conn->sendNext = false;
232 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
235 conn->lastSendTime = realtime;
240 static void NetConn_ReSendMessage(netconn_t *conn)
242 unsigned int packetLen;
243 unsigned int dataLen;
245 unsigned int *header;
247 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
249 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
251 dataLen = conn->sendMessageLength;
256 dataLen = MAX_PACKETFRAGMENT;
260 packetLen = NET_HEADERSIZE + dataLen;
262 header = (void *)sendbuffer;
263 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
264 header[1] = BigLong(conn->sendSequence - 1);
265 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
267 conn->sendNext = false;
269 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
272 conn->lastSendTime = realtime;
277 qboolean NetConn_CanSendMessage(netconn_t *conn)
279 return conn->canSend;
282 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
288 if (data->cursize == 0)
289 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
291 if (data->cursize > MAX_DATAGRAM)
292 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
295 packetLen = NET_HEADERSIZE + data->cursize;
297 header = (void *)sendbuffer;
298 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
299 header[1] = BigLong(conn->unreliableSendSequence);
300 memcpy(sendbuffer + 8, data->data, data->cursize);
302 conn->unreliableSendSequence++;
304 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
308 unreliableMessagesSent++;
312 void NetConn_CloseClientPorts(void)
314 for (;cl_numsockets > 0;cl_numsockets--)
315 if (cl_sockets[cl_numsockets - 1])
316 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
319 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
321 lhnetaddress_t address;
323 char addressstring2[1024];
324 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
326 if ((s = LHNET_OpenSocket_Connectionless(&address)))
328 cl_sockets[cl_numsockets++] = s;
329 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
330 Con_Printf("Client opened a socket on address %s\n", addressstring2);
334 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
335 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
339 Con_Printf("Client unable to parse address %s\n", addressstring);
342 void NetConn_OpenClientPorts(void)
345 NetConn_CloseClientPorts();
346 port = bound(0, cl_netport.integer, 65535);
347 if (cl_netport.integer != port)
348 Cvar_SetValueQuick(&cl_netport, port);
349 Con_Printf("Client using port %i\n", port);
350 NetConn_OpenClientPort("local", port);
351 NetConn_OpenClientPort(cl_netaddress.string, port);
352 NetConn_OpenClientPort(cl_netaddress_ipv6.string, port);
355 void NetConn_CloseServerPorts(void)
357 for (;sv_numsockets > 0;sv_numsockets--)
358 if (sv_sockets[sv_numsockets - 1])
359 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
362 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
364 lhnetaddress_t address;
366 char addressstring2[1024];
367 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
369 if ((s = LHNET_OpenSocket_Connectionless(&address)))
371 sv_sockets[sv_numsockets++] = s;
372 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
373 Con_Printf("Server listening on address %s\n", addressstring2);
377 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
378 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
382 Con_Printf("Server unable to parse address %s\n", addressstring);
385 void NetConn_OpenServerPorts(int opennetports)
388 NetConn_CloseServerPorts();
389 port = bound(0, sv_netport.integer, 65535);
392 Con_Printf("Server using port %i\n", port);
393 if (sv_netport.integer != port)
394 Cvar_SetValueQuick(&sv_netport, port);
395 if (cls.state != ca_dedicated)
396 NetConn_OpenServerPort("local", port);
399 NetConn_OpenServerPort(sv_netaddress.string, port);
400 NetConn_OpenServerPort(sv_netaddress_ipv6.string, port);
402 if (sv_numsockets == 0)
403 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
406 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
408 int i, a = LHNETADDRESS_GetAddressType(address);
409 for (i = 0;i < cl_numsockets;i++)
410 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
411 return cl_sockets[i];
415 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
417 int i, a = LHNETADDRESS_GetAddressType(address);
418 for (i = 0;i < sv_numsockets;i++)
419 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
420 return sv_sockets[i];
424 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
427 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
428 conn->mysocket = mysocket;
429 conn->peeraddress = *peeraddress;
430 conn->canSend = true;
431 conn->connecttime = realtime;
432 conn->lastMessageTime = realtime;
433 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
434 // reduce effectiveness of connection request floods
435 conn->timeout = realtime + net_connecttimeout.value;
436 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
437 conn->next = netconn_list;
442 void NetConn_Close(netconn_t *conn)
445 // remove connection from list
446 if (conn == netconn_list)
447 netconn_list = conn->next;
450 for (c = netconn_list;c;c = c->next)
454 c->next = conn->next;
458 // not found in list, we'll avoid crashing here...
466 static int clientport = -1;
467 static int clientport2 = -1;
468 static int hostport = -1;
469 static void NetConn_UpdateServerStuff(void)
471 if (clientport2 != cl_netport.integer)
473 clientport2 = cl_netport.integer;
474 if (cls.state == ca_connected)
475 Con_Printf("Changing \"cl_port\" will not take effect until you reconnect.\n");
477 if (cls.state != ca_dedicated)
479 if (cls.state == ca_disconnected && clientport != cl_netport.integer)
481 clientport = cl_netport.integer;
482 NetConn_CloseClientPorts();
484 if (cl_numsockets == 0)
485 NetConn_OpenClientPorts();
488 if (hostport != sv_netport.integer)
490 hostport = sv_netport.integer;
492 Con_Printf("Changing \"port\" will not take effect until \"map\" command is executed.\n");
496 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
500 unsigned int sequence;
504 length = BigLong(((int *)data)[0]);
505 flags = length & ~NETFLAG_LENGTH_MASK;
506 length &= NETFLAG_LENGTH_MASK;
507 // control packets were already handled
508 if (!(flags & NETFLAG_CTL))
510 sequence = BigLong(((int *)data)[1]);
514 if (flags & NETFLAG_UNRELIABLE)
516 if (sequence >= conn->unreliableReceiveSequence)
518 if (sequence > conn->unreliableReceiveSequence)
520 count = sequence - conn->unreliableReceiveSequence;
521 droppedDatagrams += count;
522 Con_DPrintf("Dropped %u datagram(s)\n", count);
524 conn->unreliableReceiveSequence = sequence + 1;
525 conn->lastMessageTime = realtime;
526 conn->timeout = realtime + net_messagetimeout.value;
527 unreliableMessagesReceived++;
530 SZ_Clear(&net_message);
531 SZ_Write(&net_message, data, length);
537 Con_DPrintf("Got a stale datagram\n");
540 else if (flags & NETFLAG_ACK)
542 if (sequence == (conn->sendSequence - 1))
544 if (sequence == conn->ackSequence)
547 if (conn->ackSequence != conn->sendSequence)
548 Con_DPrintf("ack sequencing error\n");
549 conn->lastMessageTime = realtime;
550 conn->timeout = realtime + net_messagetimeout.value;
551 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
552 if (conn->sendMessageLength > 0)
554 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
555 conn->sendNext = true;
556 NetConn_SendMessageNext(conn);
560 conn->sendMessageLength = 0;
561 conn->canSend = true;
565 Con_DPrintf("Duplicate ACK received\n");
568 Con_DPrintf("Stale ACK received\n");
571 else if (flags & NETFLAG_DATA)
573 unsigned int temppacket[2];
574 temppacket[0] = BigLong(8 | NETFLAG_ACK);
575 temppacket[1] = BigLong(sequence);
576 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
577 if (sequence == conn->receiveSequence)
579 conn->lastMessageTime = realtime;
580 conn->timeout = realtime + net_messagetimeout.value;
581 conn->receiveSequence++;
582 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
583 conn->receiveMessageLength += length;
584 if (flags & NETFLAG_EOM)
586 reliableMessagesReceived++;
587 length = conn->receiveMessageLength;
588 conn->receiveMessageLength = 0;
591 SZ_Clear(&net_message);
592 SZ_Write(&net_message, conn->receiveMessage, length);
599 receivedDuplicateCount++;
607 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
609 cls.netcon = NetConn_Open(mysocket, peeraddress);
610 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
613 cls.connect_trying = false;
614 cls.demonum = -1; // not in the demo loop now
615 cls.state = ca_connected;
616 cls.signon = 0; // need all the signon messages before playing
621 int NetConn_IsLocalGame(void)
623 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
631 lhnetaddress_t peeraddress;
633 pingcache[HOSTCACHESIZE];
635 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
638 lhnetaddress_t svaddress;
640 char *string, addressstring2[128], cname[128], ipstring[32];
641 char stringbuf[16384];
643 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
645 // received a command string - strip off the packaging and put it
646 // into our string buffer with NULL termination
649 length = min(length, (int)sizeof(stringbuf) - 1);
650 memcpy(stringbuf, data, length);
651 stringbuf[length] = 0;
654 if (developer.integer)
656 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
657 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
658 Com_HexDumpToConsole(data, length);
661 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
663 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
664 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
665 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
668 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
670 NetConn_ConnectionEstablished(mysocket, peeraddress);
673 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
675 cls.connect_trying = false;
677 length = max(length - 7, (int)sizeof(m_return_reason) - 1);
678 memcpy(m_return_reason, string, length);
679 m_return_reason[length] = 0;
680 Con_Printf("%s\n", m_return_reason);
683 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
685 int i, j, c, n, users, maxusers;
686 char game[32], mod[32], map[32], name[128];
690 // hostcache only uses text addresses
691 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
692 // search the cache for this server
693 for (n = 0; n < hostCacheCount; n++)
694 if (!strcmp(cname, hostcache[n].cname))
696 // add it or update it
697 if (n == hostCacheCount)
699 // if cache is full replace highest ping server (the list is
700 // kept sorted so this is always the last, and if this server
701 // is good it will be sorted into an early part of the list)
702 if (hostCacheCount >= HOSTCACHESIZE)
703 n = hostCacheCount - 1;
707 if ((s = SearchInfostring(string, "gamename" )) != NULL) strncpy(game, s, sizeof(game) - 1);else game[0] = 0;
708 if ((s = SearchInfostring(string, "modname" )) != NULL) strncpy(mod , s, sizeof(mod ) - 1);else mod[0] = 0;
709 if ((s = SearchInfostring(string, "mapname" )) != NULL) strncpy(map , s, sizeof(map ) - 1);else map[0] = 0;
710 if ((s = SearchInfostring(string, "hostname" )) != NULL) strncpy(name, s, sizeof(name) - 1);else name[0] = 0;
711 if ((s = SearchInfostring(string, "protocol" )) != NULL) c = atoi(s);else c = -1;
712 if ((s = SearchInfostring(string, "clients" )) != NULL) users = atoi(s);else users = 0;
713 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) maxusers = atoi(s);else maxusers = 0;
715 for (i = 0;i < HOSTCACHESIZE;i++)
716 if (!LHNETADDRESS_Compare(peeraddress, &pingcache[i].peeraddress))
717 pingtime = (int)(realtime - pingcache[i].senttime);
718 pingtime = bound(0, pingtime, 9999);
719 memset(&hostcache[n], 0, sizeof(hostcache[n]));
720 // store the data the engine cares about (address and ping)
721 strcpy(hostcache[n].cname, cname);
722 hostcache[n].ping = pingtime;
723 // build description strings for the things users care about
724 snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, c != NET_PROTOCOL_VERSION ? '*' : ' ', users, maxusers, name);
725 snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", cname, game, mod, map);
726 // if ping is especially high, display it as such
729 // orange numbers (lower block)
730 for (i = 0;i < 5;i++)
731 if (hostcache[n].line1[i] != ' ')
732 hostcache[n].line1[i] += 128;
734 else if (pingtime >= 200)
736 // yellow numbers (in upper block)
737 for (i = 0;i < 5;i++)
738 if (hostcache[n].line1[i] != ' ')
739 hostcache[n].line1[i] -= 30;
741 // if not in the slist menu we should print the server to console
742 if (m_state != m_slist)
743 Con_Printf("%s\n%s\n", hostcache[n].line1, hostcache[n].line2);
744 // and finally, re-sort the list
745 for (i = 0;i < hostCacheCount;i++)
747 for (j = i + 1;j < hostCacheCount;j++)
749 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
750 if (hostcache[i].ping > hostcache[j].ping)
752 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
753 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
754 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
760 if (!strncmp(string, "getserversResponse\\", 19) && hostCacheCount < HOSTCACHESIZE)
764 // Extract the IP addresses
767 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
769 sprintf(ipstring, "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
770 if (developer.integer)
771 Con_Printf("Requesting info from server %s\n", ipstring);
772 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
773 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
774 // replace oldest or matching entry in ping cache
775 // we scan this later when getting a reply to see how long it took
778 for (i = 0;i < HOSTCACHESIZE;i++)
780 if (!LHNETADDRESS_Compare(&svaddress, &pingcache[i].peeraddress))
785 if (besttime > pingcache[i].senttime)
787 besttime = pingcache[i].senttime;
789 // if ping cache isn't full yet we can skip out early
794 pingcache[best].peeraddress = svaddress;
795 pingcache[best].senttime = realtime;
796 // move on to next address in packet
803 if (!strncmp(string, "ping", 4))
805 if (developer.integer)
806 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
807 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
810 if (!strncmp(string, "ack", 3))
813 // we may not have liked the packet, but it was a command packet, so
814 // we're done processing this packet now
817 // netquake control packets, supported for compatibility only
818 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
823 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
827 if (developer.integer)
828 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
829 if (cls.connect_trying)
831 lhnetaddress_t clientportaddress;
832 clientportaddress = *peeraddress;
835 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
838 LHNETADDRESS_SetPort(&clientportaddress, port);
840 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
844 if (developer.integer)
845 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
846 Con_Printf("%s\n", data);
847 strncpy(m_return_reason, data, sizeof(m_return_reason) - 1);
850 case CCREP_SERVER_INFO:
851 if (developer.integer)
852 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
853 if (cls.state != ca_dedicated)
855 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
856 // string we just ignore it and keep the real address
858 // hostcache only uses text addresses
859 cname = UDP_AddrToString(readaddr);
860 // search the cache for this server
861 for (n = 0; n < hostCacheCount; n++)
862 if (!strcmp(cname, hostcache[n].cname))
865 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
868 memset(&hostcache[n], 0, sizeof(hostcache[n]));
869 strcpy(hostcache[n].name, MSG_ReadString());
870 strcpy(hostcache[n].map, MSG_ReadString());
871 hostcache[n].users = MSG_ReadByte();
872 hostcache[n].maxusers = MSG_ReadByte();
874 if (c != NET_PROTOCOL_VERSION)
876 strncpy(hostcache[n].cname, hostcache[n].name, sizeof(hostcache[n].cname) - 1);
877 hostcache[n].cname[sizeof(hostcache[n].cname) - 1] = 0;
878 strcpy(hostcache[n].name, "*");
879 strncat(hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name) - 1);
880 hostcache[n].name[sizeof(hostcache[n].name) - 1] = 0;
882 strcpy(hostcache[n].cname, cname);
886 case CCREP_PLAYER_INFO:
887 // we got a CCREP_PLAYER_INFO??
888 //if (developer.integer)
889 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
891 case CCREP_RULE_INFO:
892 // we got a CCREP_RULE_INFO??
893 //if (developer.integer)
894 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
900 // we may not have liked the packet, but it was a valid control
901 // packet, so we're done processing this packet now
905 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)
906 CL_ParseServerMessage();
910 void NetConn_ClientFrame(void)
913 lhnetaddress_t peeraddress;
915 NetConn_UpdateServerStuff();
916 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
918 if (cls.connect_remainingtries == 0)
920 cls.connect_trying = false;
921 Con_Printf("Connect failed\n");
924 if (cls.connect_nextsendtime)
925 Con_Printf("Still trying...\n");
927 Con_Printf("Trying...\n");
928 cls.connect_nextsendtime = realtime + 1;
929 cls.connect_remainingtries--;
930 // try challenge first (newer server)
931 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
932 // then try netquake as a fallback (old server, or netquake)
933 SZ_Clear(&net_message);
934 // save space for the header, filled in later
935 MSG_WriteLong(&net_message, 0);
936 MSG_WriteByte(&net_message, CCREQ_CONNECT);
937 MSG_WriteString(&net_message, "QUAKE");
938 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
939 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
940 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
941 SZ_Clear(&net_message);
943 for (i = 0;i < cl_numsockets;i++)
944 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
945 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
946 if (cls.netcon && realtime > cls.netcon->timeout)
948 Con_Printf("Connection timed out\n");
951 for (conn = netconn_list;conn;conn = conn->next)
952 NetConn_ReSendMessage(conn);
955 #define MAX_CHALLENGES 128
958 lhnetaddress_t address;
962 challenge[MAX_CHALLENGES];
964 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
968 for (i = 0;i < bufferlength - 1;i++)
972 c = rand () % (127 - 33) + 33;
973 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
979 extern void SV_ConnectClient(int clientnum, netconn_t *netconnection);
980 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
982 int i, n, ret, clientnum, responselength, best;
986 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
990 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
992 // received a command string - strip off the packaging and put it
993 // into our string buffer with NULL termination
996 length = min(length, (int)sizeof(stringbuf) - 1);
997 memcpy(stringbuf, data, length);
998 stringbuf[length] = 0;
1001 if (developer.integer)
1003 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1004 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1005 Com_HexDumpToConsole(data, length);
1008 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1010 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1012 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1014 if (besttime > challenge[i].time)
1015 besttime = challenge[best = i].time;
1017 // if we did not find an exact match, choose the oldest and
1018 // update address and string
1019 if (i == MAX_CHALLENGES)
1022 challenge[i].address = *peeraddress;
1023 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1025 challenge[i].time = realtime;
1026 // send the challenge
1027 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1030 if (length > 8 && !memcmp(string, "connect\\", 8))
1034 if ((s = SearchInfostring(string, "challenge")))
1036 // validate the challenge
1037 for (i = 0;i < MAX_CHALLENGES;i++)
1038 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1040 if (i < MAX_CHALLENGES)
1042 // check engine protocol
1043 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1045 if (developer.integer)
1046 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1047 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1051 // see if this is a duplicate connection request
1052 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1053 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1055 if (clientnum < svs.maxclients)
1057 // duplicate connection request
1058 if (realtime - client->netconnection->connecttime < 2.0)
1060 // client is still trying to connect,
1061 // so we send a duplicate reply
1062 if (developer.integer)
1063 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1064 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1066 // only kick if old connection seems dead
1067 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1069 // kick off connection and await retry
1070 client->deadsocket = true;
1075 // this is a new client, find a slot
1076 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1077 if (!client->active)
1079 if (clientnum < svs.maxclients)
1081 // prepare the client struct
1082 if ((client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_clients_mempool)))
1084 if ((conn = NetConn_Open(mysocket, peeraddress)))
1086 // allocated connection
1087 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1088 if (developer.integer)
1089 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1090 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1091 // now set up the client
1092 SV_ConnectClient(clientnum, conn);
1093 NetConn_Heartbeat(1);
1096 EntityFrame4_FreeDatabase(client->entitydatabase4);
1102 if (developer.integer)
1103 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1104 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1112 if (length >= 7 && !memcmp(string, "getinfo", 7))
1114 const char *challenge = NULL;
1115 // If there was a challenge in the getinfo message
1116 if (length > 8 && string[7] == ' ')
1117 challenge = string + 8;
1118 for (i = 0, n = 0;i < svs.maxclients;i++)
1119 if (svs.clients[i].active)
1121 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1122 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1123 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1124 gamename, com_modname, svs.maxclients, n,
1125 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1126 // does it fit in the buffer?
1127 if (responselength < (int)sizeof(response))
1129 if (developer.integer)
1130 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1131 NetConn_WriteString(mysocket, response, peeraddress);
1136 if (!strncmp(string, "ping", 4))
1138 if (developer.integer)
1139 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1140 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1143 if (!strncmp(string, "ack", 3))
1146 // we may not have liked the packet, but it was a command packet, so
1147 // we're done processing this packet now
1150 // LordHavoc: disabled netquake control packet support in server
1154 // netquake control packets, supported for compatibility only
1155 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1160 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1164 //if (developer.integer)
1165 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1166 if (length >= (int)strlen("QUAKE") + 1 + 1)
1168 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1170 if (developer.integer)
1171 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1172 SZ_Clear(&net_message);
1173 // save space for the header, filled in later
1174 MSG_WriteLong(&net_message, 0);
1175 MSG_WriteByte(&net_message, CCREP_REJECT);
1176 MSG_WriteString(&net_message, "Incompatible version.\n");
1177 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1178 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1179 SZ_Clear(&net_message);
1183 // see if this is a duplicate connection request
1184 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1185 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1187 if (clientnum < svs.maxclients)
1189 // duplicate connection request
1190 if (realtime - client->netconnection->connecttime < 2.0)
1192 // client is still trying to connect,
1193 // so we send a duplicate reply
1194 if (developer.integer)
1195 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1196 SZ_Clear(&net_message);
1197 // save space for the header, filled in later
1198 MSG_WriteLong(&net_message, 0);
1199 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1200 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1201 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1202 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1203 SZ_Clear(&net_message);
1205 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1207 // the old client hasn't sent us anything
1208 // in quite a while, so kick off and let
1209 // the retry take care of it...
1210 client->deadsocket = true;
1215 // this is a new client, find a slot
1216 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1217 if (!client->active)
1219 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1221 // connect to the client
1222 // everything is allocated, just fill in the details
1223 strcpy(conn->address, addressstring2);
1224 if (developer.integer)
1225 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1226 // send back the info about the server connection
1227 SZ_Clear(&net_message);
1228 // save space for the header, filled in later
1229 MSG_WriteLong(&net_message, 0);
1230 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1231 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1232 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1233 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1234 SZ_Clear(&net_message);
1235 // now set up the client struct
1236 SV_ConnectClient(clientnum, conn);
1237 NetConn_Heartbeat(1);
1241 //if (developer.integer)
1242 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1243 // no room; try to let player know
1244 SZ_Clear(&net_message);
1245 // save space for the header, filled in later
1246 MSG_WriteLong(&net_message, 0);
1247 MSG_WriteByte(&net_message, CCREP_REJECT);
1248 MSG_WriteString(&net_message, "Server is full.\n");
1249 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1250 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1251 SZ_Clear(&net_message);
1258 case CCREQ_SERVER_INFO:
1259 if (developer.integer)
1260 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1261 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1263 if (developer.integer)
1264 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
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_SERVER_INFO);
1269 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1270 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1271 MSG_WriteString(&net_message, hostname.string);
1272 MSG_WriteString(&net_message, sv.name);
1273 MSG_WriteByte(&net_message, net_activeconnections);
1274 MSG_WriteByte(&net_message, svs.maxclients);
1275 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1276 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1277 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1278 SZ_Clear(&net_message);
1281 case CCREQ_PLAYER_INFO:
1282 if (developer.integer)
1283 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1286 int playerNumber, activeNumber, clientNumber;
1289 playerNumber = MSG_ReadByte();
1291 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1292 if (client->active && ++activeNumber == playerNumber)
1294 if (clientNumber != svs.maxclients)
1296 SZ_Clear(&net_message);
1297 // save space for the header, filled in later
1298 MSG_WriteLong(&net_message, 0);
1299 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1300 MSG_WriteByte(&net_message, playerNumber);
1301 MSG_WriteString(&net_message, client->name);
1302 MSG_WriteLong(&net_message, client->colors);
1303 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1304 MSG_WriteLong(&net_message, (int)(realtime - client->netconnection->connecttime));
1305 MSG_WriteString(&net_message, client->netconnection->address);
1306 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1307 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1308 SZ_Clear(&net_message);
1312 case CCREQ_RULE_INFO:
1313 if (developer.integer)
1314 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1320 // find the search start location
1321 prevCvarName = MSG_ReadString();
1322 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1324 // send the response
1325 SZ_Clear(&net_message);
1326 // save space for the header, filled in later
1327 MSG_WriteLong(&net_message, 0);
1328 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1331 MSG_WriteString(&net_message, var->name);
1332 MSG_WriteString(&net_message, var->string);
1334 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1335 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1336 SZ_Clear(&net_message);
1343 // we may not have liked the packet, but it was a valid control
1344 // packet, so we're done processing this packet now
1349 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1351 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1353 sv_player = host_client->edict;
1354 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1355 SV_ReadClientMessage();
1363 void NetConn_ServerFrame(void)
1366 lhnetaddress_t peeraddress;
1368 NetConn_UpdateServerStuff();
1369 for (i = 0;i < sv_numsockets;i++)
1370 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1371 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1372 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1374 if (host_client->netconnection && realtime > host_client->netconnection->timeout)
1376 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1377 sv_player = host_client->edict;
1378 SV_DropClient(false);
1381 for (conn = netconn_list;conn;conn = conn->next)
1382 NetConn_ReSendMessage(conn);
1385 void NetConn_QueryMasters(void)
1389 lhnetaddress_t masteraddress;
1392 if (hostCacheCount >= HOSTCACHESIZE)
1395 for (i = 0;i < cl_numsockets;i++)
1402 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1404 SZ_Clear(&net_message);
1405 // save space for the header, filled in later
1406 MSG_WriteLong(&net_message, 0);
1407 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1408 MSG_WriteString(&net_message, "QUAKE");
1409 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1410 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1411 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1412 SZ_Clear(&net_message);
1416 // build the getservers
1417 snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1420 for (masternum = 0;sv_masters[masternum].name;masternum++)
1421 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1422 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1427 void NetConn_Heartbeat(int priority)
1429 lhnetaddress_t masteraddress;
1431 lhnetsocket_t *mysocket;
1433 // if it's a state change (client connected), limit next heartbeat to no
1434 // more than 30 sec in the future
1435 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1436 nextheartbeattime = realtime + 30.0;
1438 // limit heartbeatperiod to 30 to 270 second range,
1439 // lower limit is to avoid abusing master servers with excess traffic,
1440 // upper limit is to avoid timing out on the master server (which uses
1442 if (sv_heartbeatperiod.value < 30)
1443 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1444 if (sv_heartbeatperiod.value > 270)
1445 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1447 // make advertising optional and don't advertise singleplayer games, and
1448 // only send a heartbeat as often as the admin wants
1449 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1451 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1452 for (masternum = 0;sv_masters[masternum].name;masternum++)
1453 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1454 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1458 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1461 qbyte sent[MAX_SCOREBOARD];
1463 memset(sent, 0, sizeof(sent));
1465 // simultaneously wait for the first CanSendMessage and send the message,
1466 // then wait for a second CanSendMessage (verifying it was received), or
1467 // the client drops and is no longer counted
1468 // the loop aborts when either it runs out of clients to send to, or a
1470 blocktime += Sys_DoubleTime();
1474 NetConn_ClientFrame();
1475 NetConn_ServerFrame();
1476 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1478 if (host_client->netconnection)
1480 if (NetConn_CanSendMessage(host_client->netconnection))
1483 NetConn_SendReliableMessage(host_client->netconnection, data);
1486 if (!NetConn_CanSendMessage(host_client->netconnection))
1491 while (count && Sys_DoubleTime() < blocktime);
1495 static void Net_Heartbeat_f(void)
1497 NetConn_Heartbeat(2);
1500 void PrintStats(netconn_t *conn)
1502 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1505 void Net_Stats_f(void)
1508 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1509 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1510 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1511 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1512 Con_Printf("packetsSent = %i\n", packetsSent);
1513 Con_Printf("packetsReSent = %i\n", packetsReSent);
1514 Con_Printf("packetsReceived = %i\n", packetsReceived);
1515 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1516 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1517 Con_Printf("connections =\n");
1518 for (conn = netconn_list;conn;conn = conn->next)
1522 void Net_Slist_f(void)
1525 memset(&pingcache, 0, sizeof(pingcache));
1526 if (m_state != m_slist)
1527 Con_Printf("Sending requests to master servers\n");
1528 NetConn_QueryMasters();
1529 if (m_state != m_slist)
1530 Con_Printf("Listening for replies...\n");
1533 void NetConn_Init(void)
1536 lhnetaddress_t tempaddress;
1537 netconn_mempool = Mem_AllocPool("Networking");
1538 Cmd_AddCommand("net_stats", Net_Stats_f);
1539 Cmd_AddCommand("net_slist", Net_Slist_f);
1540 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1541 Cvar_RegisterVariable(&net_messagetimeout);
1542 Cvar_RegisterVariable(&net_messagerejointimeout);
1543 Cvar_RegisterVariable(&net_connecttimeout);
1544 Cvar_RegisterVariable(&cl_fakelocalping_min);
1545 Cvar_RegisterVariable(&cl_fakelocalping_max);
1546 Cvar_RegisterVariable(&cl_fakepacketloss_receive);
1547 Cvar_RegisterVariable(&cl_fakepacketloss_send);
1548 Cvar_RegisterVariable(&sv_fakepacketloss_receive);
1549 Cvar_RegisterVariable(&sv_fakepacketloss_send);
1550 Cvar_RegisterVariable(&hostname);
1551 Cvar_RegisterVariable(&developer_networking);
1552 Cvar_RegisterVariable(&cl_netport);
1553 Cvar_RegisterVariable(&cl_netaddress);
1554 Cvar_RegisterVariable(&cl_netaddress_ipv6);
1555 Cvar_RegisterVariable(&sv_netport);
1556 Cvar_RegisterVariable(&sv_netaddress);
1557 Cvar_RegisterVariable(&sv_netaddress_ipv6);
1558 Cvar_RegisterVariable(&sv_public);
1559 Cvar_RegisterVariable(&sv_heartbeatperiod);
1560 for (i = 0;sv_masters[i].name;i++)
1561 Cvar_RegisterVariable(&sv_masters[i]);
1562 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1564 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1566 Con_Printf("-ip option used, setting cl_netaddress and sv_netaddress to address \"%s\"\n");
1567 Cvar_SetQuick(&cl_netaddress, com_argv[i + 1]);
1568 Cvar_SetQuick(&sv_netaddress, com_argv[i + 1]);
1571 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1573 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1575 i = atoi(com_argv[i + 1]);
1576 if (i >= 0 && i < 65536)
1578 Con_Printf("-port option used, setting port cvar to %i\n", i);
1579 Cvar_SetValueQuick(&sv_netport, i);
1582 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1586 memset(&pingcache, 0, sizeof(pingcache));
1587 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1591 void NetConn_Shutdown(void)
1593 NetConn_CloseClientPorts();
1594 NetConn_CloseServerPorts();