2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 See the GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 #define MASTER_PORT 27950
28 cvar_t sv_public = {0, "sv_public", "0"};
29 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "180"};
31 static cvar_t sv_masters [] =
33 {CVAR_SAVE, "sv_master1", ""},
34 {CVAR_SAVE, "sv_master2", ""},
35 {CVAR_SAVE, "sv_master3", ""},
36 {CVAR_SAVE, "sv_master4", ""},
37 {0, "sv_masterextra1", "69.59.212.88"},
38 {0, "sv_masterextra2", "66.28.32.64"},
42 static double nextheartbeattime = 0;
44 sizebuf_t net_message;
46 cvar_t net_messagetimeout = {0, "net_messagetimeout","300"};
47 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10"};
48 cvar_t net_connecttimeout = {0, "net_connecttimeout","10"};
49 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED"};
50 cvar_t developer_networking = {0, "developer_networking", "0"};
52 cvar_t cl_netlocalping_min = {0, "cl_netlocalping_min","0"};
53 cvar_t cl_netlocalping_max = {0, "cl_netlocalping_max","0"};
54 static cvar_t cl_netpacketloss_receive = {0, "cl_netpacketloss_receive","0"};
55 static cvar_t cl_netpacketloss_send = {0, "cl_netpacketloss_send","0"};
56 static cvar_t sv_netpacketloss_receive = {0, "sv_netpacketloss_receive","0"};
57 static cvar_t sv_netpacketloss_send = {0, "sv_netpacketloss_send","0"};
60 /* statistic counters */
61 static int packetsSent = 0;
62 static int packetsReSent = 0;
63 static int packetsReceived = 0;
64 static int receivedDuplicateCount = 0;
65 static int droppedDatagrams = 0;
67 static int unreliableMessagesSent = 0;
68 static int unreliableMessagesReceived = 0;
69 static int reliableMessagesSent = 0;
70 static int reliableMessagesReceived = 0;
72 double masterquerytime = -1000;
73 int masterquerycount = 0;
74 int masterreplycount = 0;
75 int serverquerycount = 0;
76 int serverreplycount = 0;
78 int hostCacheCount = 0;
79 hostcache_t hostcache[HOSTCACHESIZE];
81 static qbyte sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
82 static qbyte readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
85 lhnetsocket_t *cl_sockets[16];
87 lhnetsocket_t *sv_sockets[16];
89 netconn_t *netconn_list = NULL;
90 mempool_t *netconn_mempool = NULL;
92 cvar_t cl_netport = {0, "cl_port", "0"};
93 cvar_t sv_netport = {0, "port", "26000"};
94 cvar_t net_address = {0, "net_address", "0.0.0.0"};
95 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]"};
97 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
99 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
101 if (cl_netpacketloss_receive.integer)
102 for (i = 0;i < cl_numsockets;i++)
103 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_receive.integer)
105 if (sv_netpacketloss_receive.integer)
106 for (i = 0;i < cl_numsockets;i++)
107 if (sv_sockets[i] == mysocket && (rand() % 100) < sv_netpacketloss_receive.integer)
109 if (developer_networking.integer && length != 0)
111 char addressstring[128], addressstring2[128];
112 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
115 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
116 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
117 Com_HexDumpToConsole(data, length);
120 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
125 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
129 if (cl_netpacketloss_send.integer)
130 for (i = 0;i < cl_numsockets;i++)
131 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_send.integer)
133 if (sv_netpacketloss_send.integer)
134 for (i = 0;i < cl_numsockets;i++)
135 if (sv_sockets[i] == mysocket && (rand() % 100) < sv_netpacketloss_send.integer)
137 ret = LHNET_Write(mysocket, data, length, peeraddress);
138 if (developer_networking.integer)
140 char addressstring[128], addressstring2[128];
141 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
142 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
143 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
144 Com_HexDumpToConsole(data, length);
149 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
151 // note this does not include the trailing NULL because we add that in the parser
152 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
155 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
157 unsigned int packetLen;
158 unsigned int dataLen;
160 unsigned int *header;
163 if (data->cursize == 0)
164 Sys_Error("Datagram_SendMessage: zero length message\n");
166 if (data->cursize > (int)sizeof(conn->sendMessage))
167 Sys_Error("Datagram_SendMessage: message too big (%u > %u)\n", data->cursize, sizeof(conn->sendMessage));
169 if (conn->canSend == false)
170 Sys_Error("SendMessage: called with canSend == false\n");
173 memcpy(conn->sendMessage, data->data, data->cursize);
174 conn->sendMessageLength = data->cursize;
176 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
178 dataLen = conn->sendMessageLength;
183 dataLen = MAX_PACKETFRAGMENT;
187 packetLen = NET_HEADERSIZE + dataLen;
189 header = (void *)sendbuffer;
190 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
191 header[1] = BigLong(conn->sendSequence);
192 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
194 conn->sendSequence++;
195 conn->canSend = false;
197 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
200 conn->lastSendTime = realtime;
202 reliableMessagesSent++;
206 static void NetConn_SendMessageNext(netconn_t *conn)
208 unsigned int packetLen;
209 unsigned int dataLen;
211 unsigned int *header;
213 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
215 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
217 dataLen = conn->sendMessageLength;
222 dataLen = MAX_PACKETFRAGMENT;
226 packetLen = NET_HEADERSIZE + dataLen;
228 header = (void *)sendbuffer;
229 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
230 header[1] = BigLong(conn->sendSequence);
231 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
233 conn->sendSequence++;
234 conn->sendNext = false;
236 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
239 conn->lastSendTime = realtime;
244 static void NetConn_ReSendMessage(netconn_t *conn)
246 unsigned int packetLen;
247 unsigned int dataLen;
249 unsigned int *header;
251 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
253 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
255 dataLen = conn->sendMessageLength;
260 dataLen = MAX_PACKETFRAGMENT;
264 packetLen = NET_HEADERSIZE + dataLen;
266 header = (void *)sendbuffer;
267 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
268 header[1] = BigLong(conn->sendSequence - 1);
269 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
271 conn->sendNext = false;
273 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
276 conn->lastSendTime = realtime;
281 qboolean NetConn_CanSendMessage(netconn_t *conn)
283 return conn->canSend;
286 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
291 packetLen = NET_HEADERSIZE + data->cursize;
294 if (data->cursize == 0)
295 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
297 if (packetLen > (int)sizeof(sendbuffer))
298 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
301 header = (void *)sendbuffer;
302 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
303 header[1] = BigLong(conn->unreliableSendSequence);
304 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
306 conn->unreliableSendSequence++;
308 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
312 unreliableMessagesSent++;
316 void NetConn_CloseClientPorts(void)
318 for (;cl_numsockets > 0;cl_numsockets--)
319 if (cl_sockets[cl_numsockets - 1])
320 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
323 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
325 lhnetaddress_t address;
327 char addressstring2[1024];
328 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
330 if ((s = LHNET_OpenSocket_Connectionless(&address)))
332 cl_sockets[cl_numsockets++] = s;
333 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
334 Con_Printf("Client opened a socket on address %s\n", addressstring2);
338 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
339 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
343 Con_Printf("Client unable to parse address %s\n", addressstring);
346 void NetConn_OpenClientPorts(void)
349 NetConn_CloseClientPorts();
350 port = bound(0, cl_netport.integer, 65535);
351 if (cl_netport.integer != port)
352 Cvar_SetValueQuick(&cl_netport, port);
353 Con_Printf("Client using port %i\n", port);
354 NetConn_OpenClientPort("local:2", 0);
355 NetConn_OpenClientPort(net_address.string, port);
356 //NetConn_OpenClientPort(net_address_ipv6.string, port);
359 void NetConn_CloseServerPorts(void)
361 for (;sv_numsockets > 0;sv_numsockets--)
362 if (sv_sockets[sv_numsockets - 1])
363 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
366 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
368 lhnetaddress_t address;
370 char addressstring2[1024];
371 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
373 if ((s = LHNET_OpenSocket_Connectionless(&address)))
375 sv_sockets[sv_numsockets++] = s;
376 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
377 Con_Printf("Server listening on address %s\n", addressstring2);
381 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
382 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
386 Con_Printf("Server unable to parse address %s\n", addressstring);
389 void NetConn_OpenServerPorts(int opennetports)
392 NetConn_CloseServerPorts();
393 port = bound(0, sv_netport.integer, 65535);
396 Con_Printf("Server using port %i\n", port);
397 if (sv_netport.integer != port)
398 Cvar_SetValueQuick(&sv_netport, port);
399 if (cls.state != ca_dedicated)
400 NetConn_OpenServerPort("local:1", 0);
403 NetConn_OpenServerPort(net_address.string, port);
404 //NetConn_OpenServerPort(net_address_ipv6.string, port);
406 if (sv_numsockets == 0)
407 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
410 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
412 int i, a = LHNETADDRESS_GetAddressType(address);
413 for (i = 0;i < cl_numsockets;i++)
414 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
415 return cl_sockets[i];
419 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
421 int i, a = LHNETADDRESS_GetAddressType(address);
422 for (i = 0;i < sv_numsockets;i++)
423 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
424 return sv_sockets[i];
428 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
431 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
432 conn->mysocket = mysocket;
433 conn->peeraddress = *peeraddress;
434 // updated by receiving "rate" command from client
435 conn->rate = NET_MINRATE;
436 // no limits for local player
437 if (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP)
438 conn->rate = 1000000000;
439 conn->canSend = true;
440 conn->connecttime = realtime;
441 conn->lastMessageTime = realtime;
442 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
443 // reduce effectiveness of connection request floods
444 conn->timeout = realtime + net_connecttimeout.value;
445 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
446 conn->next = netconn_list;
451 void NetConn_Close(netconn_t *conn)
454 // remove connection from list
455 if (conn == netconn_list)
456 netconn_list = conn->next;
459 for (c = netconn_list;c;c = c->next)
463 c->next = conn->next;
467 // not found in list, we'll avoid crashing here...
475 static int clientport = -1;
476 static int clientport2 = -1;
477 static int hostport = -1;
478 static void NetConn_UpdateServerStuff(void)
480 if (cls.state != ca_dedicated)
482 if (clientport2 != cl_netport.integer)
484 clientport2 = cl_netport.integer;
485 if (cls.state == ca_connected)
486 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
488 if (cls.state == ca_disconnected && clientport != clientport2)
490 clientport = clientport2;
491 NetConn_CloseClientPorts();
493 if (cl_numsockets == 0)
494 NetConn_OpenClientPorts();
497 if (hostport != sv_netport.integer)
499 hostport = sv_netport.integer;
501 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
505 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
509 unsigned int sequence;
513 length = BigLong(((int *)data)[0]);
514 flags = length & ~NETFLAG_LENGTH_MASK;
515 length &= NETFLAG_LENGTH_MASK;
516 // control packets were already handled
517 if (!(flags & NETFLAG_CTL))
519 sequence = BigLong(((int *)data)[1]);
523 if (flags & NETFLAG_UNRELIABLE)
525 if (sequence >= conn->unreliableReceiveSequence)
527 if (sequence > conn->unreliableReceiveSequence)
529 count = sequence - conn->unreliableReceiveSequence;
530 droppedDatagrams += count;
531 Con_DPrintf("Dropped %u datagram(s)\n", count);
533 conn->unreliableReceiveSequence = sequence + 1;
534 conn->lastMessageTime = realtime;
535 conn->timeout = realtime + net_messagetimeout.value;
536 unreliableMessagesReceived++;
539 SZ_Clear(&net_message);
540 SZ_Write(&net_message, data, length);
546 Con_DPrint("Got a stale datagram\n");
549 else if (flags & NETFLAG_ACK)
551 if (sequence == (conn->sendSequence - 1))
553 if (sequence == conn->ackSequence)
556 if (conn->ackSequence != conn->sendSequence)
557 Con_DPrint("ack sequencing error\n");
558 conn->lastMessageTime = realtime;
559 conn->timeout = realtime + net_messagetimeout.value;
560 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
561 if (conn->sendMessageLength > 0)
563 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
564 conn->sendNext = true;
565 NetConn_SendMessageNext(conn);
569 conn->sendMessageLength = 0;
570 conn->canSend = true;
574 Con_DPrint("Duplicate ACK received\n");
577 Con_DPrint("Stale ACK received\n");
580 else if (flags & NETFLAG_DATA)
582 unsigned int temppacket[2];
583 temppacket[0] = BigLong(8 | NETFLAG_ACK);
584 temppacket[1] = BigLong(sequence);
585 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
586 if (sequence == conn->receiveSequence)
588 conn->lastMessageTime = realtime;
589 conn->timeout = realtime + net_messagetimeout.value;
590 conn->receiveSequence++;
591 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
592 conn->receiveMessageLength += length;
593 if (flags & NETFLAG_EOM)
595 reliableMessagesReceived++;
596 length = conn->receiveMessageLength;
597 conn->receiveMessageLength = 0;
600 SZ_Clear(&net_message);
601 SZ_Write(&net_message, conn->receiveMessage, length);
608 receivedDuplicateCount++;
616 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
618 cls.netcon = NetConn_Open(mysocket, peeraddress);
619 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
622 cls.connect_trying = false;
623 cls.demonum = -1; // not in the demo loop now
624 cls.state = ca_connected;
625 cls.signon = 0; // need all the signon messages before playing
630 int NetConn_IsLocalGame(void)
632 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
640 lhnetaddress_t peeraddress;
642 pingcache[HOSTCACHESIZE];
644 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
647 lhnetaddress_t svaddress;
649 char *string, addressstring2[128], cname[128], ipstring[32];
650 char stringbuf[16384];
652 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
654 // received a command string - strip off the packaging and put it
655 // into our string buffer with NULL termination
658 length = min(length, (int)sizeof(stringbuf) - 1);
659 memcpy(stringbuf, data, length);
660 stringbuf[length] = 0;
663 if (developer.integer)
665 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
666 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
667 Com_HexDumpToConsole(data, length);
670 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
672 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
673 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
674 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
677 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
679 NetConn_ConnectionEstablished(mysocket, peeraddress);
682 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
684 cls.connect_trying = false;
686 length = max(length - 7, (int)sizeof(m_return_reason) - 1);
687 memcpy(m_return_reason, string, length);
688 m_return_reason[length] = 0;
689 Con_Printf("%s\n", m_return_reason);
692 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
694 int i, j, c, n, users, maxusers;
695 char game[32], mod[32], map[32], name[128];
699 // hostcache only uses text addresses
700 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
701 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(game, s, sizeof (game));else game[0] = 0;
702 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(mod , s, sizeof (mod ));else mod[0] = 0;
703 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(map , s, sizeof (map ));else map[0] = 0;
704 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(name, s, sizeof (name));else name[0] = 0;
705 if ((s = SearchInfostring(string, "protocol" )) != NULL) c = atoi(s);else c = -1;
706 if ((s = SearchInfostring(string, "clients" )) != NULL) users = atoi(s);else users = 0;
707 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) maxusers = atoi(s);else maxusers = 0;
708 // search the cache for this server and update it
709 for (n = 0; n < hostCacheCount; n++)
711 if (!strcmp(cname, hostcache[n].cname))
713 if (hostcache[n].ping == 100000)
715 pingtime = (int)((realtime - hostcache[n].querytime) * 1000.0);
716 pingtime = bound(0, pingtime, 9999);
718 hostcache[n].ping = pingtime;
719 // build description strings for the things users care about
720 snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, c != NET_PROTOCOL_VERSION ? '*' : ' ', users, maxusers, name);
721 snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", cname, game, mod, map);
722 // if ping is especially high, display it as such
725 // orange numbers (lower block)
726 for (i = 0;i < 5;i++)
727 if (hostcache[n].line1[i] != ' ')
728 hostcache[n].line1[i] += 128;
730 else if (pingtime >= 200)
732 // yellow numbers (in upper block)
733 for (i = 0;i < 5;i++)
734 if (hostcache[n].line1[i] != ' ')
735 hostcache[n].line1[i] -= 30;
737 // if not in the slist menu we should print the server to console
738 if (m_state != m_slist)
739 Con_Printf("%s\n%s\n", hostcache[n].line1, hostcache[n].line2);
740 // and finally, re-sort the list
741 for (i = 0;i < hostCacheCount;i++)
743 for (j = i + 1;j < hostCacheCount;j++)
745 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
746 if (hostcache[i].ping > hostcache[j].ping)
748 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
749 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
750 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
759 if (!strncmp(string, "getserversResponse\\", 19) && hostCacheCount < HOSTCACHESIZE)
763 // Extract the IP addresses
767 if (m_state != m_slist)
768 Con_Print("received server list...\n");
769 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
771 snprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
772 if (developer.integer)
773 Con_Printf("Requesting info from server %s\n", ipstring);
774 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
775 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
778 // add to slist (hostCache)
779 // search the cache for this server
780 for (n = 0; n < hostCacheCount; n++)
781 if (!strcmp(ipstring, hostcache[n].cname))
783 // add it or update it
784 if (n == hostCacheCount)
786 // if cache is full replace highest ping server (the list is
787 // kept sorted so this is always the last, and if this server
788 // is good it will be sorted into an early part of the list)
789 if (hostCacheCount >= HOSTCACHESIZE)
790 n = hostCacheCount - 1;
797 memset(&hostcache[n], 0, sizeof(hostcache[n]));
798 // store the data the engine cares about (address and ping)
799 strlcpy (hostcache[n].cname, ipstring, sizeof (hostcache[n].cname));
800 hostcache[n].ping = 100000;
801 hostcache[n].querytime = realtime;
802 // build description strings for the things users care about
803 strlcpy (hostcache[n].line1, "?", sizeof (hostcache[n].line1));
804 strlcpy (hostcache[n].line2, ipstring, sizeof (hostcache[n].line2));
805 // if not in the slist menu we should print the server to console
806 if (m_state != m_slist)
807 Con_Printf("querying %s\n", ipstring);
808 // and finally, re-sort the list
809 for (i = 0;i < hostCacheCount;i++)
811 for (j = i + 1;j < hostCacheCount;j++)
813 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
814 if (hostcache[i].ping > hostcache[j].ping)
816 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
817 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
818 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
824 // move on to next address in packet
831 if (!strncmp(string, "ping", 4))
833 if (developer.integer)
834 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
835 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
838 if (!strncmp(string, "ack", 3))
841 // we may not have liked the packet, but it was a command packet, so
842 // we're done processing this packet now
845 // netquake control packets, supported for compatibility only
846 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
851 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
855 if (developer.integer)
856 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
857 if (cls.connect_trying)
859 lhnetaddress_t clientportaddress;
860 clientportaddress = *peeraddress;
863 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
866 LHNETADDRESS_SetPort(&clientportaddress, port);
868 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
872 if (developer.integer)
873 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
874 Con_Printf("%s\n", data);
875 strlcpy (m_return_reason, data, sizeof (m_return_reason));
878 case CCREP_SERVER_INFO:
879 if (developer.integer)
880 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
881 if (cls.state != ca_dedicated)
883 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
884 // string we just ignore it and keep the real address
886 // hostcache only uses text addresses
887 cname = UDP_AddrToString(readaddr);
888 // search the cache for this server
889 for (n = 0; n < hostCacheCount; n++)
890 if (!strcmp(cname, hostcache[n].cname))
893 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
896 memset(&hostcache[n], 0, sizeof(hostcache[n]));
897 strlcpy (hostcache[n].name, MSG_ReadString(), sizeof (hostcache[n].name));
898 strlcpy (hostcache[n].map, MSG_ReadString(), sizeof (hostcache[n].map));
899 hostcache[n].users = MSG_ReadByte();
900 hostcache[n].maxusers = MSG_ReadByte();
902 if (c != NET_PROTOCOL_VERSION)
904 strlcpy (hostcache[n].cname, hostcache[n].name, sizeof (hostcache[n].cname));
905 strcpy(hostcache[n].name, "*");
906 strlcat (hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name));
908 strlcpy (hostcache[n].cname, cname, sizeof (hostcache[n].cname));
912 case CCREP_PLAYER_INFO:
913 // we got a CCREP_PLAYER_INFO??
914 //if (developer.integer)
915 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
917 case CCREP_RULE_INFO:
918 // we got a CCREP_RULE_INFO??
919 //if (developer.integer)
920 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
926 // we may not have liked the packet, but it was a valid control
927 // packet, so we're done processing this packet now
931 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)
932 CL_ParseServerMessage();
936 void NetConn_ClientFrame(void)
939 lhnetaddress_t peeraddress;
941 NetConn_UpdateServerStuff();
942 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
944 if (cls.connect_remainingtries == 0)
946 cls.connect_trying = false;
947 if (m_state == m_slist)
948 strcpy (m_return_reason, "Connect: Failed");
950 Con_Print("Connect failed\n");
953 if (cls.connect_nextsendtime)
955 if (m_state == m_slist)
956 strcpy (m_return_reason, "Connect: Still trying");
958 Con_Print("Still trying...\n");
962 if (m_state == m_slist)
963 strcpy (m_return_reason, "Connect: Trying");
965 Con_Print("Trying...\n");
967 cls.connect_nextsendtime = realtime + 1;
968 cls.connect_remainingtries--;
969 // try challenge first (newer server)
970 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
971 // then try netquake as a fallback (old server, or netquake)
972 SZ_Clear(&net_message);
973 // save space for the header, filled in later
974 MSG_WriteLong(&net_message, 0);
975 MSG_WriteByte(&net_message, CCREQ_CONNECT);
976 MSG_WriteString(&net_message, "QUAKE");
977 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
978 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
979 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
980 SZ_Clear(&net_message);
982 for (i = 0;i < cl_numsockets;i++)
983 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
984 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
985 if (cls.netcon && realtime > cls.netcon->timeout)
987 Con_Print("Connection timed out\n");
989 Host_ShutdownServer (false);
991 for (conn = netconn_list;conn;conn = conn->next)
992 NetConn_ReSendMessage(conn);
995 #define MAX_CHALLENGES 128
998 lhnetaddress_t address;
1002 challenge[MAX_CHALLENGES];
1004 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1008 for (i = 0;i < bufferlength - 1;i++)
1012 c = rand () % (127 - 33) + 33;
1013 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1019 extern void SV_ConnectClient(int clientnum, netconn_t *netconnection);
1020 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1022 int i, n, ret, clientnum, responselength, best;
1026 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1030 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1032 // received a command string - strip off the packaging and put it
1033 // into our string buffer with NULL termination
1036 length = min(length, (int)sizeof(stringbuf) - 1);
1037 memcpy(stringbuf, data, length);
1038 stringbuf[length] = 0;
1041 if (developer.integer)
1043 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1044 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1045 Com_HexDumpToConsole(data, length);
1048 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1050 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1052 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1054 if (besttime > challenge[i].time)
1055 besttime = challenge[best = i].time;
1057 // if we did not find an exact match, choose the oldest and
1058 // update address and string
1059 if (i == MAX_CHALLENGES)
1062 challenge[i].address = *peeraddress;
1063 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1065 challenge[i].time = realtime;
1066 // send the challenge
1067 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1070 if (length > 8 && !memcmp(string, "connect\\", 8))
1074 if ((s = SearchInfostring(string, "challenge")))
1076 // validate the challenge
1077 for (i = 0;i < MAX_CHALLENGES;i++)
1078 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1080 if (i < MAX_CHALLENGES)
1082 // check engine protocol
1083 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1085 if (developer.integer)
1086 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1087 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1091 // see if this is a duplicate connection request
1092 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1093 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1095 if (clientnum < svs.maxclients)
1097 // duplicate connection request
1098 if (realtime - client->netconnection->connecttime < 2.0)
1100 // client is still trying to connect,
1101 // so we send a duplicate reply
1102 if (developer.integer)
1103 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1104 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1106 // only kick if old connection seems dead
1107 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1109 // kick off connection and await retry
1110 client->deadsocket = true;
1115 // this is a new client, find a slot
1116 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1117 if (!client->active)
1119 if (clientnum < svs.maxclients)
1121 // prepare the client struct
1122 if ((client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_clients_mempool)))
1124 if ((conn = NetConn_Open(mysocket, peeraddress)))
1126 // allocated connection
1127 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1128 if (developer.integer)
1129 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1130 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1131 // now set up the client
1132 SV_ConnectClient(clientnum, conn);
1133 NetConn_Heartbeat(1);
1136 EntityFrame4_FreeDatabase(client->entitydatabase4);
1142 if (developer.integer)
1143 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1144 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1152 if (length >= 7 && !memcmp(string, "getinfo", 7))
1154 const char *challenge = NULL;
1155 // If there was a challenge in the getinfo message
1156 if (length > 8 && string[7] == ' ')
1157 challenge = string + 8;
1158 for (i = 0, n = 0;i < svs.maxclients;i++)
1159 if (svs.clients[i].active)
1161 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1162 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1163 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1164 gamename, com_modname, svs.maxclients, n,
1165 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1166 // does it fit in the buffer?
1167 if (responselength < (int)sizeof(response))
1169 if (developer.integer)
1170 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1171 NetConn_WriteString(mysocket, response, peeraddress);
1176 if (!strncmp(string, "ping", 4))
1178 if (developer.integer)
1179 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1180 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1183 if (!strncmp(string, "ack", 3))
1186 // we may not have liked the packet, but it was a command packet, so
1187 // we're done processing this packet now
1190 // LordHavoc: disabled netquake control packet support in server
1194 // netquake control packets, supported for compatibility only
1195 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1200 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1204 //if (developer.integer)
1205 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1206 if (length >= (int)strlen("QUAKE") + 1 + 1)
1208 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1210 if (developer.integer)
1211 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1212 SZ_Clear(&net_message);
1213 // save space for the header, filled in later
1214 MSG_WriteLong(&net_message, 0);
1215 MSG_WriteByte(&net_message, CCREP_REJECT);
1216 MSG_WriteString(&net_message, "Incompatible version.\n");
1217 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1218 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1219 SZ_Clear(&net_message);
1223 // see if this is a duplicate connection request
1224 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1225 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1227 if (clientnum < svs.maxclients)
1229 // duplicate connection request
1230 if (realtime - client->netconnection->connecttime < 2.0)
1232 // client is still trying to connect,
1233 // so we send a duplicate reply
1234 if (developer.integer)
1235 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1236 SZ_Clear(&net_message);
1237 // save space for the header, filled in later
1238 MSG_WriteLong(&net_message, 0);
1239 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1240 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1241 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1242 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1243 SZ_Clear(&net_message);
1245 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1247 // the old client hasn't sent us anything
1248 // in quite a while, so kick off and let
1249 // the retry take care of it...
1250 client->deadsocket = true;
1255 // this is a new client, find a slot
1256 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1257 if (!client->active)
1259 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1261 // connect to the client
1262 // everything is allocated, just fill in the details
1263 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1264 if (developer.integer)
1265 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1266 // send back the info about the server connection
1267 SZ_Clear(&net_message);
1268 // save space for the header, filled in later
1269 MSG_WriteLong(&net_message, 0);
1270 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1271 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1272 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1273 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1274 SZ_Clear(&net_message);
1275 // now set up the client struct
1276 SV_ConnectClient(clientnum, conn);
1277 NetConn_Heartbeat(1);
1281 //if (developer.integer)
1282 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1283 // no room; try to let player know
1284 SZ_Clear(&net_message);
1285 // save space for the header, filled in later
1286 MSG_WriteLong(&net_message, 0);
1287 MSG_WriteByte(&net_message, CCREP_REJECT);
1288 MSG_WriteString(&net_message, "Server is full.\n");
1289 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1290 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1291 SZ_Clear(&net_message);
1298 case CCREQ_SERVER_INFO:
1299 if (developer.integer)
1300 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1301 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1303 if (developer.integer)
1304 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1305 SZ_Clear(&net_message);
1306 // save space for the header, filled in later
1307 MSG_WriteLong(&net_message, 0);
1308 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1309 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1310 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1311 MSG_WriteString(&net_message, hostname.string);
1312 MSG_WriteString(&net_message, sv.name);
1313 MSG_WriteByte(&net_message, net_activeconnections);
1314 MSG_WriteByte(&net_message, svs.maxclients);
1315 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1316 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1317 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1318 SZ_Clear(&net_message);
1321 case CCREQ_PLAYER_INFO:
1322 if (developer.integer)
1323 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1326 int playerNumber, activeNumber, clientNumber;
1329 playerNumber = MSG_ReadByte();
1331 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1332 if (client->active && ++activeNumber == playerNumber)
1334 if (clientNumber != svs.maxclients)
1336 SZ_Clear(&net_message);
1337 // save space for the header, filled in later
1338 MSG_WriteLong(&net_message, 0);
1339 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1340 MSG_WriteByte(&net_message, playerNumber);
1341 MSG_WriteString(&net_message, client->name);
1342 MSG_WriteLong(&net_message, client->colors);
1343 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1344 MSG_WriteLong(&net_message, (int)(realtime - client->netconnection->connecttime));
1345 MSG_WriteString(&net_message, client->netconnection->address);
1346 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1347 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1348 SZ_Clear(&net_message);
1352 case CCREQ_RULE_INFO:
1353 if (developer.integer)
1354 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1360 // find the search start location
1361 prevCvarName = MSG_ReadString();
1362 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1364 // send the response
1365 SZ_Clear(&net_message);
1366 // save space for the header, filled in later
1367 MSG_WriteLong(&net_message, 0);
1368 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1371 MSG_WriteString(&net_message, var->name);
1372 MSG_WriteString(&net_message, var->string);
1374 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1375 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1376 SZ_Clear(&net_message);
1383 // we may not have liked the packet, but it was a valid control
1384 // packet, so we're done processing this packet now
1389 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1391 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1393 sv_player = host_client->edict;
1394 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1395 SV_ReadClientMessage();
1403 void NetConn_ServerFrame(void)
1406 lhnetaddress_t peeraddress;
1408 NetConn_UpdateServerStuff();
1409 for (i = 0;i < sv_numsockets;i++)
1410 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1411 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1412 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1414 // never timeout loopback connections
1415 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(host_client->netconnection->mysocket)) != LHNETADDRESSTYPE_LOOP)
1417 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1418 sv_player = host_client->edict;
1419 SV_DropClient(false);
1422 for (conn = netconn_list;conn;conn = conn->next)
1423 NetConn_ReSendMessage(conn);
1426 void NetConn_QueryMasters(void)
1430 lhnetaddress_t masteraddress;
1433 if (hostCacheCount >= HOSTCACHESIZE)
1436 for (i = 0;i < cl_numsockets;i++)
1443 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1445 SZ_Clear(&net_message);
1446 // save space for the header, filled in later
1447 MSG_WriteLong(&net_message, 0);
1448 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1449 MSG_WriteString(&net_message, "QUAKE");
1450 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1451 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1452 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1453 SZ_Clear(&net_message);
1457 // build the getservers
1458 snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1461 for (masternum = 0;sv_masters[masternum].name;masternum++)
1463 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1466 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1471 if (!masterquerycount)
1473 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1474 strcpy(m_return_reason, "No network");
1478 void NetConn_Heartbeat(int priority)
1480 lhnetaddress_t masteraddress;
1482 lhnetsocket_t *mysocket;
1484 // if it's a state change (client connected), limit next heartbeat to no
1485 // more than 30 sec in the future
1486 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1487 nextheartbeattime = realtime + 30.0;
1489 // limit heartbeatperiod to 30 to 270 second range,
1490 // lower limit is to avoid abusing master servers with excess traffic,
1491 // upper limit is to avoid timing out on the master server (which uses
1493 if (sv_heartbeatperiod.value < 30)
1494 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1495 if (sv_heartbeatperiod.value > 270)
1496 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1498 // make advertising optional and don't advertise singleplayer games, and
1499 // only send a heartbeat as often as the admin wants
1500 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1502 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1503 for (masternum = 0;sv_masters[masternum].name;masternum++)
1504 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1505 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1509 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1512 qbyte sent[MAX_SCOREBOARD];
1514 memset(sent, 0, sizeof(sent));
1516 // simultaneously wait for the first CanSendMessage and send the message,
1517 // then wait for a second CanSendMessage (verifying it was received), or
1518 // the client drops and is no longer counted
1519 // the loop aborts when either it runs out of clients to send to, or a
1521 blocktime += Sys_DoubleTime();
1525 NetConn_ClientFrame();
1526 NetConn_ServerFrame();
1527 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1529 if (host_client->netconnection)
1531 if (NetConn_CanSendMessage(host_client->netconnection))
1534 NetConn_SendReliableMessage(host_client->netconnection, data);
1537 if (!NetConn_CanSendMessage(host_client->netconnection))
1542 while (count && Sys_DoubleTime() < blocktime);
1546 static void Net_Heartbeat_f(void)
1549 NetConn_Heartbeat(2);
1551 Con_Print("No server running, can not heartbeat to master server.\n");
1554 void PrintStats(netconn_t *conn)
1556 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1559 void Net_Stats_f(void)
1562 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1563 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1564 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1565 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1566 Con_Printf("packetsSent = %i\n", packetsSent);
1567 Con_Printf("packetsReSent = %i\n", packetsReSent);
1568 Con_Printf("packetsReceived = %i\n", packetsReceived);
1569 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1570 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1571 Con_Print("connections =\n");
1572 for (conn = netconn_list;conn;conn = conn->next)
1576 void Net_Slist_f(void)
1578 masterquerytime = realtime;
1579 masterquerycount = 0;
1580 masterreplycount = 0;
1581 serverquerycount = 0;
1582 serverreplycount = 0;
1584 memset(&pingcache, 0, sizeof(pingcache));
1585 if (m_state != m_slist)
1586 Con_Print("Sending requests to master servers\n");
1587 NetConn_QueryMasters();
1588 if (m_state != m_slist)
1589 Con_Print("Listening for replies...\n");
1592 void NetConn_Init(void)
1595 lhnetaddress_t tempaddress;
1596 netconn_mempool = Mem_AllocPool("Networking");
1597 Cmd_AddCommand("net_stats", Net_Stats_f);
1598 Cmd_AddCommand("net_slist", Net_Slist_f);
1599 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1600 Cvar_RegisterVariable(&net_messagetimeout);
1601 Cvar_RegisterVariable(&net_messagerejointimeout);
1602 Cvar_RegisterVariable(&net_connecttimeout);
1603 Cvar_RegisterVariable(&cl_netlocalping_min);
1604 Cvar_RegisterVariable(&cl_netlocalping_max);
1605 Cvar_RegisterVariable(&cl_netpacketloss_receive);
1606 Cvar_RegisterVariable(&cl_netpacketloss_send);
1607 Cvar_RegisterVariable(&sv_netpacketloss_receive);
1608 Cvar_RegisterVariable(&sv_netpacketloss_send);
1609 Cvar_RegisterVariable(&hostname);
1610 Cvar_RegisterVariable(&developer_networking);
1611 Cvar_RegisterVariable(&cl_netport);
1612 Cvar_RegisterVariable(&sv_netport);
1613 Cvar_RegisterVariable(&net_address);
1614 //Cvar_RegisterVariable(&net_address_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 net_address to \"%s\"\n");
1624 Cvar_SetQuick(&net_address, com_argv[i + 1]);
1627 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1629 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1631 i = atoi(com_argv[i + 1]);
1632 if (i >= 0 && i < 65536)
1634 Con_Printf("-port option used, setting port cvar to %i\n", i);
1635 Cvar_SetValueQuick(&sv_netport, i);
1638 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1642 memset(&pingcache, 0, sizeof(pingcache));
1643 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1647 void NetConn_Shutdown(void)
1649 NetConn_CloseClientPorts();
1650 NetConn_CloseServerPorts();