]> git.xonotic.org Git - xonotic/darkplaces.git/blobdiff - netconn.c
fix all the () problems, and make gcc warn for them
[xonotic/darkplaces.git] / netconn.c
index ce127fec5e3527bdd1ea97717e29efa8ee370462..7a6352887c57dab73be7b4d69edc4f1b38ed3a10 100755 (executable)
--- a/netconn.c
+++ b/netconn.c
@@ -23,6 +23,11 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include "quakedef.h"
 #include "lhnet.h"
 
+// for secure rcon authentication
+#include "hmac.h"
+#include "mdfour.h"
+#include <time.h>
+
 #define QWMASTER_PORT 27000
 #define DPMASTER_PORT 27950
 
@@ -36,9 +41,9 @@ static cvar_t sv_masters [] =
        {CVAR_SAVE, "sv_master2", "", "user-chosen master server 2"},
        {CVAR_SAVE, "sv_master3", "", "user-chosen master server 3"},
        {CVAR_SAVE, "sv_master4", "", "user-chosen master server 4"},
-       {0, "sv_masterextra1", "ghdigital.com", "default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
-       {0, "sv_masterextra2", "dpmaster.deathmask.net", "default master server 2 (admin: Willis)"}, // admin: Willis
-       {0, "sv_masterextra3", "dpmaster.tchr.no", "default master server 3 (admin: tChr)"}, // admin: tChr
+       {0, "sv_masterextra1", "69.59.212.88", "ghdigital.com - default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
+       {0, "sv_masterextra2", "64.22.107.125", "dpmaster.deathmask.net - default master server 2 (admin: Willis)"}, // admin: Willis
+       {0, "sv_masterextra3", "92.62.40.73", "dpmaster.tchr.no - default master server 3 (admin: tChr)"}, // admin: tChr
        {0, NULL, NULL, NULL}
 };
 
@@ -62,7 +67,7 @@ sizebuf_t net_message;
 static unsigned char net_message_buf[NET_MAXMESSAGE];
 
 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
-cvar_t net_connecttimeout = {0, "net_connecttimeout","10", "after requesting a connection, the client must reply within this many seconds or be dropped (cuts down on connect floods)"};
+cvar_t net_connecttimeout = {0, "net_connecttimeout","15", "after requesting a connection, the client must reply within this many seconds or be dropped (cuts down on connect floods). Must be above 10 seconds."};
 cvar_t net_connectfloodblockingtimeout = {0, "net_connectfloodblockingtimeout", "5", "when a connection packet is received, it will block all future connect packets from that IP address for this many seconds (cuts down on connect floods)"};
 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
@@ -75,11 +80,14 @@ static cvar_t net_slist_queriesperframe = {0, "net_slist_queriesperframe", "4",
 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
 static cvar_t net_slist_pause = {0, "net_slist_pause", "0", "when set to 1, the server list won't update until it is set back to 0"};
 static cvar_t net_slist_maxtries = {0, "net_slist_maxtries", "3", "how many times to ask the same server for information (more times gives better ping reports but takes longer)"};
-static cvar_t net_slist_favorites = {CVAR_SAVE, "net_slist_favorites", "", "contains a list of IP addresses and ports to always query explicitly"};
-
-static cvar_t gameversion = {0, "gameversion", "0", "version of game data (mod-specific), when client and server gameversion mismatch in the server browser the server is shown as incompatible"};
+static cvar_t net_slist_favorites = {CVAR_SAVE | CVAR_NQUSERINFOHACK, "net_slist_favorites", "", "contains a list of IP addresses and ports to always query explicitly"};
+static cvar_t gameversion = {0, "gameversion", "0", "version of game data (mod-specific) to be sent to querying clients"};
+static cvar_t gameversion_min = {0, "gameversion_min", "-1", "minimum version of game data (mod-specific), when client and server gameversion mismatch in the server browser the server is shown as incompatible; if -1, gameversion is used alone"};
+static cvar_t gameversion_max = {0, "gameversion_max", "-1", "maximum version of game data (mod-specific), when client and server gameversion mismatch in the server browser the server is shown as incompatible; if -1, gameversion is used alone"};
 static cvar_t rcon_restricted_password = {CVAR_PRIVATE, "rcon_restricted_password", "", "password to authenticate rcon commands in restricted mode"};
 static cvar_t rcon_restricted_commands = {0, "rcon_restricted_commands", "", "allowed commands for rcon when the restricted mode password was used"};
+static cvar_t rcon_secure_maxdiff = {0, "rcon_secure_maxdiff", "5", "maximum time difference between rcon request and server system clock (to protect against replay attack)"};
+extern cvar_t rcon_secure;
 
 /* statistic counters */
 static int packetsSent = 0;
@@ -99,12 +107,12 @@ int masterreplycount = 0;
 int serverquerycount = 0;
 int serverreplycount = 0;
 
-// this is only false if there are still servers left to query
+/// this is only false if there are still servers left to query
 static qboolean serverlist_querysleep = true;
 static qboolean serverlist_paused = false;
-// this is pushed a second or two ahead of realtime whenever a master server
-// reply is received, to avoid issuing queries while master replies are still
-// flooding in (which would make a mess of the ping times)
+/// this is pushed a second or two ahead of realtime whenever a master server
+/// reply is received, to avoid issuing queries while master replies are still
+/// flooding in (which would make a mess of the ping times)
 static double serverlist_querywaittime = 0;
 
 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
@@ -120,8 +128,8 @@ mempool_t *netconn_mempool = NULL;
 
 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
-cvar_t net_address = {0, "net_address", "0.0.0.0", "network address to open ports on"};
-//cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]", "network address to open ipv6 ports on"};
+cvar_t net_address = {0, "net_address", "", "network address to open ipv4 ports on (if empty, use default interfaces)"};
+cvar_t net_address_ipv6 = {0, "net_address_ipv6", "", "network address to open ipv6 ports on (if empty, use default interfaces)"};
 
 char net_extresponse[NET_EXTRESPONSE_MAX][1400];
 int net_extresponse_count = 0;
@@ -142,8 +150,23 @@ serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
 
 qboolean serverlist_consoleoutput;
 
-// helper function to insert a value into the viewset
-// spare entries will be removed
+static int nFavorites = 0;
+static lhnetaddress_t favorites[256];
+
+void NetConn_UpdateFavorites(void)
+{
+       const char *p;
+       nFavorites = 0;
+       p = net_slist_favorites.string;
+       while((size_t) nFavorites < sizeof(favorites) / sizeof(*favorites) && COM_ParseToken_Console(&p))
+       {
+               if(LHNETADDRESS_FromString(&favorites[nFavorites], com_token, 26000))
+                       ++nFavorites;
+       }
+}
+
+/// helper function to insert a value into the viewset
+/// spare entries will be removed
 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
 {
     int i;
@@ -159,7 +182,7 @@ static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entr
        serverlist_viewlist[index] = entry;
 }
 
-// we suppose serverlist_viewcount to be valid, ie > 0
+/// we suppose serverlist_viewcount to be valid, ie > 0
 static void _ServerList_ViewList_Helper_Remove( int index )
 {
        serverlist_viewcount--;
@@ -167,7 +190,7 @@ static void _ServerList_ViewList_Helper_Remove( int index )
                serverlist_viewlist[index] = serverlist_viewlist[index + 1];
 }
 
-// returns true if A should be inserted before B
+/// \returns true if A should be inserted before B
 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
 {
        int result = 0; // > 0 if for numbers A > B and for text if A < B
@@ -352,22 +375,33 @@ static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info
 
 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
 {
-       int start, end, mid;
-       const char *text;
+       int start, end, mid, i;
+       lhnetaddress_t addr;
 
        // reject incompatible servers
-       if (entry->info.gameversion != gameversion.integer)
+       if(
+               entry->info.gameversion != gameversion.integer
+               &&
+               !(
+                          gameversion_min.integer >= 0 // min/max range set by user/mod?
+                       && gameversion_max.integer >= 0
+                       && gameversion_min.integer >= entry->info.gameversion // version of server in min/max range?
+                       && gameversion_max.integer <= entry->info.gameversion
+                )
+       )
                return;
 
        // refresh the "favorite" status
-       text = net_slist_favorites.string;
        entry->info.isfavorite = false;
-       while(COM_ParseToken_Console(&text))
+       if(LHNETADDRESS_FromString(&addr, entry->info.cname, 26000))
        {
-               if(!strcmp(com_token, entry->info.cname))
+               for(i = 0; i < nFavorites; ++i)
                {
-                       entry->info.isfavorite = true;
-                       break;
+                       if(LHNETADDRESS_Compare(&addr, &favorites[i]) == 0)
+                       {
+                               entry->info.isfavorite = true;
+                               break;
+                       }
                }
        }
 
@@ -531,11 +565,11 @@ int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddres
                if (length > 0)
                {
                        LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
-                       Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
+                       Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", (void *)mysocket, addressstring, (void *)data, maxlength, (void *)peeraddress, length, addressstring2);
                        Com_HexDumpToConsole((unsigned char *)data, length);
                }
                else
-                       Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
+                       Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", (void *)mysocket, addressstring, (void *)data, maxlength, (void *)peeraddress, length);
        }
        return length;
 }
@@ -554,7 +588,7 @@ int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const l
                char addressstring[128], addressstring2[128];
                LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
                LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
-               Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
+               Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", (void *)mysocket, addressstring, (void *)data, length, (void *)peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
                Com_HexDumpToConsole((unsigned char *)data, length);
        }
        return ret;
@@ -804,12 +838,17 @@ void NetConn_CloseClientPorts(void)
                        LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
 }
 
