]> de.git.xonotic.org Git - xonotic/darkplaces.git/blobdiff - netconn.c
Lots of str[n]cat, str[n]cpy, and [v]sprintf have been replaced by strlcat, strlcpy...
[xonotic/darkplaces.git] / netconn.c
index c83966422ba4048a1c055826ad33dc047e29a123..c37a42b481e6cf521cfa8efebda262e80d7e10e5 100755 (executable)
--- a/netconn.c
+++ b/netconn.c
@@ -35,7 +35,6 @@ static cvar_t sv_masters [] =
        {CVAR_SAVE, "sv_master3", ""},
        {CVAR_SAVE, "sv_master4", ""},
        {0, "sv_masterextra1", "198.88.152.4"},
-       {0, "sv_masterextra2", "68.102.242.12"},
        {0, NULL, NULL}
 };
 
@@ -49,6 +48,14 @@ cvar_t net_connecttimeout = {0, "net_connecttimeout","10"};
 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED"};
 cvar_t developer_networking = {0, "developer_networking", "0"};
 
+cvar_t cl_fakelocalping_min = {0, "cl_fakelocalping_min","0"};
+cvar_t cl_fakelocalping_max = {0, "cl_fakelocalping_max","0"};
+static cvar_t cl_fakepacketloss_receive = {0, "cl_fakepacketloss_receive","0"};
+static cvar_t cl_fakepacketloss_send = {0, "cl_fakepacketloss_send","0"};
+static cvar_t sv_fakepacketloss_receive = {0, "sv_fakepacketloss_receive","0"};
+static cvar_t sv_fakepacketloss_send = {0, "sv_fakepacketloss_send","0"};
+
+
 /* statistic counters */
 static int packetsSent = 0;
 static int packetsReSent = 0;
@@ -61,6 +68,12 @@ static int unreliableMessagesReceived = 0;
 static int reliableMessagesSent = 0;
 static int reliableMessagesReceived = 0;
 
+double masterquerytime = -1000;
+int masterquerycount = 0;
+int masterreplycount = 0;
+int serverquerycount = 0;
+int serverreplycount = 0;
+
 int hostCacheCount = 0;
 hostcache_t hostcache[HOSTCACHESIZE];
 
