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 // FIXME: resolve DNS on masters whenever their value changes and cache it (to avoid major delays in active servers when they heartbeat)
32 static cvar_t sv_masters [] =
34 {CVAR_SAVE, "sv_master1", ""},
35 {CVAR_SAVE, "sv_master2", ""},
36 {CVAR_SAVE, "sv_master3", ""},
37 {CVAR_SAVE, "sv_master4", ""},
38 {0, "sv_masterextra1", "69.59.212.88"}, // ghdigital.com
39 {0, "sv_masterextra2", "66.169.205.13"}, // dpmaster.deathmask.net
43 static double nextheartbeattime = 0;
45 sizebuf_t net_message;
47 cvar_t net_messagetimeout = {0, "net_messagetimeout","300"};
48 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10"};
49 cvar_t net_connecttimeout = {0, "net_connecttimeout","10"};
50 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED"};
51 cvar_t developer_networking = {0, "developer_networking", "0"};
53 cvar_t cl_netlocalping = {0, "cl_netlocalping","0"};
54 static cvar_t cl_netpacketloss = {0, "cl_netpacketloss","0"};
57 /* statistic counters */
58 static int packetsSent = 0;
59 static int packetsReSent = 0;
60 static int packetsReceived = 0;
61 static int receivedDuplicateCount = 0;
62 static int droppedDatagrams = 0;
64 static int unreliableMessagesSent = 0;
65 static int unreliableMessagesReceived = 0;
66 static int reliableMessagesSent = 0;
67 static int reliableMessagesReceived = 0;
69 double masterquerytime = -1000;
70 int masterquerycount = 0;
71 int masterreplycount = 0;
72 int serverquerycount = 0;
73 int serverreplycount = 0;
75 int hostCacheCount = 0;
76 hostcache_t hostcache[HOSTCACHESIZE];
78 static qbyte sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
79 static qbyte readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
82 lhnetsocket_t *cl_sockets[16];
84 lhnetsocket_t *sv_sockets[16];
86 netconn_t *netconn_list = NULL;
87 mempool_t *netconn_mempool = NULL;
89 cvar_t cl_netport = {0, "cl_port", "0"};
90 cvar_t sv_netport = {0, "port", "26000"};
91 cvar_t net_address = {0, "net_address", "0.0.0.0"};
92 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]"};
94 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
96 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
98 if (cl_netpacketloss.integer)
99 for (i = 0;i < cl_numsockets;i++)
100 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
102 if (developer_networking.integer && length != 0)
104 char addressstring[128], addressstring2[128];
105 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
108 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
109 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
110 Com_HexDumpToConsole(data, length);
113 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
118 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
122 if (cl_netpacketloss.integer)
123 for (i = 0;i < cl_numsockets;i++)
124 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
126 ret = LHNET_Write(mysocket, data, length, peeraddress);
127 if (developer_networking.integer)
129 char addressstring[128], addressstring2[128];
130 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
131 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
132 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
133 Com_HexDumpToConsole(data, length);
138 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
140 // note this does not include the trailing NULL because we add that in the parser
141 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
144 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
146 unsigned int packetLen;
147 unsigned int dataLen;
149 unsigned int *header;
152 if (data->cursize == 0)
153 Sys_Error("Datagram_SendMessage: zero length message\n");
155 if (data->cursize > (int)sizeof(conn->sendMessage))
156 Sys_Error("Datagram_SendMessage: message too big (%u > %u)\n", data->cursize, sizeof(conn->sendMessage));
158 if (conn->canSend == false)
159 Sys_Error("SendMessage: called with canSend == false\n");
162 memcpy(conn->sendMessage, data->data, data->cursize);
163 conn->sendMessageLength = data->cursize;
165 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
167 dataLen = conn->sendMessageLength;
172 dataLen = MAX_PACKETFRAGMENT;
176 packetLen = NET_HEADERSIZE + dataLen;
178 header = (void *)sendbuffer;
179 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
180 header[1] = BigLong(conn->sendSequence);
181 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
183 conn->sendSequence++;
184 conn->canSend = false;
186 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
189 conn->lastSendTime = realtime;
191 reliableMessagesSent++;
195 static void NetConn_SendMessageNext(netconn_t *conn)
197 unsigned int packetLen;
198 unsigned int dataLen;
200 unsigned int *header;
202 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
204 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
206 dataLen = conn->sendMessageLength;
211 dataLen = MAX_PACKETFRAGMENT;
215 packetLen = NET_HEADERSIZE + dataLen;
217 header = (void *)sendbuffer;
218 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
219 header[1] = BigLong(conn->sendSequence);
220 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
222 conn->sendSequence++;
223 conn->sendNext = false;
225 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
228 conn->lastSendTime = realtime;
233 static void NetConn_ReSendMessage(netconn_t *conn)
235 unsigned int packetLen;
236 unsigned int dataLen;
238 unsigned int *header;
240 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
242 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
244 dataLen = conn->sendMessageLength;
249 dataLen = MAX_PACKETFRAGMENT;
253 packetLen = NET_HEADERSIZE + dataLen;
255 header = (void *)sendbuffer;
256 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
257 header[1] = BigLong(conn->sendSequence - 1);
258 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
260 conn->sendNext = false;
262 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
265 conn->lastSendTime = realtime;
270 qboolean NetConn_CanSendMessage(netconn_t *conn)
272 return conn->canSend;
275 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
280 packetLen = NET_HEADERSIZE + data->cursize;
283 if (data->cursize == 0)
284 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
286 if (packetLen > (int)sizeof(sendbuffer))
287 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
290 header = (void *)sendbuffer;
291 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
292 header[1] = BigLong(conn->unreliableSendSequence);
293 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
295 conn->unreliableSendSequence++;
297 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
301 unreliableMessagesSent++;
305 void NetConn_CloseClientPorts(void)
307 for (;cl_numsockets > 0;cl_numsockets--)
308 if (cl_sockets[cl_numsockets - 1])
309 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
312 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
314 lhnetaddress_t address;
316 char addressstring2[1024];
317 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
319 if ((s = LHNET_OpenSocket_Connectionless(&address)))
321 cl_sockets[cl_numsockets++] = s;
322 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
323 Con_Printf("Client opened a socket on address %s\n", addressstring2);
327 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
328 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
332 Con_Printf("Client unable to parse address %s\n", addressstring);
335 void NetConn_OpenClientPorts(void)
338 NetConn_CloseClientPorts();
339 port = bound(0, cl_netport.integer, 65535);
340 if (cl_netport.integer != port)
341 Cvar_SetValueQuick(&cl_netport, port);
342 Con_Printf("Client using port %i\n", port);
343 NetConn_OpenClientPort("local:2", 0);
344 NetConn_OpenClientPort(net_address.string, port);
345 //NetConn_OpenClientPort(net_address_ipv6.string, port);
348 void NetConn_CloseServerPorts(void)
350 for (;sv_numsockets > 0;sv_numsockets--)
351 if (sv_sockets[sv_numsockets - 1])
352 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
355 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
357 lhnetaddress_t address;
359 char addressstring2[1024];
360 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
362 if ((s = LHNET_OpenSocket_Connectionless(&address)))
364 sv_sockets[sv_numsockets++] = s;
365 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
366 Con_Printf("Server listening on address %s\n", addressstring2);
370 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
371 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
375 Con_Printf("Server unable to parse address %s\n", addressstring);
378 void NetConn_OpenServerPorts(int opennetports)
381 NetConn_CloseServerPorts();
382 port = bound(0, sv_netport.integer, 65535);
385 Con_Printf("Server using port %i\n", port);
386 if (sv_netport.integer != port)
387 Cvar_SetValueQuick(&sv_netport, port);
388 if (cls.state != ca_dedicated)
389 NetConn_OpenServerPort("local:1", 0);
392 NetConn_OpenServerPort(net_address.string, port);
393 //NetConn_OpenServerPort(net_address_ipv6.string, port);
395 if (sv_numsockets == 0)
396 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
399 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
401 int i, a = LHNETADDRESS_GetAddressType(address);
402 for (i = 0;i < cl_numsockets;i++)
403 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
404 return cl_sockets[i];
408 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
410 int i, a = LHNETADDRESS_GetAddressType(address);
411 for (i = 0;i < sv_numsockets;i++)
412 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
413 return sv_sockets[i];
417 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
420 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
421 conn->mysocket = mysocket;
422 conn->peeraddress = *peeraddress;
423 // updated by receiving "rate" command from client
424 conn->rate = NET_MINRATE;
425 // no limits for local player
426 if (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP)
427 conn->rate = 1000000000;
428 conn->canSend = true;
429 conn->connecttime = realtime;
430 conn->lastMessageTime = realtime;
431 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
432 // reduce effectiveness of connection request floods
433 conn->timeout = realtime + net_connecttimeout.value;
434 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
435 conn->next = netconn_list;
440 void NetConn_Close(netconn_t *conn)
443 // remove connection from list
444 if (conn == netconn_list)
445 netconn_list = conn->next;
448 for (c = netconn_list;c;c = c->next)
452 c->next = conn->next;
456 // not found in list, we'll avoid crashing here...
464 static int clientport = -1;
465 static int clientport2 = -1;
466 static int hostport = -1;
467 static void NetConn_UpdateServerStuff(void)
469 if (cls.state != ca_dedicated)
471 if (clientport2 != cl_netport.integer)
473 clientport2 = cl_netport.integer;
474 if (cls.state == ca_connected)
475 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
477 if (cls.state == ca_disconnected && clientport != clientport2)
479 clientport = clientport2;
480 NetConn_CloseClientPorts();
482 if (cl_numsockets == 0)
483 NetConn_OpenClientPorts();
486 if (hostport != sv_netport.integer)
488 hostport = sv_netport.integer;
490 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
494 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
498 unsigned int sequence;
502 length = BigLong(((int *)data)[0]);
503 flags = length & ~NETFLAG_LENGTH_MASK;
504 length &= NETFLAG_LENGTH_MASK;
505 // control packets were already handled
506 if (!(flags & NETFLAG_CTL))
508 sequence = BigLong(((int *)data)[1]);
512 if (flags & NETFLAG_UNRELIABLE)
514 if (sequence >= conn->unreliableReceiveSequence)
516 if (sequence > conn->unreliableReceiveSequence)
518 count = sequence - conn->unreliableReceiveSequence;
519 droppedDatagrams += count;
520 Con_DPrintf("Dropped %u datagram(s)\n", count);
522 conn->unreliableReceiveSequence = sequence + 1;
523 conn->lastMessageTime = realtime;
524 conn->timeout = realtime + net_messagetimeout.value;
525 unreliableMessagesReceived++;
528 SZ_Clear(&net_message);
529 SZ_Write(&net_message, data, length);
535 Con_DPrint("Got a stale datagram\n");
538 else if (flags & NETFLAG_ACK)
540 if (sequence == (conn->sendSequence - 1))
542 if (sequence == conn->ackSequence)
545 if (conn->ackSequence != conn->sendSequence)
546 Con_DPrint("ack sequencing error\n");
547 conn->lastMessageTime = realtime;
548 conn->timeout = realtime + net_messagetimeout.value;
549 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
550 if (conn->sendMessageLength > 0)
552 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
553 conn->sendNext = true;
554 NetConn_SendMessageNext(conn);
558 conn->sendMessageLength = 0;
559 conn->canSend = true;
563 Con_DPrint("Duplicate ACK received\n");
566 Con_DPrint("Stale ACK received\n");
569 else if (flags & NETFLAG_DATA)
571 unsigned int temppacket[2];
572 temppacket[0] = BigLong(8 | NETFLAG_ACK);
573 temppacket[1] = BigLong(sequence);
574 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
575 if (sequence == conn->receiveSequence)
577 conn->lastMessageTime = realtime;
578 conn->timeout = realtime + net_messagetimeout.value;
579 conn->receiveSequence++;
580 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
581 conn->receiveMessageLength += length;
582 if (flags & NETFLAG_EOM)
584 reliableMessagesReceived++;
585 length = conn->receiveMessageLength;
586 conn->receiveMessageLength = 0;
589 SZ_Clear(&net_message);
590 SZ_Write(&net_message, conn->receiveMessage, length);
597 receivedDuplicateCount++;
605 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
607 cls.connect_trying = false;
608 M_Update_Return_Reason("");
609 // the connection request succeeded, stop current connection and set up a new connection
611 cls.netcon = NetConn_Open(mysocket, peeraddress);
612 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
615 cls.demonum = -1; // not in the demo loop now
616 cls.state = ca_connected;
617 cls.signon = 0; // need all the signon messages before playing
619 SCR_BeginLoadingPlaque();
622 int NetConn_IsLocalGame(void)
624 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
632 lhnetaddress_t peeraddress;
634 pingcache[HOSTCACHESIZE];
636 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
639 lhnetaddress_t svaddress;
641 char *string, addressstring2[128], cname[128], ipstring[32];
642 char stringbuf[16384];
644 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
646 // received a command string - strip off the packaging and put it
647 // into our string buffer with NULL termination
650 length = min(length, (int)sizeof(stringbuf) - 1);
651 memcpy(stringbuf, data, length);
652 stringbuf[length] = 0;
655 if (developer.integer)
657 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
658 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
659 Com_HexDumpToConsole(data, length);
662 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
664 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
665 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
666 M_Update_Return_Reason("Got challenge response");
667 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
670 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
672 M_Update_Return_Reason("Accepted");
673 NetConn_ConnectionEstablished(mysocket, peeraddress);
676 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
678 char rejectreason[32];
679 cls.connect_trying = false;
681 length = max(length - 7, (int)sizeof(rejectreason) - 1);
682 memcpy(rejectreason, string, length);
683 rejectreason[length] = 0;
684 M_Update_Return_Reason(rejectreason);
687 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
689 int i, j, c, n, users, maxusers;
690 char game[32], mod[32], map[32], name[128];
694 // hostcache only uses text addresses
695 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
696 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(game, s, sizeof (game));else game[0] = 0;
697 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(mod , s, sizeof (mod ));else mod[0] = 0;
698 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(map , s, sizeof (map ));else map[0] = 0;
699 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(name, s, sizeof (name));else name[0] = 0;
700 if ((s = SearchInfostring(string, "protocol" )) != NULL) c = atoi(s);else c = -1;
701 if ((s = SearchInfostring(string, "clients" )) != NULL) users = atoi(s);else users = 0;
702 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) maxusers = atoi(s);else maxusers = 0;
703 // search the cache for this server and update it
704 for (n = 0; n < hostCacheCount; n++)
706 if (!strcmp(cname, hostcache[n].cname))
708 if (hostcache[n].ping == 100000)
710 pingtime = (int)((realtime - hostcache[n].querytime) * 1000.0);
711 pingtime = bound(0, pingtime, 9999);
713 hostcache[n].ping = pingtime;
714 // build description strings for the things users care about
715 snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, c != NET_PROTOCOL_VERSION ? '*' : ' ', users, maxusers, name);
716 snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", cname, game, mod, map);
717 // if ping is especially high, display it as such
720 // orange numbers (lower block)
721 for (i = 0;i < 5;i++)
722 if (hostcache[n].line1[i] != ' ')
723 hostcache[n].line1[i] += 128;
725 else if (pingtime >= 200)
727 // yellow numbers (in upper block)
728 for (i = 0;i < 5;i++)
729 if (hostcache[n].line1[i] != ' ')
730 hostcache[n].line1[i] -= 30;
732 // if not in the slist menu we should print the server to console
733 if (m_state != m_slist)
734 Con_Printf("%s\n%s\n", hostcache[n].line1, hostcache[n].line2);
735 // and finally, re-sort the list
736 for (i = 0;i < hostCacheCount;i++)
738 for (j = i + 1;j < hostCacheCount;j++)
740 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
741 if (hostcache[i].ping > hostcache[j].ping)
743 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
744 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
745 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
754 if (!strncmp(string, "getserversResponse\\", 19) && hostCacheCount < HOSTCACHESIZE)
758 // Extract the IP addresses
762 if (m_state != m_slist)
763 Con_Print("received server list...\n");
764 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
766 snprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
767 if (developer.integer)
768 Con_Printf("Requesting info from server %s\n", ipstring);
769 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
770 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
773 // add to slist (hostCache)
774 // search the cache for this server
775 for (n = 0; n < hostCacheCount; n++)
776 if (!strcmp(ipstring, hostcache[n].cname))
778 // add it or update it
779 if (n == hostCacheCount)
781 // if cache is full replace highest ping server (the list is
782 // kept sorted so this is always the last, and if this server
783 // is good it will be sorted into an early part of the list)
784 if (hostCacheCount >= HOSTCACHESIZE)
785 n = hostCacheCount - 1;
792 memset(&hostcache[n], 0, sizeof(hostcache[n]));
793 // store the data the engine cares about (address and ping)
794 strlcpy (hostcache[n].cname, ipstring, sizeof (hostcache[n].cname));
795 hostcache[n].ping = 100000;
796 hostcache[n].querytime = realtime;
797 // build description strings for the things users care about
798 strlcpy (hostcache[n].line1, "?", sizeof (hostcache[n].line1));
799 strlcpy (hostcache[n].line2, ipstring, sizeof (hostcache[n].line2));
800 // if not in the slist menu we should print the server to console
801 if (m_state != m_slist)
802 Con_Printf("querying %s\n", ipstring);
803 // and finally, re-sort the list
804 for (i = 0;i < hostCacheCount;i++)
806 for (j = i + 1;j < hostCacheCount;j++)
808 //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
809 if (hostcache[i].ping > hostcache[j].ping)
811 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
812 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
813 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
819 // move on to next address in packet
826 if (!strncmp(string, "ping", 4))
828 if (developer.integer)
829 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
830 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
833 if (!strncmp(string, "ack", 3))
836 // we may not have liked the packet, but it was a command packet, so
837 // we're done processing this packet now
840 // netquake control packets, supported for compatibility only
841 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
846 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
850 if (developer.integer)
851 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
852 if (cls.connect_trying)
854 lhnetaddress_t clientportaddress;
855 clientportaddress = *peeraddress;
858 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
861 LHNETADDRESS_SetPort(&clientportaddress, port);
863 M_Update_Return_Reason("Accepted");
864 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
868 if (developer.integer)
869 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
870 cls.connect_trying = false;
871 M_Update_Return_Reason(data);
874 case CCREP_SERVER_INFO:
875 if (developer.integer)
876 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
877 if (cls.state != ca_dedicated)
879 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
880 // string we just ignore it and keep the real address
882 // hostcache only uses text addresses
883 cname = UDP_AddrToString(readaddr);
884 // search the cache for this server
885 for (n = 0; n < hostCacheCount; n++)
886 if (!strcmp(cname, hostcache[n].cname))
889 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
892 memset(&hostcache[n], 0, sizeof(hostcache[n]));
893 strlcpy (hostcache[n].name, MSG_ReadString(), sizeof (hostcache[n].name));
894 strlcpy (hostcache[n].map, MSG_ReadString(), sizeof (hostcache[n].map));
895 hostcache[n].users = MSG_ReadByte();
896 hostcache[n].maxusers = MSG_ReadByte();
898 if (c != NET_PROTOCOL_VERSION)
900 strlcpy (hostcache[n].cname, hostcache[n].name, sizeof (hostcache[n].cname));
901 strcpy(hostcache[n].name, "*");
902 strlcat (hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name));
904 strlcpy (hostcache[n].cname, cname, sizeof (hostcache[n].cname));
908 case CCREP_PLAYER_INFO:
909 // we got a CCREP_PLAYER_INFO??
910 //if (developer.integer)
911 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
913 case CCREP_RULE_INFO:
914 // we got a CCREP_RULE_INFO??
915 //if (developer.integer)
916 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
922 // we may not have liked the packet, but it was a valid control
923 // packet, so we're done processing this packet now
927 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)
928 CL_ParseServerMessage();
932 void NetConn_ClientFrame(void)
935 lhnetaddress_t peeraddress;
937 NetConn_UpdateServerStuff();
938 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
940 if (cls.connect_remainingtries == 0)
942 cls.connect_trying = false;
943 M_Update_Return_Reason("Connect: Failed");
946 cls.connect_nextsendtime = realtime + 1;
947 cls.connect_remainingtries--;
948 // try challenge first (newer server)
949 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
950 // then try netquake as a fallback (old server, or netquake)
951 SZ_Clear(&net_message);
952 // save space for the header, filled in later
953 MSG_WriteLong(&net_message, 0);
954 MSG_WriteByte(&net_message, CCREQ_CONNECT);
955 MSG_WriteString(&net_message, "QUAKE");
956 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
957 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
958 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
959 SZ_Clear(&net_message);
961 for (i = 0;i < cl_numsockets;i++)
962 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
963 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
964 if (cls.netcon && realtime > cls.netcon->timeout)
966 Con_Print("Connection timed out\n");
968 Host_ShutdownServer (false);
970 for (conn = netconn_list;conn;conn = conn->next)
971 NetConn_ReSendMessage(conn);
974 #define MAX_CHALLENGES 128
977 lhnetaddress_t address;
981 challenge[MAX_CHALLENGES];
983 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
987 for (i = 0;i < bufferlength - 1;i++)
991 c = rand () % (127 - 33) + 33;
992 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
998 extern void SV_ConnectClient(int clientnum, netconn_t *netconnection);
999 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1001 int i, n, ret, clientnum, responselength, best;
1005 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1009 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1011 // received a command string - strip off the packaging and put it
1012 // into our string buffer with NULL termination
1015 length = min(length, (int)sizeof(stringbuf) - 1);
1016 memcpy(stringbuf, data, length);
1017 stringbuf[length] = 0;
1020 if (developer.integer)
1022 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1023 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1024 Com_HexDumpToConsole(data, length);
1027 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1029 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1031 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1033 if (besttime > challenge[i].time)
1034 besttime = challenge[best = i].time;
1036 // if we did not find an exact match, choose the oldest and
1037 // update address and string
1038 if (i == MAX_CHALLENGES)
1041 challenge[i].address = *peeraddress;
1042 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1044 challenge[i].time = realtime;
1045 // send the challenge
1046 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1049 if (length > 8 && !memcmp(string, "connect\\", 8))
1053 if ((s = SearchInfostring(string, "challenge")))
1055 // validate the challenge
1056 for (i = 0;i < MAX_CHALLENGES;i++)
1057 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1059 if (i < MAX_CHALLENGES)
1061 // check engine protocol
1062 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1064 if (developer.integer)
1065 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1066 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1070 // see if this is a duplicate connection request
1071 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1072 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1074 if (clientnum < svs.maxclients)
1076 // duplicate connection request
1077 if (realtime - client->netconnection->connecttime < 2.0)
1079 // client is still trying to connect,
1080 // so we send a duplicate reply
1081 if (developer.integer)
1082 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1083 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1085 // only kick if old connection seems dead
1086 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1088 // kick off connection and await retry
1089 client->deadsocket = true;
1094 // this is a new client, find a slot
1095 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1096 if (!client->active)
1098 if (clientnum < svs.maxclients)
1100 // prepare the client struct
1101 if ((conn = NetConn_Open(mysocket, peeraddress)))
1103 // allocated connection
1104 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1105 if (developer.integer)
1106 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1107 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1108 // now set up the client
1109 SV_ConnectClient(clientnum, conn);
1110 NetConn_Heartbeat(1);
1116 if (developer.integer)
1117 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1118 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1126 if (length >= 7 && !memcmp(string, "getinfo", 7))
1128 const char *challenge = NULL;
1129 // If there was a challenge in the getinfo message
1130 if (length > 8 && string[7] == ' ')
1131 challenge = string + 8;
1132 for (i = 0, n = 0;i < svs.maxclients;i++)
1133 if (svs.clients[i].active)
1135 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1136 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1137 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1138 gamename, com_modname, svs.maxclients, n,
1139 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1140 // does it fit in the buffer?
1141 if (responselength < (int)sizeof(response))
1143 if (developer.integer)
1144 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1145 NetConn_WriteString(mysocket, response, peeraddress);
1150 if (!strncmp(string, "ping", 4))
1152 if (developer.integer)
1153 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1154 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1157 if (!strncmp(string, "ack", 3))
1160 // we may not have liked the packet, but it was a command packet, so
1161 // we're done processing this packet now
1164 // LordHavoc: disabled netquake control packet support in server
1168 // netquake control packets, supported for compatibility only
1169 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1174 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1178 //if (developer.integer)
1179 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1180 if (length >= (int)strlen("QUAKE") + 1 + 1)
1182 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1184 if (developer.integer)
1185 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1186 SZ_Clear(&net_message);
1187 // save space for the header, filled in later
1188 MSG_WriteLong(&net_message, 0);
1189 MSG_WriteByte(&net_message, CCREP_REJECT);
1190 MSG_WriteString(&net_message, "Incompatible version.\n");
1191 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1192 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1193 SZ_Clear(&net_message);
1197 // see if this is a duplicate connection request
1198 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1199 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1201 if (clientnum < svs.maxclients)
1203 // duplicate connection request
1204 if (realtime - client->netconnection->connecttime < 2.0)
1206 // client is still trying to connect,
1207 // so we send a duplicate reply
1208 if (developer.integer)
1209 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1210 SZ_Clear(&net_message);
1211 // save space for the header, filled in later
1212 MSG_WriteLong(&net_message, 0);
1213 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1214 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1215 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1216 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1217 SZ_Clear(&net_message);
1219 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1221 // the old client hasn't sent us anything
1222 // in quite a while, so kick off and let
1223 // the retry take care of it...
1224 client->deadsocket = true;
1229 // this is a new client, find a slot
1230 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1231 if (!client->active)
1233 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1235 // connect to the client
1236 // everything is allocated, just fill in the details
1237 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1238 if (developer.integer)
1239 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1240 // send back the info about the server connection
1241 SZ_Clear(&net_message);
1242 // save space for the header, filled in later
1243 MSG_WriteLong(&net_message, 0);
1244 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1245 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1246 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1247 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1248 SZ_Clear(&net_message);
1249 // now set up the client struct
1250 SV_ConnectClient(clientnum, conn);
1251 NetConn_Heartbeat(1);
1255 //if (developer.integer)
1256 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1257 // no room; try to let player know
1258 SZ_Clear(&net_message);
1259 // save space for the header, filled in later
1260 MSG_WriteLong(&net_message, 0);
1261 MSG_WriteByte(&net_message, CCREP_REJECT);
1262 MSG_WriteString(&net_message, "Server is full.\n");
1263 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1264 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1265 SZ_Clear(&net_message);
1272 case CCREQ_SERVER_INFO:
1273 if (developer.integer)
1274 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1275 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1277 if (developer.integer)
1278 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1279 SZ_Clear(&net_message);
1280 // save space for the header, filled in later
1281 MSG_WriteLong(&net_message, 0);
1282 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1283 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1284 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1285 MSG_WriteString(&net_message, hostname.string);
1286 MSG_WriteString(&net_message, sv.name);
1287 MSG_WriteByte(&net_message, net_activeconnections);
1288 MSG_WriteByte(&net_message, svs.maxclients);
1289 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1290 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1291 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1292 SZ_Clear(&net_message);
1295 case CCREQ_PLAYER_INFO:
1296 if (developer.integer)
1297 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1300 int playerNumber, activeNumber, clientNumber;
1303 playerNumber = MSG_ReadByte();
1305 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1306 if (client->active && ++activeNumber == playerNumber)
1308 if (clientNumber != svs.maxclients)
1310 SZ_Clear(&net_message);
1311 // save space for the header, filled in later
1312 MSG_WriteLong(&net_message, 0);
1313 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1314 MSG_WriteByte(&net_message, playerNumber);
1315 MSG_WriteString(&net_message, client->name);
1316 MSG_WriteLong(&net_message, client->colors);
1317 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1318 MSG_WriteLong(&net_message, (int)(realtime - client->netconnection->connecttime));
1319 MSG_WriteString(&net_message, client->netconnection->address);
1320 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1321 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1322 SZ_Clear(&net_message);
1326 case CCREQ_RULE_INFO:
1327 if (developer.integer)
1328 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1334 // find the search start location
1335 prevCvarName = MSG_ReadString();
1336 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1338 // send the response
1339 SZ_Clear(&net_message);
1340 // save space for the header, filled in later
1341 MSG_WriteLong(&net_message, 0);
1342 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1345 MSG_WriteString(&net_message, var->name);
1346 MSG_WriteString(&net_message, var->string);
1348 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1349 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1350 SZ_Clear(&net_message);
1357 // we may not have liked the packet, but it was a valid control
1358 // packet, so we're done processing this packet now
1363 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1365 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1367 sv_player = host_client->edict;
1368 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1369 SV_ReadClientMessage();
1377 void NetConn_ServerFrame(void)
1380 lhnetaddress_t peeraddress;
1382 NetConn_UpdateServerStuff();
1383 for (i = 0;i < sv_numsockets;i++)
1384 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1385 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1386 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1388 // never timeout loopback connections
1389 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(host_client->netconnection->mysocket)) != LHNETADDRESSTYPE_LOOP)
1391 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1392 sv_player = host_client->edict;
1393 SV_DropClient(false);
1396 for (conn = netconn_list;conn;conn = conn->next)
1397 NetConn_ReSendMessage(conn);
1400 void NetConn_QueryMasters(void)
1404 lhnetaddress_t masteraddress;
1407 if (hostCacheCount >= HOSTCACHESIZE)
1410 for (i = 0;i < cl_numsockets;i++)
1417 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1419 SZ_Clear(&net_message);
1420 // save space for the header, filled in later
1421 MSG_WriteLong(&net_message, 0);
1422 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1423 MSG_WriteString(&net_message, "QUAKE");
1424 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1425 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1426 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1427 SZ_Clear(&net_message);
1431 // build the getservers
1432 snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1435 for (masternum = 0;sv_masters[masternum].name;masternum++)
1437 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1440 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1445 if (!masterquerycount)
1447 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1448 M_Update_Return_Reason("No network");
1452 void NetConn_Heartbeat(int priority)
1454 lhnetaddress_t masteraddress;
1456 lhnetsocket_t *mysocket;
1458 // if it's a state change (client connected), limit next heartbeat to no
1459 // more than 30 sec in the future
1460 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1461 nextheartbeattime = realtime + 30.0;
1463 // limit heartbeatperiod to 30 to 270 second range,
1464 // lower limit is to avoid abusing master servers with excess traffic,
1465 // upper limit is to avoid timing out on the master server (which uses
1467 if (sv_heartbeatperiod.value < 30)
1468 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1469 if (sv_heartbeatperiod.value > 270)
1470 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1472 // make advertising optional and don't advertise singleplayer games, and
1473 // only send a heartbeat as often as the admin wants
1474 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1476 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1477 for (masternum = 0;sv_masters[masternum].name;masternum++)
1478 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1479 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1483 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1486 qbyte sent[MAX_SCOREBOARD];
1488 memset(sent, 0, sizeof(sent));
1490 // simultaneously wait for the first CanSendMessage and send the message,
1491 // then wait for a second CanSendMessage (verifying it was received), or
1492 // the client drops and is no longer counted
1493 // the loop aborts when either it runs out of clients to send to, or a
1495 blocktime += Sys_DoubleTime();
1499 NetConn_ClientFrame();
1500 NetConn_ServerFrame();
1501 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1503 if (host_client->netconnection)
1505 if (NetConn_CanSendMessage(host_client->netconnection))
1508 NetConn_SendReliableMessage(host_client->netconnection, data);
1511 if (!NetConn_CanSendMessage(host_client->netconnection))
1516 while (count && Sys_DoubleTime() < blocktime);
1520 static void Net_Heartbeat_f(void)
1523 NetConn_Heartbeat(2);
1525 Con_Print("No server running, can not heartbeat to master server.\n");
1528 void PrintStats(netconn_t *conn)
1530 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1533 void Net_Stats_f(void)
1536 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1537 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1538 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1539 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1540 Con_Printf("packetsSent = %i\n", packetsSent);
1541 Con_Printf("packetsReSent = %i\n", packetsReSent);
1542 Con_Printf("packetsReceived = %i\n", packetsReceived);
1543 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1544 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1545 Con_Print("connections =\n");
1546 for (conn = netconn_list;conn;conn = conn->next)
1550 void Net_Slist_f(void)
1552 masterquerytime = realtime;
1553 masterquerycount = 0;
1554 masterreplycount = 0;
1555 serverquerycount = 0;
1556 serverreplycount = 0;
1558 memset(&pingcache, 0, sizeof(pingcache));
1559 if (m_state != m_slist)
1560 Con_Print("Sending requests to master servers\n");
1561 NetConn_QueryMasters();
1562 if (m_state != m_slist)
1563 Con_Print("Listening for replies...\n");
1566 void NetConn_Init(void)
1569 lhnetaddress_t tempaddress;
1570 netconn_mempool = Mem_AllocPool("Networking", 0, NULL);
1571 Cmd_AddCommand("net_stats", Net_Stats_f);
1572 Cmd_AddCommand("net_slist", Net_Slist_f);
1573 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1574 Cvar_RegisterVariable(&net_messagetimeout);
1575 Cvar_RegisterVariable(&net_messagerejointimeout);
1576 Cvar_RegisterVariable(&net_connecttimeout);
1577 Cvar_RegisterVariable(&cl_netlocalping);
1578 Cvar_RegisterVariable(&cl_netpacketloss);
1579 Cvar_RegisterVariable(&hostname);
1580 Cvar_RegisterVariable(&developer_networking);
1581 Cvar_RegisterVariable(&cl_netport);
1582 Cvar_RegisterVariable(&sv_netport);
1583 Cvar_RegisterVariable(&net_address);
1584 //Cvar_RegisterVariable(&net_address_ipv6);
1585 Cvar_RegisterVariable(&sv_public);
1586 Cvar_RegisterVariable(&sv_heartbeatperiod);
1587 for (i = 0;sv_masters[i].name;i++)
1588 Cvar_RegisterVariable(&sv_masters[i]);
1589 // COMMANDLINEOPTION: Server: -ip <ipaddress> sets the ip address of this machine for purposes of networking (default 0.0.0.0 also known as INADDR_ANY), use only if you have multiple network adapters and need to choose one specifically.
1590 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1592 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1594 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
1595 Cvar_SetQuick(&net_address, com_argv[i + 1]);
1598 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1600 // COMMANDLINEOPTION: Server: -port <portnumber> sets the port to use for a server (default 26000, the same port as QUAKE itself), useful if you host multiple servers on your machine
1601 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1603 i = atoi(com_argv[i + 1]);
1604 if (i >= 0 && i < 65536)
1606 Con_Printf("-port option used, setting port cvar to %i\n", i);
1607 Cvar_SetValueQuick(&sv_netport, i);
1610 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1614 memset(&pingcache, 0, sizeof(pingcache));
1615 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1619 void NetConn_Shutdown(void)
1621 NetConn_CloseClientPorts();
1622 NetConn_CloseServerPorts();