-void NetConn_OpenClientPort(const char *addressstring, int defaultport)
+void NetConn_OpenClientPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport)
 {
        lhnetaddress_t address;
        lhnetsocket_t *s;
+       int success;
        char addressstring2[1024];
-       if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
+       if (addressstring && addressstring[0])
+               success = LHNETADDRESS_FromString(&address, addressstring, defaultport);
+       else
+               success = LHNETADDRESS_FromPort(&address, addresstype, defaultport);
+       if (success)
        {
                if ((s = LHNET_OpenSocket_Connectionless(&address)))
                {
@@ -838,9 +877,9 @@ void NetConn_OpenClientPorts(void)
                Con_Printf("Client using an automatically assigned port\n");
        else
                Con_Printf("Client using port %i\n", port);
-       NetConn_OpenClientPort("local:2", 0);
-       NetConn_OpenClientPort(net_address.string, port);
-       //NetConn_OpenClientPort(net_address_ipv6.string, port);
+       NetConn_OpenClientPort(NULL, LHNETADDRESSTYPE_LOOP, 2);
+       NetConn_OpenClientPort(net_address.string, LHNETADDRESSTYPE_INET4, port);
+       NetConn_OpenClientPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port);
 }
 
 void NetConn_CloseServerPorts(void)
@@ -850,23 +889,28 @@ void NetConn_CloseServerPorts(void)
                        LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
 }
 