@@ -86,6 +99,15 @@ cvar_t sv_netaddress_ipv6 = {0, "sv_netaddress_ipv6", "[0:0:0:0:0:0:0:0]:26000"}
 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
 {
        int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
+       int i;
+       if (cl_fakepacketloss_receive.integer)
+               for (i = 0;i < cl_numsockets;i++)
+                       if (cl_sockets[i] == mysocket && (rand() % 100) < cl_fakepacketloss_receive.integer)
+                               return 0;
+       if (sv_fakepacketloss_receive.integer)
+               for (i = 0;i < cl_numsockets;i++)
+                       if (sv_sockets[i] == mysocket && (rand() % 100) < sv_fakepacketloss_receive.integer)
+                               return 0;
        if (developer_networking.integer && length != 0)
        {
                char addressstring[128], addressstring2[128];
@@ -104,8 +126,18 @@ int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddres
 
 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
 {
-       int ret = LHNET_Write(mysocket, data, length, peeraddress);
-       if (developer_networking.integer && ret != 0)
+       int ret;
+       int i;
+       if (cl_fakepacketloss_send.integer)
+               for (i = 0;i < cl_numsockets;i++)
+                       if (cl_sockets[i] == mysocket && (rand() % 100) < cl_fakepacketloss_send.integer)
+                               return length;
+       if (sv_fakepacketloss_send.integer)
+               for (i = 0;i < cl_numsockets;i++)
+                       if (sv_sockets[i] == mysocket && (rand() % 100) < sv_fakepacketloss_send.integer)
+                               return length;
+       ret = LHNET_Write(mysocket, data, length, peeraddress);
+       if (developer_networking.integer)
        {
                char addressstring[128], addressstring2[128];
                LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
@@ -116,6 +148,12 @@ int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const l
        return ret;
 }
 
+int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
+{
+       // note this does not include the trailing NULL because we add that in the parser
+       return NetConn_Write(mysocket, string, strlen(string), peeraddress);
+}
+
 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
 {
        unsigned int packetLen;
@@ -137,14 +175,14 @@ int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
        memcpy(conn->sendMessage, data->data, data->cursize);
        conn->sendMessageLength = data->cursize;
 
-       if (conn->sendMessageLength <= MAX_DATAGRAM)
+       if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
        {
                dataLen = conn->sendMessageLength;
                eom = NETFLAG_EOM;
        }
        else
        {
-               dataLen = MAX_DATAGRAM;
+               dataLen = MAX_PACKETFRAGMENT;
                eom = 0;
        }
 
@@ -176,14 +214,14 @@ static void NetConn_SendMessageNext(netconn_t *conn)
 
        if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
        {
-               if (conn->sendMessageLength <= MAX_DATAGRAM)
+               if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
                {
                        dataLen = conn->sendMessageLength;
                        eom = NETFLAG_EOM;
                }
                else
                {
-                       dataLen = MAX_DATAGRAM;
+                       dataLen = MAX_PACKETFRAGMENT;
                        eom = 0;
                }
 
@@ -214,14 +252,14 @@ static void NetConn_ReSendMessage(netconn_t *conn)
 
        if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
        {
-               if (conn->sendMessageLength <= MAX_DATAGRAM)
+               if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
                {
                        dataLen = conn->sendMessageLength;
                        eom = NETFLAG_EOM;
                }
                else
                {
-                       dataLen = MAX_DATAGRAM;
+                       dataLen = MAX_PACKETFRAGMENT;
                        eom = 0;
                }
 
@@ -284,20 +322,40 @@ void NetConn_CloseClientPorts(void)
                        LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
 }
 
+void NetConn_OpenClientPort(const char *addressstring, int defaultport)
+{
+       lhnetaddress_t address;
+       lhnetsocket_t *s;
+       char addressstring2[1024];
+       if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
+       {
+               if ((s = LHNET_OpenSocket_Connectionless(&address)))
+               {
+                       cl_sockets[cl_numsockets++] = s;
+                       LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
+                       Con_Printf("Client opened a socket on address %s\n", addressstring2);
+               }
+               else
+               {
+                       LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
+                       Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
+               }
+       }
+       else
+               Con_Printf("Client unable to parse address %s\n", addressstring);
+}
+
 void NetConn_OpenClientPorts(void)
 {
        int port;
-       lhnetaddress_t address;
        NetConn_CloseClientPorts();
        port = bound(0, cl_netport.integer, 65535);
        if (cl_netport.integer != port)
                Cvar_SetValueQuick(&cl_netport, port);
-       LHNETADDRESS_FromString(&address, "local", port);
-       cl_sockets[cl_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
-       LHNETADDRESS_FromString(&address, cl_netaddress.string, port);
-       cl_sockets[cl_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
-       LHNETADDRESS_FromString(&address, cl_netaddress_ipv6.string, port);
-       cl_sockets[cl_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
+       Con_Printf("Client using port %i\n", port);
+       NetConn_OpenClientPort("local", port);
+       NetConn_OpenClientPort(cl_netaddress.string, port);
+       NetConn_OpenClientPort(cl_netaddress_ipv6.string, port);
 }
 
 void NetConn_CloseServerPorts(void)
@@ -307,32 +365,55 @@ void NetConn_CloseServerPorts(void)
                        LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
 }
 
+void NetConn_OpenServerPort(const char *addressstring, int defaultport)
+{
+       lhnetaddress_t address;
+       lhnetsocket_t *s;
+       char addressstring2[1024];
+       if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
+       {
+               if ((s = LHNET_OpenSocket_Connectionless(&address)))
+               {
+                       sv_sockets[sv_numsockets++] = s;
+                       LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
+                       Con_Printf("Server listening on address %s\n", addressstring2);
+               }
+               else
+               {
+                       LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
+                       Con_Printf("Server failed to open socket on address %s\n", addressstring2);
+               }
+       }
+       else
+               Con_Printf("Server unable to parse address %s\n", addressstring);
+}
+
 void NetConn_OpenServerPorts(int opennetports)
 {
        int port;
-       lhnetaddress_t address;
        NetConn_CloseServerPorts();
        port = bound(0, sv_netport.integer, 65535);
        if (port == 0)
                port = 26000;
+       Con_Printf("Server using port %i\n", port);
        if (sv_netport.integer != port)
                Cvar_SetValueQuick(&sv_netport, port);
-       LHNETADDRESS_FromString(&address, "local", port);
-       sv_sockets[sv_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
+       if (cls.state != ca_dedicated)
+               NetConn_OpenServerPort("local", port);
        if (opennetports)
        {
-               LHNETADDRESS_FromString(&address, sv_netaddress.string, port);
-               sv_sockets[sv_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
-               LHNETADDRESS_FromString(&address, sv_netaddress_ipv6.string, port);
-               sv_sockets[sv_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
+               NetConn_OpenServerPort(sv_netaddress.string, port);
+               NetConn_OpenServerPort(sv_netaddress_ipv6.string, port);
        }
+       if (sv_numsockets == 0)
+               Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
 }
 
 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
 {
        int i, a = LHNETADDRESS_GetAddressType(address);
        for (i = 0;i < cl_numsockets;i++)
-               if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
+               if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
                        return cl_sockets[i];
        return NULL;
 }
@@ -341,7 +422,7 @@ lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
 {
        int i, a = LHNETADDRESS_GetAddressType(address);
        for (i = 0;i < sv_numsockets;i++)
-               if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
+               if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
                        return sv_sockets[i];
        return NULL;
 }
@@ -393,17 +474,17 @@ static int clientport2 = -1;
 static int hostport = -1;
 static void NetConn_UpdateServerStuff(void)
 {
-       if (clientport2 != cl_netport.integer)
-       {
-               clientport2 = cl_netport.integer;
-               if (cls.state == ca_connected)
-                       Con_Printf("Changing \"cl_port\" will not take effect until you reconnect.\n");
-       }
        if (cls.state != ca_dedicated)
        {
-               if (cls.state == ca_disconnected && clientport != cl_netport.integer)
+               if (clientport2 != cl_netport.integer)
+               {
+                       clientport2 = cl_netport.integer;
+                       if (cls.state == ca_connected)
+                               Con_Printf("Changing \"cl_port\" will not take effect until you reconnect.\n");
+               }
+               if (cls.state == ca_disconnected && clientport != clientport2)
                {
-                       clientport = cl_netport.integer;
+                       clientport = clientport2;
                        NetConn_CloseClientPorts();
                }
                if (cl_numsockets == 0)
@@ -450,10 +531,13 @@ int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
                                        conn->lastMessageTime = realtime;
                                        conn->timeout = realtime + net_messagetimeout.value;
                                        unreliableMessagesReceived++;
-                                       SZ_Clear(&net_message);
-                                       SZ_Write(&net_message, data, length);
-                                       MSG_BeginReading();
-                                       return 2;
+                                       if (length > 0)
+                                       {
+                                               SZ_Clear(&net_message);
+                                               SZ_Write(&net_message, data, length);
+                                               MSG_BeginReading();
+                                               return 2;
+                                       }
                                }
                                else
                                        Con_DPrintf("Got a stale datagram\n");
@@ -470,10 +554,10 @@ int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
                                                        Con_DPrintf("ack sequencing error\n");
                                                conn->lastMessageTime = realtime;
                                                conn->timeout = realtime + net_messagetimeout.value;
-                                               conn->sendMessageLength -= MAX_DATAGRAM;
+                                               conn->sendMessageLength -= MAX_PACKETFRAGMENT;
                                                if (conn->sendMessageLength > 0)
                                                {
-                                                       memcpy(conn->sendMessage, conn->sendMessage+MAX_DATAGRAM, conn->sendMessageLength);
+                                                       memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
                                                        conn->sendNext = true;
                                                        NetConn_SendMessageNext(conn);
                                                }
@@ -506,11 +590,15 @@ int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
                                        if (flags & NETFLAG_EOM)
                                        {
                                                reliableMessagesReceived++;
-                                               SZ_Clear(&net_message);
-                                               SZ_Write(&net_message, conn->receiveMessage, conn->receiveMessageLength);
+                                               length = conn->receiveMessageLength;
                                                conn->receiveMessageLength = 0;
-                                               MSG_BeginReading();
-                                               return 2;
+                                               if (length > 0)
+                                               {
+                                                       SZ_Clear(&net_message);
+                                                       SZ_Write(&net_message, conn->receiveMessage, length);
+                                                       MSG_BeginReading();
+                                                       return 2;
+                                               }
                                        }
                                }
                                else
@@ -522,6 +610,27 @@ int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
        return 0;
 }
 
+void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
+{
+       cls.netcon = NetConn_Open(mysocket, peeraddress);
+       Con_Printf("Connection accepted to %s\n", cls.netcon->address);
+       key_dest = key_game;
+       m_state = m_none;
+       cls.connect_trying = false;
+       cls.demonum = -1;                       // not in the demo loop now
+       cls.state = ca_connected;
+       cls.signon = 0;                         // need all the signon messages before playing
+       CL_ClearState();
+       Host_Reconnect_f();
+}
+
+int NetConn_IsLocalGame(void)
+{
+       if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
+               return true;
+       return false;
+}
+
 static struct
 {
        double senttime;
@@ -535,18 +644,48 @@ int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
        lhnetaddress_t svaddress;
        const char *s;
        char *string, addressstring2[128], cname[128], ipstring[32];
+       char stringbuf[16384];
 
        if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
        {
+               // received a command string - strip off the packaging and put it
+               // into our string buffer with NULL termination
                data += 4;
                length -= 4;
-               string = (char *)data;
+               length = min(length, (int)sizeof(stringbuf) - 1);
+               memcpy(stringbuf, data, length);
+               stringbuf[length] = 0;
+               string = stringbuf;
+
                if (developer.integer)
                {
                        LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
                        Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
                        Com_HexDumpToConsole(data, length);
                }
+
+               if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
+               {
+                       LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
+                       Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
+                       NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
+                       return true;
+               }
+               if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
+               {
+                       NetConn_ConnectionEstablished(mysocket, peeraddress);
+                       return true;
+               }
+               if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
+               {
+                       cls.connect_trying = false;
+                       string += 7;
+                       length = max(length - 7, (int)sizeof(m_return_reason) - 1);
+                       memcpy(m_return_reason, string, length);
+                       m_return_reason[length] = 0;
+                       Con_Printf("%s\n", m_return_reason);
+                       return true;
+               }
                if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
                {
                        int i, j, c, n, users, maxusers;
@@ -556,110 +695,129 @@ int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                        string += 13;
                        // hostcache only uses text addresses
                        LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
-                       // search the cache for this server
-                       for (n = 0; n < hostCacheCount; n++)
-                               if (!strcmp(cname, hostcache[n].cname))
-                                       break;
-                       // add it or update it
-                       if (n == hostCacheCount)
-                       {
-                               // if cache is full replace highest ping server (the list is
-                               // kept sorted so this is always the last, and if this server
-                               // is good it will be sorted into an early part of the list)
-                               if (hostCacheCount >= HOSTCACHESIZE)
-                                       n = hostCacheCount - 1;
-                               else
-                                       hostCacheCount++;
-                       }
-                       if ((s = SearchInfostring(string, "gamename"     )) != NULL) strncpy(game, s, sizeof(game) - 1);else game[0] = 0;
-                       if ((s = SearchInfostring(string, "modname"      )) != NULL) strncpy(mod , s, sizeof(mod ) - 1);else mod[0] = 0;
-                       if ((s = SearchInfostring(string, "mapname"      )) != NULL) strncpy(map , s, sizeof(map ) - 1);else map[0] = 0;
-                       if ((s = SearchInfostring(string, "hostname"     )) != NULL) strncpy(name, s, sizeof(name) - 1);else name[0] = 0;
+                       if ((s = SearchInfostring(string, "gamename"     )) != NULL) strlcpy(game, s, sizeof (game));else game[0] = 0;
+                       if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(mod , s, sizeof (mod ));else mod[0]  = 0;
+                       if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(map , s, sizeof (map ));else map[0]  = 0;
+                       if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(name, s, sizeof (name));else name[0] = 0;
                        if ((s = SearchInfostring(string, "protocol"     )) != NULL) c = atoi(s);else c = -1;
                        if ((s = SearchInfostring(string, "clients"      )) != NULL) users = atoi(s);else users = 0;
                        if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) maxusers = atoi(s);else maxusers = 0;
-                       pingtime = 9999;
-                       for (i = 0;i < HOSTCACHESIZE;i++)
-                               if (!LHNETADDRESS_Compare(peeraddress, &pingcache[i].peeraddress))
-                                       pingtime = (int)(realtime - pingcache[i].senttime);
-                       pingtime = bound(0, pingtime, 9999);
-                       memset(&hostcache[n], 0, sizeof(hostcache[n]));
-                       // store the data the engine cares about (address and ping)
-                       strcpy(hostcache[n].cname, cname);
-                       hostcache[n].ping = pingtime;
-                       // build description strings for the things users care about
-                       snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, c != NET_PROTOCOL_VERSION ? '*' : ' ', users, maxusers, name);
-                       snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", cname, game, mod, map);
-                       // if ping is especially high, display it as such
-                       if (pingtime >= 300)
-                       {
-                               // orange numbers (lower block)
-                               for (i = 0;i < 5;i++)
-                                       if (hostcache[n].line1[i] != ' ')
-                                               hostcache[n].line1[i] += 128;
-                       }
-                       else if (pingtime >= 200)
-                       {
-                               // yellow numbers (in upper block)
-                               for (i = 0;i < 5;i++)
-                                       if (hostcache[n].line1[i] != ' ')
-                                               hostcache[n].line1[i] -= 30;
-                       }
-                       // if not in the slist menu we should print the server to console
-                       if (m_state != m_slist)
-                               Con_Printf("%s\n%s\n", hostcache[n].line1, hostcache[n].line2);
-                       // and finally, re-sort the list
-                       for (i = 0;i < hostCacheCount;i++)
+                       // search the cache for this server and update it
+                       for (n = 0; n < hostCacheCount; n++)
                        {
-                               for (j = i + 1;j < hostCacheCount;j++)
+                               if (!strcmp(cname, hostcache[n].cname))
                                {
-                                       //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
-                                       if (hostcache[i].ping > hostcache[j].ping)
+                                       if (hostcache[n].ping == 100000)
+                                               serverreplycount++;
+                                       pingtime = (int)((realtime - hostcache[n].querytime) * 1000.0);
+                                       pingtime = bound(0, pingtime, 9999);
+                                       // update the ping
+                                       hostcache[n].ping = pingtime;
+                                       // build description strings for the things users care about
+                                       snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, c != NET_PROTOCOL_VERSION ? '*' : ' ', users, maxusers, name);
+                                       snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", cname, game, mod, map);
+                                       // if ping is especially high, display it as such
+                                       if (pingtime >= 300)
                                        {
-                                               memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
-                                               memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
-                                               memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
+                                               // orange numbers (lower block)
+                                               for (i = 0;i < 5;i++)
+                                                       if (hostcache[n].line1[i] != ' ')
+                                                               hostcache[n].line1[i] += 128;
                                        }
+                                       else if (pingtime >= 200)
+                                       {
+                                               // yellow numbers (in upper block)
+                                               for (i = 0;i < 5;i++)
+                                                       if (hostcache[n].line1[i] != ' ')
+                                                               hostcache[n].line1[i] -= 30;
+                                       }
+                                       // if not in the slist menu we should print the server to console
+                                       if (m_state != m_slist)
+                                               Con_Printf("%s\n%s\n", hostcache[n].line1, hostcache[n].line2);
+                                       // and finally, re-sort the list
+                                       for (i = 0;i < hostCacheCount;i++)
+                                       {
+                                               for (j = i + 1;j < hostCacheCount;j++)
+                                               {
+                                                       //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
+                                                       if (hostcache[i].ping > hostcache[j].ping)
+                                                       {
+                                                               memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
+                                                               memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
+                                                               memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
+                                                       }
+                                               }
+                                       }
+                                       break;
                                }
                        }
                        return true;
                }
                if (!strncmp(string, "getserversResponse\\", 19) && hostCacheCount < HOSTCACHESIZE)
                {
-                       int i, best;
-                       double besttime;
+                       int i, n, j;
+                       hostcache_t temp;
                        // Extract the IP addresses
                        data += 18;
                        length -= 18;
+                       masterreplycount++;
+                       if (m_state != m_slist)
+                               Con_Printf("received server list...\n");
                        while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
                        {
                                sprintf(ipstring, "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
                                if (developer.integer)
                                        Con_Printf("Requesting info from server %s\n", ipstring);
                                LHNETADDRESS_FromString(&svaddress, ipstring, 0);
-                               NetConn_Write(mysocket, "\377\377\377\377getinfo", 11, &svaddress);
-                               // replace oldest or matching entry in ping cache
-                               // we scan this later when getting a reply to see how long it took
-                               besttime = realtime;
-                               best = 0;
-                               for (i = 0;i < HOSTCACHESIZE;i++)
+                               NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
+
+
+                               // add to slist (hostCache)
+                               // search the cache for this server
+                               for (n = 0; n < hostCacheCount; n++)
+                                       if (!strcmp(ipstring, hostcache[n].cname))
+                                               break;
+                               // add it or update it
+                               if (n == hostCacheCount)
                                {
-                                       if (!LHNETADDRESS_Compare(&svaddress, &pingcache[i].peeraddress))
+                                       // if cache is full replace highest ping server (the list is
+                                       // kept sorted so this is always the last, and if this server
+                                       // is good it will be sorted into an early part of the list)
+                                       if (hostCacheCount >= HOSTCACHESIZE)
+                                               n = hostCacheCount - 1;
+                                       else
                                        {
-                                               best = i;
-                                               break;
+                                               serverquerycount++;
+                                               hostCacheCount++;
                                        }
-                                       if (besttime > pingcache[i].senttime)
+                               }
+                               memset(&hostcache[n], 0, sizeof(hostcache[n]));
+                               // store the data the engine cares about (address and ping)
+                               strcpy(hostcache[n].cname, ipstring);
+                               hostcache[n].ping = 100000;
+                               hostcache[n].querytime = realtime;
+                               // build description strings for the things users care about
+                               snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "?");
+                               snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%s", ipstring);
+                               // if not in the slist menu we should print the server to console
+                               if (m_state != m_slist)
+                                       Con_Printf("querying %s\n", ipstring);
+                               // and finally, re-sort the list
+                               for (i = 0;i < hostCacheCount;i++)
+                               {
+                                       for (j = i + 1;j < hostCacheCount;j++)
                                        {
-                                               besttime = pingcache[i].senttime;
-                                               best = i;
-                                               // if ping cache isn't full yet we can skip out early
-                                               if (!besttime)
-                                                       break;
+                                               //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
+                                               if (hostcache[i].ping > hostcache[j].ping)
+                                               {
+                                                       memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
+                                                       memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
+                                                       memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
+                                               }
                                        }
                                }
-                               pingcache[best].peeraddress = svaddress;
-                               pingcache[best].senttime = realtime;
+
+
                                // move on to next address in packet
                                data += 7;
                                length -= 7;
@@ -671,7 +829,7 @@ int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                {
                        if (developer.integer)
                                Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
-                       NetConn_Write(mysocket, "\377\377\377\377ack", 7, peeraddress);
+                       NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
                        return true;
                }
                if (!strncmp(string, "ack", 3))
@@ -681,6 +839,7 @@ int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                // we're done processing this packet now
                return true;
        }
+       // netquake control packets, supported for compatibility only
        if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
        {
                c = data[4];
@@ -694,30 +853,23 @@ int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                                Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
                        if (cls.connect_trying)
                        {
-                               Con_Printf("Connection accepted to %s\n", addressstring2);
-                               key_dest = key_game;
-                               m_state = m_none;
-                               cls.netcon = NetConn_Open(mysocket, peeraddress);
+                               lhnetaddress_t clientportaddress;
+                               clientportaddress = *peeraddress;
                                if (length >= 4)
                                {
-                                       unsigned int port = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3];
+                                       unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
                                        data += 4;
                                        length -= 4;
-                                       LHNETADDRESS_SetPort(&cls.netcon->peeraddress, port);
+                                       LHNETADDRESS_SetPort(&clientportaddress, port);
                                }
-                               cls.connect_trying = false;
-                               cls.demonum = -1;                       // not in the demo loop now
-                               cls.state = ca_connected;
-                               cls.signon = 0;                         // need all the signon messages before playing
-                               CL_ClearState();
-                               Host_Reconnect_f();
+                               NetConn_ConnectionEstablished(mysocket, &clientportaddress);
                        }
                        break;
                case CCREP_REJECT:
                        if (developer.integer)
                                Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
                        Con_Printf("%s\n", data);
-                       strncpy(m_return_reason, data, sizeof(m_return_reason) - 1);
+                       strlcpy (m_return_reason, data, sizeof (m_return_reason));
                        break;
 #if 0
                case CCREP_SERVER_INFO:
@@ -746,11 +898,9 @@ int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                                        c = MSG_ReadByte();
                                        if (c != NET_PROTOCOL_VERSION)
                                        {
-                                               strncpy(hostcache[n].cname, hostcache[n].name, sizeof(hostcache[n].cname) - 1);
-                                               hostcache[n].cname[sizeof(hostcache[n].cname) - 1] = 0;
+                                               strlcpy (hostcache[n].cname, hostcache[n].name, sizeof (hostcache[n].cname));
                                                strcpy(hostcache[n].name, "*");
-                                               strncat(hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name) - 1);
-                                               hostcache[n].name[sizeof(hostcache[n].name) - 1] = 0;
+                                               strlcat (hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name));
                                        }
                                        strcpy(hostcache[n].cname, cname);
                                }
@@ -791,15 +941,31 @@ void NetConn_ClientFrame(void)
                if (cls.connect_remainingtries == 0)
                {
                        cls.connect_trying = false;
-                       Host_Error("Connect failed\n");
+                       if (m_state == m_slist)
+                               strcpy(m_return_reason, "Connect: Failed");
+                       else
+                               Con_Printf("Connect failed\n");
                        return;
                }
                if (cls.connect_nextsendtime)
-                       Con_Printf("Still trying...\n");
+               {
+                       if (m_state == m_slist)
+                               strcpy(m_return_reason, "Connect: Still trying");
+                       else
+                               Con_Printf("Still trying...\n");
+               }
                else
-                       Con_Printf("Trying...\n");
+               {
+                       if (m_state == m_slist)
+                               strcpy(m_return_reason, "Connect: Trying");
+                       else
+                               Con_Printf("Trying...\n");
+               }
                cls.connect_nextsendtime = realtime + 1;
                cls.connect_remainingtries--;
+               // try challenge first (newer server)
+               NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
+               // then try netquake as a fallback (old server, or netquake)
                SZ_Clear(&net_message);
                // save space for the header, filled in later
                MSG_WriteLong(&net_message, 0);
@@ -822,21 +988,51 @@ void NetConn_ClientFrame(void)
                NetConn_ReSendMessage(conn);
 }
 
+#define MAX_CHALLENGES 128
+struct
+{
+       lhnetaddress_t address;
+       double time;
+       char string[12];
+}
+challenge[MAX_CHALLENGES];
+
+static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
+{
+       int i;
+       char c;
+       for (i = 0;i < bufferlength - 1;i++)
+       {
+               do
+               {
+                       c = rand () % (127 - 33) + 33;
+               } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
+               buffer[i] = c;
+       }
+       buffer[i] = 0;
+}
+
 extern void SV_ConnectClient(int clientnum, netconn_t *netconnection);
 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
 {
-       int i, c, n, ret, clientnum, control, responselength;
+       int i, n, ret, clientnum, responselength, best;
+       double besttime;
        client_t *client;
        netconn_t *conn;
-       char *string, response[512], addressstring2[128];
+       char *s, *string, response[512], addressstring2[128], stringbuf[16384];
 
        if (sv.active)
        {
                if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
                {
+                       // received a command string - strip off the packaging and put it
+                       // into our string buffer with NULL termination
                        data += 4;
                        length -= 4;
-                       string = (char *)data;
+                       length = min(length, (int)sizeof(stringbuf) - 1);
+                       memcpy(stringbuf, data, length);
+                       stringbuf[length] = 0;
+                       string = stringbuf;
 
                        if (developer.integer)
                        {
@@ -845,6 +1041,110 @@ int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                                Com_HexDumpToConsole(data, length);
                        }
 
+                       if (length >= 12 && !memcmp(string, "getchallenge", 12))
+                       {
+                               for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
+                               {
+                                       if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
+                                               break;
+                                       if (besttime > challenge[i].time)
+                                               besttime = challenge[best = i].time;
+                               }
+                               // if we did not find an exact match, choose the oldest and
+                               // update address and string
+                               if (i == MAX_CHALLENGES)
+                               {
+                                       i = best;
+                                       challenge[i].address = *peeraddress;
+                                       NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
+                               }
+                               challenge[i].time = realtime;
+                               // send the challenge
+                               NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
+                               return true;
+                       }
+                       if (length > 8 && !memcmp(string, "connect\\", 8))
+                       {
+                               string += 7;
+                               length -= 7;
+                               if ((s = SearchInfostring(string, "challenge")))
+                               {
+                                       // validate the challenge
+                                       for (i = 0;i < MAX_CHALLENGES;i++)
+                                               if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
+                                                       break;
+                                       if (i < MAX_CHALLENGES)
+                                       {
+                                               // check engine protocol
+                                               if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
+                                               {
+                                                       if (developer.integer)
+                                                               Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
+                                                       NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
+                                               }
+                                               else
+                                               {
+                                                       // see if this is a duplicate connection request
+                                                       for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
+                                                               if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
+                                                                       break;
+                                                       if (clientnum < svs.maxclients)
+                                                       {
+                                                               // duplicate connection request
+                                                               if (realtime - client->netconnection->connecttime < 2.0)
+                                                               {
+                                                                       // client is still trying to connect,
+                                                                       // so we send a duplicate reply
+                                                                       if (developer.integer)
+                                                                               Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
+                                                                       NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
+                                                               }
+                                                               // only kick if old connection seems dead
+                                                               if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
+                                                               {
+                                                                       // kick off connection and await retry
+                                                                       client->deadsocket = true;
+                                                               }
+                                                       }
+                                                       else
+                                                       {
+                                                               // this is a new client, find a slot
+                                                               for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
+                                                                       if (!client->active)
+                                                                               break;
+                                                               if (clientnum < svs.maxclients)
+                                                               {
+                                                                       // prepare the client struct
+                                                                       if ((client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_clients_mempool)))
+                                                                       {
+                                                                               if ((conn = NetConn_Open(mysocket, peeraddress)))
+                                                                               {
+                                                                                       // allocated connection
+                                                                                       LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
+                                                                                       if (developer.integer)
+                                                                                               Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
+                                                                                       NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
+                                                                                       // now set up the client
+                                                                                       SV_ConnectClient(clientnum, conn);
+                                                                                       NetConn_Heartbeat(1);
+                                                                               }
+                                                                               else
+                                                                                       EntityFrame4_FreeDatabase(client->entitydatabase4);
+                                                                       }
+                                                               }
+                                                               else
+                                                               {
+                                                                       // server is full
+                                                                       if (developer.integer)
+                                                                               Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
+                                                                       NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
+                                                               }
+                                                       }
+                                               }
+                                       }
+                               }
+                               return true;
+                       }
                        if (length >= 7 && !memcmp(string, "getinfo", 7))
                        {
                                const char *challenge = NULL;
@@ -864,7 +1164,7 @@ int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                                {
                                        if (developer.integer)
                                                Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
-                                       NetConn_Write(mysocket, response, responselength, peeraddress);
+                                       NetConn_WriteString(mysocket, response, peeraddress);
                                }
                                return true;
                        }
@@ -873,7 +1173,7 @@ int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                        {
                                if (developer.integer)
                                        Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
-                               NetConn_Write(mysocket, "\377\377\377\377ack", 7, peeraddress);
+                               NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
                                return true;
                        }
                        if (!strncmp(string, "ack", 3))
@@ -883,11 +1183,12 @@ int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                        // we're done processing this packet now
                        return true;
                }
-#if 1
-               if (length >= 5)
+               // LordHavoc: disabled netquake control packet support in server
+#if 0
                {
-                       control = BigLong(*((int *)data));
-                       if ((control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
+                       int c, control;
+                       // netquake control packets, supported for compatibility only
+                       if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
                        {
                                c = data[4];
                                data += 5;
@@ -904,9 +1205,6 @@ int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                                                {
                                                        if (developer.integer)
                                                                Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
-#if 0
-                                                       NetConn_Write(mysocket, "\377\377\377\377reject Incompatible version.", 32, peeraddress);
-#else
                                                        SZ_Clear(&net_message);
                                                        // save space for the header, filled in later
                                                        MSG_WriteLong(&net_message, 0);
@@ -915,13 +1213,12 @@ int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                                                        *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
                                                        NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
                                                        SZ_Clear(&net_message);
-#endif
                                                }
                                                else
                                                {
                                                        // see if this is a duplicate connection request
                                                        for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
-                                                               if (client->active && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
+                                                               if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
                                                                        break;
                                                        if (clientnum < svs.maxclients)
                                                        {
@@ -932,9 +1229,6 @@ int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                                                                        // so we send a duplicate reply
                                                                        if (developer.integer)
                                                                                Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
-#if 0
-                                                                       NetConn_Write(mysocket, "\377\377\377\377accept", 10, peeraddress);
-#else
                                                                        SZ_Clear(&net_message);
                                                                        // save space for the header, filled in later
                                                                        MSG_WriteLong(&net_message, 0);
@@ -943,7 +1237,6 @@ int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                                                                        *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
                                                                        NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
                                                                        SZ_Clear(&net_message);
-#endif
                                                                }
                                                                else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
                                                                {
@@ -966,9 +1259,6 @@ int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                                                                        strcpy(conn->address, addressstring2);
                                                                        if (developer.integer)
                                                                                Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
-#if 0
-                                                                       NetConn_Write(mysocket, "\377\377\377\377accept", 10, peeraddress);
-#else
                                                                        // send back the info about the server connection
                                                                        SZ_Clear(&net_message);
                                                                        // save space for the header, filled in later
@@ -978,7 +1268,6 @@ int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                                                                        *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
                                                                        NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
                                                                        SZ_Clear(&net_message);
-#endif
                                                                        // now set up the client struct
                                                                        SV_ConnectClient(clientnum, conn);
                                                                        NetConn_Heartbeat(1);
@@ -988,9 +1277,6 @@ int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                                                                        //if (developer.integer)
                                                                                Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
                                                                        // no room; try to let player know
-#if 0
-                                                                       NetConn_Write(mysocket, "\377\377\377\377reject Server is full.", 26, peeraddress);
-#else
                                                                        SZ_Clear(&net_message);
                                                                        // save space for the header, filled in later
                                                                        MSG_WriteLong(&net_message, 0);
@@ -999,7 +1285,6 @@ int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
                                                                        *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
                                                                        NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
                                                                        SZ_Clear(&net_message);
-#endif
                                                                }
                                                        }
                                                }
@@ -1099,7 +1384,7 @@ int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length,
 #endif
                for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
                {
-                       if (host_client->active && host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
+                       if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
                        {
                                sv_player = host_client->edict;
                                if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
@@ -1122,7 +1407,8 @@ void NetConn_ServerFrame(void)
                        NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
        for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
        {
-               if (host_client->active && realtime > host_client->netconnection->timeout)
+               // never timeout loopback connections
+               if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(host_client->netconnection->mysocket)) != LHNETADDRESSTYPE_LOOP)
                {
                        Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
                        sv_player = host_client->edict;
@@ -1137,7 +1423,6 @@ void NetConn_QueryMasters(void)
 {
        int i;
        int masternum;
-       int requestlen;
        lhnetaddress_t masteraddress;
        char request[256];
 
@@ -1166,22 +1451,30 @@ void NetConn_QueryMasters(void)
 #endif
 
                        // build the getservers
-                       requestlen = snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
+                       snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
 
                        // search internet
                        for (masternum = 0;sv_masters[masternum].name;masternum++)
+                       {
                                if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
-                                       NetConn_Write(cl_sockets[i], request, requestlen, &masteraddress);
+                               {
+                                       masterquerycount++;
+                                       NetConn_WriteString(cl_sockets[i], request, &masteraddress);
+                               }
+                       }
                }
        }
+       if (!masterquerycount)
+       {
+               Con_Printf("Unable to query master servers, no suitable network sockets active.\n");
+               strcpy(m_return_reason, "No network");
+       }
 }
 
 void NetConn_Heartbeat(int priority)
 {
        lhnetaddress_t masteraddress;
        int masternum;
-       char *request = "\377\377\377\377heartbeat DarkPlaces\x0A";
-       int requestlen = strlen(request);
        lhnetsocket_t *mysocket;
 
        // if it's a state change (client connected), limit next heartbeat to no
@@ -1205,7 +1498,7 @@ void NetConn_Heartbeat(int priority)
                nextheartbeattime = realtime + sv_heartbeatperiod.value;
                for (masternum = 0;sv_masters[masternum].name;masternum++)
                        if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
-                               NetConn_Write(mysocket, request, requestlen, &masteraddress);
+                               NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
        }
 }
 
@@ -1229,7 +1522,7 @@ int NetConn_SendToAll(sizebuf_t *data, double blocktime)
                NetConn_ServerFrame();
                for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
                {
-                       if (host_client->active)
+                       if (host_client->netconnection)
                        {
                                if (NetConn_CanSendMessage(host_client->netconnection))
                                {
@@ -1246,33 +1539,12 @@ int NetConn_SendToAll(sizebuf_t *data, double blocktime)
        return count;
 }
 
-static void MaxPlayers_f(void)
-{
-       int n;
-
-       if (Cmd_Argc() != 2)
-       {
-               Con_Printf("\"maxplayers\" is \"%u\"\n", svs.maxclients);
-               return;
-       }
-
-       if (sv.active)
-       {
-               Con_Printf("maxplayers can not be changed while a server is running.\n");
-               return;
-       }
-
-       n = atoi(Cmd_Argv(1));
-       n = bound(1, n, MAX_SCOREBOARD);
-       if (svs.maxclients != n)
-               Con_Printf("\"maxplayers\" set to \"%u\"\n", n);
-
-       SV_SetMaxClients(n);
-}
-
 static void Net_Heartbeat_f(void)
 {
-       NetConn_Heartbeat(2);
+       if (sv.active)
+               NetConn_Heartbeat(2);
+       else
+               Con_Printf("No server running, can not heartbeat to master server.\n");
 }
 
 void PrintStats(netconn_t *conn)
@@ -1299,6 +1571,11 @@ void Net_Stats_f(void)
 
 void Net_Slist_f(void)
 {
+       masterquerytime = realtime;
+       masterquerycount = 0;
+       masterreplycount = 0;
+       serverquerycount = 0;
+       serverreplycount = 0;
        hostCacheCount = 0;
        memset(&pingcache, 0, sizeof(pingcache));
        if (m_state != m_slist)
@@ -1310,15 +1587,21 @@ void Net_Slist_f(void)
 
 void NetConn_Init(void)
 {
-       int masternum;
+       int i;
+       lhnetaddress_t tempaddress;
        netconn_mempool = Mem_AllocPool("Networking");
        Cmd_AddCommand("net_stats", Net_Stats_f);
        Cmd_AddCommand("net_slist", Net_Slist_f);
-       Cmd_AddCommand("maxplayers", MaxPlayers_f);
        Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
        Cvar_RegisterVariable(&net_messagetimeout);
        Cvar_RegisterVariable(&net_messagerejointimeout);
        Cvar_RegisterVariable(&net_connecttimeout);
+       Cvar_RegisterVariable(&cl_fakelocalping_min);
+       Cvar_RegisterVariable(&cl_fakelocalping_max);
+       Cvar_RegisterVariable(&cl_fakepacketloss_receive);
+       Cvar_RegisterVariable(&cl_fakepacketloss_send);
+       Cvar_RegisterVariable(&sv_fakepacketloss_receive);
+       Cvar_RegisterVariable(&sv_fakepacketloss_send);
        Cvar_RegisterVariable(&hostname);
        Cvar_RegisterVariable(&developer_networking);
        Cvar_RegisterVariable(&cl_netport);
@@ -1329,8 +1612,30 @@ void NetConn_Init(void)
        Cvar_RegisterVariable(&sv_netaddress_ipv6);
        Cvar_RegisterVariable(&sv_public);
        Cvar_RegisterVariable(&sv_heartbeatperiod);
-       for (masternum = 0;sv_masters[masternum].name;masternum++)
-               Cvar_RegisterVariable(&sv_masters[masternum]);
+       for (i = 0;sv_masters[i].name;i++)
+               Cvar_RegisterVariable(&sv_masters[i]);
+       if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
+       {
+               if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
+               {
+                       Con_Printf("-ip option used, setting cl_netaddress and sv_netaddress to address \"%s\"\n");
+                       Cvar_SetQuick(&cl_netaddress, com_argv[i + 1]);
+                       Cvar_SetQuick(&sv_netaddress, com_argv[i + 1]);
+               }
+               else
+                       Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
+       }
+       if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
+       {
+               i = atoi(com_argv[i + 1]);
+               if (i >= 0 && i < 65536)
+               {
+                       Con_Printf("-port option used, setting port cvar to %i\n", i);
+                       Cvar_SetValueQuick(&sv_netport, i);
+               }
+               else
+                       Con_Printf("-port option used, but %i is not a valid port number\n", i);
+       }
        cl_numsockets = 0;
        sv_numsockets = 0;
        memset(&pingcache, 0, sizeof(pingcache));