-void NetConn_OpenServerPort(const char *addressstring, int defaultport)
+qboolean NetConn_OpenServerPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport, int range)
 {
        lhnetaddress_t address;
        lhnetsocket_t *s;
        int port;
        char addressstring2[1024];
+       int success;
 
-       for (port = defaultport; port <= defaultport + 100; port++)
+       for (port = defaultport; port <= defaultport + range; port++)
        {
-               if (LHNETADDRESS_FromString(&address, addressstring, port))
+               if (addressstring && addressstring[0])
+                       success = LHNETADDRESS_FromString(&address, addressstring, port);
+               else
+                       success = LHNETADDRESS_FromPort(&address, addresstype, port);
+               if (success)
                {
                        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);
-                               break;
+                               return true;
                        }
                        else
                        {
@@ -878,9 +922,10 @@ void NetConn_OpenServerPort(const char *addressstring, int defaultport)
                {
                        Con_Printf("Server unable to parse address %s\n", addressstring);
                        // if it cant parse one address, it wont be able to parse another for sure
-                       break;
+                       return false;
                }
        }
+       return false;
 }
 
 void NetConn_OpenServerPorts(int opennetports)
@@ -895,11 +940,11 @@ void NetConn_OpenServerPorts(int opennetports)
        if (sv_netport.integer != port)
                Cvar_SetValueQuick(&sv_netport, port);
        if (cls.state != ca_dedicated)
-               NetConn_OpenServerPort("local:1", 0);
+               NetConn_OpenServerPort(NULL, LHNETADDRESSTYPE_LOOP, 1, 1);
        if (opennetports)
        {
-               NetConn_OpenServerPort(net_address.string, port);
-               //NetConn_OpenServerPort(net_address_ipv6.string, port);
+               qboolean ip4success = NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
+               NetConn_OpenServerPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port, ip4success ? 1 : 100);
        }
        if (sv_numsockets == 0)
                Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
@@ -1311,16 +1356,6 @@ static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *address
                if (serverlist_consoleoutput)
                        Con_Printf("querying %s\n", addressstring);
                ++serverlist_cachecount;
-
-#if 0
-               // we should not NEED this part...
-               text = net_slist_favorites.string;
-               while(COM_ParseToken_Console(&text))
-               {
-                       if(!strcmp(com_token, addressstring))
-                               entry->isfavorite = 1;
-               }
-#endif
        }
        // if this is the first reply from this server, count it as having replied
        pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
@@ -1345,7 +1380,18 @@ static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
        serverlist_info_t *info = &entry->info;
        // update description strings for engine menu and console output
        dpsnprintf(entry->line1, sizeof(serverlist_cache[n].line1), "^%c%5d^7 ^%c%3u^7/%3u %-65.65s", info->ping >= 300 ? '1' : (info->ping >= 200 ? '3' : '7'), (int)info->ping, ((info->numhumans > 0 && info->numhumans < info->maxplayers) ? (info->numhumans >= 4 ? '7' : '3') : '1'), info->numplayers, info->maxplayers, info->name);
-       dpsnprintf(entry->line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game, (info->gameversion != gameversion.integer) ? '1' : '4', info->mod, info->map);
+       dpsnprintf(entry->line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game,
+                       (
+                        info->gameversion != gameversion.integer
+                        &&
+                        !(
+                                   gameversion_min.integer >= 0 // min/max range set by user/mod?
+                                && gameversion_max.integer >= 0
+                                && gameversion_min.integer >= info->gameversion // version of server in min/max range?
+                                && gameversion_max.integer <= info->gameversion
+                         )
+                       ) ? '1' : '4',
+                       info->mod, info->map);
        if (entry->query == SQS_QUERIED)
        {
                if(!serverlist_paused)
@@ -1399,6 +1445,79 @@ static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol,
        return true;
 }
 
+static void NetConn_ClientParsePacket_ServerList_ParseDPList(lhnetaddress_t *senderaddress, const unsigned char *data, int length, qboolean isextended)
+{
+       masterreplycount++;
+       if (serverlist_consoleoutput)
+               Con_Printf("received DarkPlaces %sserver list...\n", isextended ? "extended " : "");
+       while (length >= 7)
+       {
+               char ipstring [128];
+
+               // IPv4 address
+               if (data[0] == '\\')
+               {
+                       unsigned short port = data[5] * 256 + data[6];
+
+                       if (port != 0 && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF))
+                               dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%hu", data[1], data[2], data[3], data[4], port);
+
+                       // move on to next address in packet
+                       data += 7;
+                       length -= 7;
+               }
+               // IPv6 address
+               else if (data[0] == '/' && isextended && length >= 19)
+               {
+                       unsigned short port = data[17] * 256 + data[18];
+
+                       if (port != 0)
+                       {
+                               const char *ifname;
+
+                               /// \TODO: make some basic checks of the IP address (broadcast, ...)
+
+                               ifname = LHNETADDRESS_GetInterfaceName(senderaddress);
+                               if (ifname != NULL)
+                               {
+                                       dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x%%%s]:%hu",
+                                                               data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
+                                                               data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
+                                                               ifname, port);
+                               }
+                               else
+                               {
+                                       dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x]:%hu",
+                                                               data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
+                                                               data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
+                                                               port);
+                               }
+                       }
+
+                       // move on to next address in packet
+                       data += 19;
+                       length -= 19;
+               }
+               else
+               {
+                       Con_Print("Error while parsing the server list\n");
+                       break;
+               }
+
+               if (serverlist_consoleoutput && developer_networking.integer)
+                       Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
+               
+               if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
+                       break;
+               }
+
+       }
+
+       // begin or resume serverlist queries
+       serverlist_querysleep = false;
+       serverlist_querywaittime = realtime + 3;
+}
+
 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
 {
        qboolean fromserver;
@@ -1455,7 +1574,7 @@ static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *dat
                        char rejectreason[32];
                        cls.connect_trying = false;
                        string += 7;
-                       length = max(length - 7, (int)sizeof(rejectreason) - 1);
+                       length = min(length - 7, (int)sizeof(rejectreason) - 1);
                        memcpy(rejectreason, string, length);
                        rejectreason[length] = 0;
                        M_Update_Return_Reason(rejectreason);
@@ -1559,26 +1678,15 @@ static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *dat
                        // Extract the IP addresses
                        data += 18;
                        length -= 18;
-                       masterreplycount++;
-                       if (serverlist_consoleoutput)
-                               Con_Print("received DarkPlaces 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)
-                       {
-                               dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], data[5] * 256 + data[6]);
-                               if (serverlist_consoleoutput && developer_networking.integer)
-                                       Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
-                               
-                               if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
-                                       break;
-                               }
-
-                               // move on to next address in packet
-                               data += 7;
-                               length -= 7;
-                       }
-                       // begin or resume serverlist queries
-                       serverlist_querysleep = false;
-                       serverlist_querywaittime = realtime + 3;
+                       NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
+                       return true;
+               }
+               if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
+               {
+                       // Extract the IP addresses
+                       data += 21;
+                       length -= 21;
+                       NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
                        return true;
                }
                if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
@@ -1765,6 +1873,12 @@ static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *dat
 
                        NetConn_ClientParsePacket_ServerList_UpdateCache(n);
 
+                       break;
+               case CCREP_RCON: // RocketGuy: ProQuake rcon support
+                       if (developer.integer >= 10)
+                               Con_Printf("Datagram_ParseConnectionless: received CCREP_RCON from %s.\n", addressstring2);
+
+                       Con_Printf("%s\n", MSG_ReadString());
                        break;
                case CCREP_PLAYER_INFO:
                        // we got a CCREP_PLAYER_INFO??
@@ -1945,12 +2059,13 @@ static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
        buffer[i] = 0;
 }
 
-// (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
+/// (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
 {
-       const char *qcstatus = NULL;
+       char qcstatus[256];
        unsigned int nb_clients = 0, nb_bots = 0, i;
        int length;
+       char teambuf[3];
 
        SV_VM_Begin();
 
@@ -1965,6 +2080,7 @@ static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg
                }
        }
 
+       *qcstatus = 0;
        if(prog->globaloffsets.worldstatus >= 0)
        {
                const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
@@ -1972,15 +2088,15 @@ static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg
                {
                        char *p;
                        const char *q;
-                       qcstatus = p = Mem_Alloc(tempmempool, strlen(str) + 1);
+                       p = qcstatus;
                        for(q = str; *q; ++q)
-                               if(*q != '\\')
+                               if(*q != '\\' && *q != '\n')
                                        *p++ = *q;
                        *p = 0;
                }
        }
 
-       // TODO: we should add more information for the full status string
+       /// \TODO: we should add more information for the full status string
        length = dpsnprintf(out_msg, out_size,
                                                "\377\377\377\377%s\x0A"
                                                "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
@@ -1991,16 +2107,10 @@ static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg
                                                fullstatus ? "statusResponse" : "infoResponse",
                                                gamename, com_modname, gameversion.integer, svs.maxclients,
                                                nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
-                                               qcstatus ? "\\qcstatus\\" : "", qcstatus ? qcstatus : "",
+                                               *qcstatus ? "\\qcstatus\\" : "", qcstatus,
                                                challenge ? "\\challenge\\" : "", challenge ? challenge : "",
                                                fullstatus ? "\n" : "");
 
-       if(qcstatus)
-       {
-               Mem_Free((char *)qcstatus);
-               qcstatus = NULL;
-       }
-
        // Make sure it fits in the buffer
        if (length < 0)
                goto bad;
@@ -2038,6 +2148,7 @@ static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg
                                                        break;
                                        }
                                } while (curchar != '\0');
+                               cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
 
                                pingvalue = (int)(cl->ping * 1000.0f);
                                if(cl->netconnection)
@@ -2045,6 +2156,7 @@ static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg
                                else
                                        pingvalue = 0;
 
+                               *qcstatus = 0;
                                if(prog->fieldoffsets.clientstatus >= 0)
                                {
                                        const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
@@ -2052,27 +2164,44 @@ static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg
                                        {
                                                char *p;
                                                const char *q;
-                                               qcstatus = p = Mem_Alloc(tempmempool, strlen(str) + 1);
-                                               for(q = str; *q; ++q)
-                                                       if(*q != '\\' && *q != ' ')
+                                               p = qcstatus;
+                                               for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
+                                                       if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
                                                                *p++ = *q;
                                                *p = 0;
                                        }
                                }
 
-                               if(qcstatus)
+                               if ((gamemode == GAME_NEXUIZ) && (teamplay.integer > 0))
                                {
-                                       length = dpsnprintf(ptr, left, "%s %d \"%s\"\n",
+                                       if(cl->frags == -666) // spectator
+                                               strlcpy(teambuf, " 0", sizeof(teambuf));
+                                       else if(cl->colors == 0x44) // red team
+                                               strlcpy(teambuf, " 1", sizeof(teambuf));
+                                       else if(cl->colors == 0xDD) // blue team
+                                               strlcpy(teambuf, " 2", sizeof(teambuf));
+                                       else if(cl->colors == 0xCC) // yellow team
+                                               strlcpy(teambuf, " 3", sizeof(teambuf));
+                                       else if(cl->colors == 0x99) // pink team
+                                               strlcpy(teambuf, " 4", sizeof(teambuf));
+                                       else
+                                               strlcpy(teambuf, " 0", sizeof(teambuf));
+                               }
+                               else
+                                       *teambuf = 0;
+
+                               // note: team number is inserted according to SoF2 protocol
+                               if(*qcstatus)
+                                       length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
                                                                                qcstatus,
                                                                                pingvalue,
+                                                                               teambuf,
                                                                                cleanname);
-                                       Mem_Free((char *)qcstatus);
-                                       qcstatus = NULL;
-                               }
                                else
-                                       length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
+                                       length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
                                                                                cl->frags,
                                                                                pingvalue,
+                                                                               teambuf,
                                                                                cleanname);
 
                                if(length < 0)
@@ -2158,16 +2287,39 @@ void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
        }
 }
 
-// returns a string describing the user level, or NULL for auth failure
-const char *RCon_Authenticate(const char *password, const char *s, const char *endpos)
+typedef qboolean (*rcon_matchfunc_t) (const char *password, const char *hash, const char *s, int slen);
+
+qboolean hmac_mdfour_matching(const char *password, const char *hash, const char *s, int slen)
+{
+       char mdfourbuf[16];
+       long t1, t2;
+
+       t1 = (long) time(NULL);
+       t2 = strtol(s, NULL, 0);
+       if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
+               return false;
+
+       if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
+               return false;
+
+       return !memcmp(mdfourbuf, hash, 16);
+}
+
+qboolean plaintext_matching(const char *password, const char *hash, const char *s, int slen)
+{
+       return !strcmp(password, hash);
+}
+
+/// returns a string describing the user level, or NULL for auth failure
+const char *RCon_Authenticate(const char *password, const char *s, const char *endpos, rcon_matchfunc_t comparator, const char *cs, int cslen)
 {
        const char *text;
        qboolean hasquotes;
 
-       if(!strcmp(rcon_password.string, password))
+       if(comparator(rcon_password.string, password, cs, cslen))
                return "rcon";
        
-       if(strcmp(rcon_restricted_password.string, password))
+       if(!comparator(rcon_restricted_password.string, password, cs, cslen))
                return NULL;
 
        for(text = s; text != endpos; ++text)
@@ -2215,6 +2367,44 @@ match:
        return "restricted rcon";
 }
 
+void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos)
+{
+       if(userlevel)
+       {
+               // looks like a legitimate rcon command with the correct password
+               const char *s_ptr = s;
+               Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
+               while(s_ptr != endpos)
+               {
+                       size_t l = strlen(s_ptr);
+                       if(l)
+                               Con_Printf(" %s;", s_ptr);
+                       s_ptr += l + 1;
+               }
+               Con_Printf("\n");
+
+               if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
+                       Con_Rcon_Redirect_Init(mysocket, peeraddress);
+               while(s != endpos)
+               {
+                       size_t l = strlen(s);
+                       if(l)
+                       {
+                               client_t *host_client_save = host_client;
+                               Cmd_ExecuteString(s, src_command);
+                               host_client = host_client_save;
+                               // in case it is a command that changes host_client (like restart)
+                       }
+                       s += l + 1;
+               }
+               Con_Rcon_Redirect_End();
+       }
+       else
+       {
+               Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
+       }
+}
+
 extern void SV_SendServerinfo (client_t *client);
 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
 {
@@ -2294,7 +2484,7 @@ static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *dat
                                return true;
 
                        // check engine protocol
-                       if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
+                       if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
                        {
                                if (developer.integer >= 10)
                                        Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
@@ -2393,12 +2583,31 @@ static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *dat
                        }
                        return true;
                }
+               if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
+               {
+                       char *password = string + 20;
+                       char *timeval = string + 37;
+                       char *s = strchr(timeval, ' ');
+                       char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
+                       const char *userlevel;
+                       if(!s)
+                               return true; // invalid packet
+                       ++s;
+
+                       userlevel = RCon_Authenticate(password, s, endpos, hmac_mdfour_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
+                       RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
+                       return true;
+               }
                if (length >= 5 && !memcmp(string, "rcon ", 5))
                {
                        int i;
                        char *s = string + 5;
                        char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
                        char password[64];
+
+                       if(rcon_secure.integer)
+                               return true;
+
                        for (i = 0;!ISWHITESPACE(*s);s++)
                                if (i < (int)sizeof(password) - 1)
                                        password[i++] = *s;
@@ -2407,41 +2616,8 @@ static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *dat
                        password[i] = 0;
                        if (!ISWHITESPACE(password[0]))
                        {
-                               const char *userlevel = RCon_Authenticate(password, s, endpos);
-                               if(userlevel)
-                               {
-                                       // looks like a legitimate rcon command with the correct password
-                                       char *s_ptr = s;
-                                       Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
-                                       while(s_ptr != endpos)
-                                       {
-                                               size_t l = strlen(s_ptr);
-                                               if(l)
-                                                       Con_Printf(" %s;", s_ptr);
-                                               s_ptr += l + 1;
-                                       }
-                                       Con_Printf("\n");
-
-                                       if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
-                                               Con_Rcon_Redirect_Init(mysocket, peeraddress);
-                                       while(s != endpos)
-                                       {
-                                               size_t l = strlen(s);
-                                               if(l)
-                                               {
-                                                       client_t *host_client_save = host_client;
-                                                       Cmd_ExecuteString(s, src_command);
-                                                       host_client = host_client_save;
-                                                       // in case it is a command that changes host_client (like restart)
-                                               }
-                                               s += l + 1;
-                                       }
-                                       Con_Rcon_Redirect_End();
-                               }
-                               else
-                               {
-                                       Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
-                               }
+                               const char *userlevel = RCon_Authenticate(password, s, endpos, plaintext_matching, NULL, 0);
+                               RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
                        }
                        return true;
                }
@@ -2718,12 +2894,10 @@ void NetConn_SleepMicroseconds(int microseconds)
 
 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
 {
-       int i;
+       int i, j;
        int masternum;
        lhnetaddress_t masteraddress;
        lhnetaddress_t broadcastaddress;
-       lhnetaddress_t serveraddress;
-       const char *text;
        char request[256];
 
        if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
@@ -2740,6 +2914,7 @@ void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
                {
                        if (cl_sockets[i])
                        {
+                               const char *cmdname, *extraoptions;
                                int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
 
                                if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
@@ -2760,7 +2935,17 @@ void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
                                }
 
                                // build the getservers message to send to the dpmaster master servers
-                               dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
+                               if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
+                               {
+                                       cmdname = "getserversExt";
+                                       extraoptions = " ipv4 ipv6";  // ask for IPv4 and IPv6 servers
+                               }
+                               else
+                               {
+                                       cmdname = "getservers";
+                                       extraoptions = "";
+                               }
+                               dpsnprintf(request, sizeof(request), "\377\377\377\377%s %s %u empty full%s", cmdname, gamename, NET_PROTOCOL_VERSION, extraoptions);
 
                                // search internet
                                for (masternum = 0;sv_masters[masternum].name;masternum++)
@@ -2773,12 +2958,12 @@ void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
                                }
 
                                // search favorite servers
-                               text = net_slist_favorites.string;
-                               while(COM_ParseToken_Console(&text))
+                               for(j = 0; j < nFavorites; ++j)
                                {
-                                       if(LHNETADDRESS_FromString(&serveraddress, com_token, 26000) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
+                                       if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
                                        {
-                                               NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, com_token, true );
+                                               if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
+                                                       NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
                                        }
                                }
                        }
@@ -2821,16 +3006,15 @@ void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
                                }
 
                                // search favorite servers
-                               text = net_slist_favorites.string;
-                               while(COM_ParseToken_Console(&text))
+                               for(j = 0; j < nFavorites; ++j)
                                {
-                                       if(LHNETADDRESS_FromString(&serveraddress, com_token, 26000) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
+                                       if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
                                        {
-                                               // writing AND querying to catch replies for both
-                                               // protocols (in case DP has been queried above, this
-                                               // would only try the DP protocol otherwise)
-                                               NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &serveraddress);
-                                               NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, com_token, true );
+                                               if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
+                                               {
+                                                       NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
+                                                       NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
+                                               }
                                        }
                                }
                        }
@@ -2956,6 +3140,7 @@ void NetConn_Init(void)
        Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
        Cvar_RegisterVariable(&rcon_restricted_password);
        Cvar_RegisterVariable(&rcon_restricted_commands);
+       Cvar_RegisterVariable(&rcon_secure_maxdiff);
        Cvar_RegisterVariable(&net_slist_queriespersecond);
        Cvar_RegisterVariable(&net_slist_queriesperframe);
        Cvar_RegisterVariable(&net_slist_timeout);
@@ -2973,12 +3158,14 @@ void NetConn_Init(void)
        Cvar_RegisterVariable(&cl_netport);
        Cvar_RegisterVariable(&sv_netport);
        Cvar_RegisterVariable(&net_address);
-       //Cvar_RegisterVariable(&net_address_ipv6);
+       Cvar_RegisterVariable(&net_address_ipv6);
        Cvar_RegisterVariable(&sv_public);
        Cvar_RegisterVariable(&sv_heartbeatperiod);
        for (i = 0;sv_masters[i].name;i++)
                Cvar_RegisterVariable(&sv_masters[i]);
        Cvar_RegisterVariable(&gameversion);
+       Cvar_RegisterVariable(&gameversion_min);
+       Cvar_RegisterVariable(&gameversion_max);
 // 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.
        if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
        {