Exemplo n.º 1
0
  TEST(Session, ClientsServers)
  {
    Timer::GetInstance().UseVirtualTime();
    ConnectionManager::UseTimer = false;
    OverlayNetwork net = ConstructOverlay(10, 20);
    VerifyStoppedNetwork(net);
    StartNetwork(net);
    VerifyNetwork(net);

    Sessions sessions = BuildSessions(net);
    qDebug() << "Starting sessions...";
    StartSessions(sessions);
    StartRound(sessions);
    SendTest(sessions);
    SendTest(sessions);
    DisconnectServer(sessions, true);
    SendTest(sessions);
    DisconnectServer(sessions, false);
    SendTest(sessions);
    SendTest(sessions);
    StopSessions(sessions);

    StopNetwork(sessions.network);
    VerifyStoppedNetwork(sessions.network);
    ConnectionManager::UseTimer = true;
  }
Exemplo n.º 2
0
vzsdk::VzConnectDev::~VzConnectDev() {
    DisconnectServer();
}
Exemplo n.º 3
0
static void HailExec(AgentConnection *conn, char *peer, char *recvbuffer, char *sendbuffer)
{
    FILE *fp = stdout;
    char *sp;
    int n_read;

    if (strlen(DEFINECLASSES))
    {
        snprintf(sendbuffer, CF_BUFSIZE, "EXEC %s -D%s", REMOTE_AGENT_OPTIONS, DEFINECLASSES);
    }
    else
    {
        snprintf(sendbuffer, CF_BUFSIZE, "EXEC %s", REMOTE_AGENT_OPTIONS);
    }

    if (SendTransaction(conn->sd, sendbuffer, 0, CF_DONE) == -1)
    {
        CfOut(cf_error, "send", "Transmission rejected");
        DisconnectServer(conn);
        return;
    }

    fp = NewStream(peer);
    SendClassData(conn);

    while (true)
    {
        memset(recvbuffer, 0, CF_BUFSIZE);

        if ((n_read = ReceiveTransaction(conn->sd, recvbuffer, NULL)) == -1)
        {
            return;
        }

        if (n_read == 0)
        {
            break;
        }

        if (strlen(recvbuffer) == 0)
        {
            continue;
        }

        if ((sp = strstr(recvbuffer, CFD_TERMINATOR)) != NULL)
        {
            fprintf(fp, "%s> !!\n\n", VPREFIX);
            break;
        }

        if ((sp = strstr(recvbuffer, "BAD:")) != NULL)
        {
            fprintf(fp, "%s> !! %s\n", VPREFIX, recvbuffer + 4);
            continue;
        }

        if (strstr(recvbuffer, "too soon"))
        {
            fprintf(fp, "%s> !! %s\n", VPREFIX, recvbuffer);
            continue;
        }

        fprintf(fp, "%s> -> %s", VPREFIX, recvbuffer);
    }

    DeleteStream(fp);
    DisconnectServer(conn);
}
Exemplo n.º 4
0
static int HailServer(char *host, Attributes a, Promise *pp)
{
    AgentConnection *conn;
    char sendbuffer[CF_BUFSIZE], recvbuffer[CF_BUFSIZE], peer[CF_MAXVARSIZE], ipv4[CF_MAXVARSIZE],
        digest[CF_MAXVARSIZE], user[CF_SMALLBUF];
    bool gotkey;
    char reply[8];

    a.copy.portnumber = (short) ParseHostname(host, peer);

    snprintf(ipv4, CF_MAXVARSIZE, "%s", Hostname2IPString(peer));
    Address2Hostkey(ipv4, digest);
    GetCurrentUserName(user, CF_SMALLBUF);

    if (INTERACTIVE)
    {
        CfOut(cf_verbose, "", " -> Using interactive key trust...\n");

        gotkey = HavePublicKey(user, peer, digest) != NULL;

        if (!gotkey)
        {
            gotkey = HavePublicKey(user, ipv4, digest) != NULL;
        }

        if (!gotkey)
        {
            printf("WARNING - You do not have a public key from host %s = %s\n", host, ipv4);
            printf("          Do you want to accept one on trust? (yes/no)\n\n--> ");

            while (true)
            {
                if (fgets(reply, 8, stdin) == NULL)
                {
                    FatalError("EOF trying to read answer from terminal");
                }

                if (Chop(reply, CF_EXPANDSIZE) == -1)
                {
                    CfOut(cf_error, "", "Chop was called on a string that seemed to have no terminator");
                }

                if (strcmp(reply, "yes") == 0)
                {
                    printf(" -> Will trust the key...\n");
                    a.copy.trustkey = true;
                    break;
                }
                else if (strcmp(reply, "no") == 0)
                {
                    printf(" -> Will not trust the key...\n");
                    a.copy.trustkey = false;
                    break;
                }
                else
                {
                    printf(" !! Please reply yes or no...(%s)\n", reply);
                }
            }
        }
    }

/* Continue */

#ifdef __MINGW32__

    CfOut(cf_inform, "", "...........................................................................\n");
    CfOut(cf_inform, "", " * Hailing %s : %u, with options \"%s\" (serial)\n", peer, a.copy.portnumber,
          REMOTE_AGENT_OPTIONS);
    CfOut(cf_inform, "", "...........................................................................\n");

#else /* !__MINGW32__ */

    if (BACKGROUND)
    {
        CfOut(cf_inform, "", "Hailing %s : %u, with options \"%s\" (parallel)\n", peer, a.copy.portnumber,
              REMOTE_AGENT_OPTIONS);
    }
    else
    {
        CfOut(cf_inform, "", "...........................................................................\n");
        CfOut(cf_inform, "", " * Hailing %s : %u, with options \"%s\" (serial)\n", peer, a.copy.portnumber,
              REMOTE_AGENT_OPTIONS);
        CfOut(cf_inform, "", "...........................................................................\n");
    }

#endif /* !__MINGW32__ */

    a.copy.servers = SplitStringAsRList(peer, '*');

    if (a.copy.servers == NULL || strcmp(a.copy.servers->item, "localhost") == 0)
    {
        cfPS(cf_inform, CF_NOP, "", pp, a, "No hosts are registered to connect to");
        return false;
    }
    else
    {
        conn = NewServerConnection(a, pp);

        if (conn == NULL)
        {
            DeleteRlist(a.copy.servers);
            CfOut(cf_verbose, "", " -> No suitable server responded to hail\n");
            return false;
        }
    }

/* Check trust interaction*/

    pp->cache = NULL;

    if (strlen(MENU) > 0)
    {
#if defined(HAVE_NOVA)
        if (!Nova_ExecuteRunagent(conn, MENU))
        {
            DisconnectServer(conn);
            DeleteRlist(a.copy.servers);
            return false;
        }
#endif
    }
    else
    {
        HailExec(conn, peer, recvbuffer, sendbuffer);
    }

    DeleteRlist(a.copy.servers);

    return true;
}
Exemplo n.º 5
0
static void HailExec(AgentConnection *conn, char *peer, char *recvbuffer, char *sendbuffer)
{
    if (DEFINECLASSES[0] != '\0')
    {
        snprintf(sendbuffer, CF_BUFSIZE, "EXEC -D%s", DEFINECLASSES);
    }
    else
    {
        snprintf(sendbuffer, CF_BUFSIZE, "EXEC");
    }

    if (SendTransaction(conn->conn_info, sendbuffer, 0, CF_DONE) == -1)
    {
        Log(LOG_LEVEL_ERR, "Transmission rejected. (send: %s)", GetErrorStr());
        DisconnectServer(conn);
        return;
    }

    /* TODO we are sending class data right after EXEC, when the server might
     * have already rejected us with BAD reply. So this class data with the
     * CFD_TERMINATOR will be interpreted by the server as a new, bogus
     * protocol command, and the server will complain. */
    SendClassData(conn);

    FILE *fp = NewStream(peer);
    while (true)
    {
        memset(recvbuffer, 0, CF_BUFSIZE);

        int n_read = ReceiveTransaction(conn->conn_info, recvbuffer, NULL);

        if (n_read == -1)
        {
            break;
        }
        if (n_read == 0)                               /* connection closed */
        {
            break;
        }
        if (strncmp(recvbuffer, CFD_TERMINATOR, strlen(CFD_TERMINATOR)) == 0)
        {
            break;
        }

        const size_t recv_len = strlen(recvbuffer);
        const char   *ipaddr  = conn->remoteip;

        if (strncmp(recvbuffer, "BAD:", 4) == 0)
        {
            fprintf(fp, "%s> !! %s\n", ipaddr, recvbuffer + 4);
        }
        /* cf-serverd >= 3.7 quotes command output with "> ". */
        else if (strncmp(recvbuffer, "> ", 2) == 0)
        {
            fprintf(fp, "%s> -> %s", ipaddr, &recvbuffer[2]);
        }
        else
        {
            fprintf(fp, "%s> %s", ipaddr, recvbuffer);
        }

        if (recv_len > 0 && recvbuffer[recv_len - 1] != '\n')
        {
            /* We'll be printing double newlines here with new cf-serverd
             * versions, so check for already trailing newlines. */
            /* TODO deprecate this path in a couple of versions. cf-serverd is
             * supposed to munch the newlines so we must always append one. */
            fputc('\n', fp);
        }
    }

    if (fp != stdout)
    {
        fclose(fp);
    }
    DisconnectServer(conn);
}
Exemplo n.º 6
0
void Cleanup(void) {
	DisconnectServer();
	FreeHandles();
}
Exemplo n.º 7
0
static AgentConnection *ServerConnection(const char *server, FileCopy fc, int *err)
{
    AgentConnection *conn;
    *err = 0;

#if !defined(__MINGW32__)
    signal(SIGPIPE, SIG_IGN);
#endif /* !__MINGW32__ */

#if !defined(__MINGW32__)
    static sigset_t signal_mask;
    sigemptyset(&signal_mask);
    sigaddset(&signal_mask, SIGPIPE);
    pthread_sigmask(SIG_BLOCK, &signal_mask, NULL);
#endif

    conn = NewAgentConn(server);

    if (strcmp(server, "localhost") == 0)
    {
        conn->authenticated = true;
        return conn;
    }

    conn->authenticated = false;
    conn->encryption_type = CfEnterpriseOptions();

/* username of the client - say root from Windows */

#ifdef __MINGW32__
    snprintf(conn->username, CF_SMALLBUF, "root");
#else
    GetCurrentUserName(conn->username, CF_SMALLBUF);
#endif /* !__MINGW32__ */

    if (conn->sd == SOCKET_INVALID)
    {
        if (!ServerConnect(conn, server, fc))
        {
            Log(LOG_LEVEL_INFO, "No server is responding on this port");

            DisconnectServer(conn);

            *err = -1;
            return NULL;
        }

        if (conn->sd < 0)                      /* INVALID or OFFLINE socket */
        {
            UnexpectedError("ServerConnect() succeeded but socket descriptor is %d!",
                            conn->sd);
            *err = -1;
            return NULL;
        }

        if (!IdentifyAgent(conn->sd))
        {
            Log(LOG_LEVEL_ERR, "Id-authentication for '%s' failed", VFQNAME);
            errno = EPERM;
            DisconnectServer(conn);
            *err = -2; // auth err
            return NULL;
        }

        if (!AuthenticateAgent(conn, fc.trustkey))
        {
            Log(LOG_LEVEL_ERR, "Authentication dialogue with '%s' failed", server);
            errno = EPERM;
            DisconnectServer(conn);
            *err = -2; // auth err
            return NULL;
        }

        conn->authenticated = true;
        return conn;
    }

    return conn;
}
Exemplo n.º 8
0
static void HailExec(AgentConnection *conn, char *peer)
{
    char sendbuf[CF_BUFSIZE - CF_INBAND_OFFSET] = "EXEC";
    size_t sendbuf_len = strlen(sendbuf);

    if (!NULL_OR_EMPTY(DEFINECLASSES))
    {
        StrCat(sendbuf, sizeof(sendbuf), &sendbuf_len, " -D", 0);
        StrCat(sendbuf, sizeof(sendbuf), &sendbuf_len, DEFINECLASSES, 0);
    }
    if (!NULL_OR_EMPTY(REMOTEBUNDLES))
    {
        StrCat(sendbuf, sizeof(sendbuf), &sendbuf_len, " -b ", 0);
        StrCat(sendbuf, sizeof(sendbuf), &sendbuf_len, REMOTEBUNDLES, 0);
    }

    if (sendbuf_len >= sizeof(sendbuf))
    {
        Log(LOG_LEVEL_ERR, "Command longer than maximum transaction packet");
        DisconnectServer(conn);
        return;
    }

    if (SendTransaction(conn->conn_info, sendbuf, 0, CF_DONE) == -1)
    {
        Log(LOG_LEVEL_ERR, "Transmission rejected. (send: %s)", GetErrorStr());
        DisconnectServer(conn);
        return;
    }

    /* TODO we are sending class data right after EXEC, when the server might
     * have already rejected us with BAD reply. So this class data with the
     * CFD_TERMINATOR will be interpreted by the server as a new, bogus
     * protocol command, and the server will complain. */
    SendClassData(conn);

    char recvbuffer[CF_BUFSIZE];
    FILE *fp = NewStream(peer);
    while (true)
    {
        memset(recvbuffer, 0, sizeof(recvbuffer));

        if (ReceiveTransaction(conn->conn_info, recvbuffer, NULL) == -1)
        {
            break;
        }
        if (strncmp(recvbuffer, CFD_TERMINATOR, strlen(CFD_TERMINATOR)) == 0)
        {
            break;
        }

        const size_t recv_len = strlen(recvbuffer);
        const char   *ipaddr  = conn->remoteip;

        if (strncmp(recvbuffer, "BAD:", 4) == 0)
        {
            fprintf(fp, "%s> !! %s\n", ipaddr, recvbuffer + 4);
        }
        /* cf-serverd >= 3.7 quotes command output with "> ". */
        else if (strncmp(recvbuffer, "> ", 2) == 0)
        {
            fprintf(fp, "%s> -> %s", ipaddr, &recvbuffer[2]);
        }
        else
        {
            fprintf(fp, "%s> %s", ipaddr, recvbuffer);
        }

        if (recv_len > 0 && recvbuffer[recv_len - 1] != '\n')
        {
            /* We'll be printing double newlines here with new cf-serverd
             * versions, so check for already trailing newlines. */
            /* TODO deprecate this path in a couple of versions. cf-serverd is
             * supposed to munch the newlines so we must always append one. */
            fputc('\n', fp);
        }
    }

    if (fp != stdout)
    {
        fclose(fp);
    }
    DisconnectServer(conn);
}
bool MMG_TrackableServer::HandleMessage(SvClient *aClient, MN_ReadMessage *aMessage, MMG_ProtocolDelimiters::Delimiter aDelimiter)
{
	MN_WriteMessage	responseMessage(2048);

	//
	// All dedicated sever packets require an authenticated connection, except
	// for the initial auth delimiter
	//
	auto server = FindServer(aClient);

	if (!server &&
		aDelimiter != MMG_ProtocolDelimiters::SERVERTRACKER_SERVER_AUTH_DS_CONNECTION)
	{
		// Unauthed messages ignored
		return false;
	}

	// Handle all message types and disconnect the server on any errors
	switch(aDelimiter)
	{
		// Ping/pong handler
		case MMG_ProtocolDelimiters::MESSAGING_DS_PING:
		{
			DebugLog(L_INFO, "MESSAGING_DS_PING:");
			ushort protocolVersion;// MassgateProtocolVersion
			uint publicServerId;   // Server ID sent on SERVERTRACKER_SERVER_STARTED

			if (!aMessage->ReadUShort(protocolVersion))
				return false;

			if (!aMessage->ReadUInt(publicServerId))
				return false;

			//if (aProtocolVersion != MassgateProtocolVersion)
			//	return false;

			if (publicServerId != server->m_PublicId)
			{
				DisconnectServer(aClient);
				return false;
			}

			// Pong!
			responseMessage.WriteDelimiter(MMG_ProtocolDelimiters::MESSAGING_DS_PONG);

			if (!aClient->SendData(&responseMessage))
				return false;
		}
		break;

		case MMG_ProtocolDelimiters::MESSAGING_DS_SET_METRICS:
		{
			DebugLog(L_INFO, "MESSAGING_DS_SET_METRICS:");

			uchar metricContext;
			uint metricCount;

			if (!aMessage->ReadUChar(metricContext) || !aMessage->ReadUInt(metricCount))
				return false;

			for (uint i = 0; i < metricCount; i++)
			{
				char key[256];
				char value[256];

				if (!aMessage->ReadString(key, ARRAYSIZE(key)))
					return false;

				if (!aMessage->ReadString(value, ARRAYSIZE(value)))
					return false;

				DebugLog(L_INFO, "Metric [%u]: %s -- %s", (uint)metricContext, key, value);
			}
		}
		break;

		case MMG_ProtocolDelimiters::MESSAGING_DS_INFORM_PLAYER_JOINED:
		{
			DebugLog(L_INFO, "MESSAGING_DS_INFORM_PLAYER_JOINED:");

			uint profileId;
			uint antiSpoofToken;

			if (!aMessage->ReadUInt(profileId) || !aMessage->ReadUInt(antiSpoofToken))
				return false;

#ifdef USING_MYSQL_DATABASE
			SvClient *player = SvClientManager::ourInstance->FindPlayerByProfileId(profileId);

			// if profileId not logged in, kick profileId
			if (!player)
			{
				DebugLog(L_INFO, "MESSAGING_DS_KICK_PLAYER:");
				responseMessage.WriteDelimiter(MMG_ProtocolDelimiters::MESSAGING_DS_KICK_PLAYER);
				responseMessage.WriteUInt(profileId);

				if (!aClient->SendData(&responseMessage))
					return false;
			}
			else
			{
				//if antispooftoken does not match the generated token from ACCOUNT_AUTH_ACCOUNT_REQ, then kick profileId
				MMG_AuthToken *authtoken = player->GetToken();

				// TODO
				if (authtoken->m_TokenId != antiSpoofToken)
				{
					DebugLog(L_INFO, "MESSAGING_DS_KICK_PLAYER:");
					responseMessage.WriteDelimiter(MMG_ProtocolDelimiters::MESSAGING_DS_KICK_PLAYER);
					responseMessage.WriteUInt(profileId);

					if (!aClient->SendData(&responseMessage))
						return false;
				}
			}
#endif
		}
		break;
		
		// List of banned words in chat
		case MMG_ProtocolDelimiters::MESSAGING_DS_GET_BANNED_WORDS_REQ:
		{
			DebugLog(L_INFO, "MESSAGING_DS_GET_BANNED_WORDS_REQ:");
		}
		break;

		// Initial message from any server that wants to connect to Massgate
		case MMG_ProtocolDelimiters::SERVERTRACKER_SERVER_AUTH_DS_CONNECTION:
		{
			DebugLog(L_INFO, "SERVERTRACKER_SERVER_AUTH_DS_CONNECTION:");

			ushort protocolVersion;// MassgateProtocolVersion
			uint keySequenceNumber;// See EncryptionKeySequenceNumber in MMG_AccountProtocol
			
			if (!aMessage->ReadUShort(protocolVersion))
				return false;
			
			if (!aMessage->ReadUInt(keySequenceNumber))
				return false;

			// Drop immediately if key not valid
			if (!AuthServer(aClient, keySequenceNumber, protocolVersion))
			{
				DebugLog(L_INFO, "Failed to authenticate server");
				return false;
			}

			// If a valid sequence was supplied, ask for the "encrypted" quiz answer. This is set to 0
			// if no cdkey is used (unranked).
			if (keySequenceNumber != 0)
			{
				responseMessage.WriteDelimiter(MMG_ProtocolDelimiters::SERVERTRACKER_SERVER_QUIZ_FROM_MASSGATE);
				responseMessage.WriteUInt(12345678);// Quiz seed

				if (!aClient->SendData(&responseMessage))
					return false;
			}
		}
		break;

		// Encrypted quiz answer response from the dedicated server when using a cdkey
		case MMG_ProtocolDelimiters::SERVERTRACKER_SERVER_QUIZ_ANSWERS_TO_MASSGATE:
		{
			DebugLog(L_INFO, "SERVERTRACKER_SERVER_QUIZ_ANSWERS_TO_MASSGATE:");

			// quizAnswer = quizSeed
			//
			// MMG_BlockTEA::SetKey(CDKeyEncryptionKey);
			// MMG_BlockTEA::Decrypt(&quizAnswer, 4);
			// quizAnswer = (quizAnswer >> 16) | 65183 * quizAnswer;
			// MMG_BlockTEA::Encrypt(&quizAnswer, 4);

			uint quizAnswer;
			if (!aMessage->ReadUInt(quizAnswer))
				return false;
		}
		break;

		case MMG_ProtocolDelimiters::SERVERTRACKER_SERVER_REPORT_PLAYER_STATS:
		{
			DebugLog(L_INFO, "SERVERTRACKER_SERVER_REPORT_PLAYER_STATS:");

			uint statCount;
			uint64 mapHash;
			MMG_Stats::PlayerMatchStats playerStats[100];
			uint profileIds[100];
			memset(profileIds, 0, sizeof(profileIds));

			time_t local_timestamp = time(NULL);
			uint datematchplayed = (uint)local_timestamp;

			if (!aMessage->ReadUInt(statCount) || !aMessage->ReadUInt64(mapHash))
				return false;

			DebugLog(L_INFO, "Number of player statistics to read from packet: %u", statCount);

			for (uint i = 0; i < statCount; i++)
			{
				if (!playerStats[i].FromStream(aMessage))
					return false;

				profileIds[i] = playerStats[i].m_ProfileId;
			}

			DebugLog(L_INFO, "Read Packet: OK");

			if (!MySQLDatabase::ourInstance->ProcessMatchStatistics(datematchplayed, statCount, playerStats))
			{
				DebugLog(L_INFO, "Error: ProcessMatchStatistics() failed");
				return false;
			}

			DebugLog(L_INFO, "Save Match Statistics: OK");

			if (!MySQLDatabase::ourInstance->BuildPlayerLeaderboard(datematchplayed))
			{
				DebugLog(L_INFO, "Error: BuildPlayerLeaderboard() failed");
				return false;
			}

			DebugLog(L_INFO, "Build Player Leaderboard: OK");
			
			if (!MySQLDatabase::ourInstance->CalculatePlayerRanks(statCount, profileIds))
			{
				DebugLog(L_INFO, "Error: CalculatePlayerRanks() failed");
				return false;
			}

			DebugLog(L_INFO, "Calculate Player Ranks: OK");

			if (!MySQLDatabase::ourInstance->InsertAcquaintances(datematchplayed, statCount, profileIds))
				return false;

			DebugLog(L_INFO, "Process Acquaintances: OK");
			
			DebugLog(L_INFO, "SERVERTRACKER_SERVER_REPORT_PLAYER_STATS: Completed Successfully");
		}
		break;

		// Broadcasted message when the very first map is loaded
		case MMG_ProtocolDelimiters::SERVERTRACKER_SERVER_STARTED:
		{
			DebugLog(L_INFO, "SERVERTRACKER_SERVER_STARTED:");

			MMG_ServerStartupVariables startupVars;
			if (!startupVars.FromStream(aMessage))
				return false;

			// Request to "connect" the active game server
			if (ConnectServer(server, aClient->GetIPAddress(), &startupVars))
			{
				// Tell SvClientManager
				aClient->SetIsServer(true);
				aClient->SetLoginStatus(true);
				aClient->SetTimeout(WIC_HEARTBEAT_NET_TIMEOUT);

				// Send back the assigned public ID
				responseMessage.WriteDelimiter(MMG_ProtocolDelimiters::SERVERTRACKER_SERVER_PUBLIC_ID);
				responseMessage.WriteUInt(server->m_PublicId);// ServerId

				if (!aClient->SendData(&responseMessage))
					return false;

				// Send back the connection cookie
				responseMessage.WriteDelimiter(MMG_ProtocolDelimiters::SERVERTRACKER_SERVER_INTERNAL_AUTHTOKEN);
				responseMessage.WriteRawData(&server->m_Cookie, sizeof(server->m_Cookie));// myCookie
				responseMessage.WriteUInt(10000);// myConnectCookieBase

				if (!aClient->SendData(&responseMessage))
					return false;
			}
			else
			{
				DebugLog(L_INFO, "Failed to connect server");
				DisconnectServer(aClient);
			}
		}
		break;

		// Server heartbeat sent every X seconds
		case MMG_ProtocolDelimiters::SERVERTRACKER_SERVER_STATUS:
		{
			DebugLog(L_INFO, "SERVERTRACKER_SERVER_STATUS:");

			MMG_TrackableServerHeartbeat heartbeat;
			if (!heartbeat.FromStream(aMessage))
				return false;

			if (!UpdateServer(server, &heartbeat))
				return false;
		}
		break;

		// Map rotation cycle info
		case MMG_ProtocolDelimiters::SERVERTRACKER_SERVER_MAP_LIST:
		{
			DebugLog(L_INFO, "SERVERTRACKER_SERVER_MAP_LIST:");

			ushort mapCount;
			aMessage->ReadUShort(mapCount);

			for (int i = 0; i < mapCount; i++)
			{
				uint64 mapHash;
				wchar_t mapName[128];

				aMessage->ReadUInt64(mapHash);
				aMessage->ReadString(mapName, ARRAYSIZE(mapName));

				DebugLog(L_INFO, "%llX - %ws", mapHash, mapName);
			}
		}
		break;

		default:
			DebugLog(L_WARN, "Unknown delimiter %i", aDelimiter);
		return false;
	}

	return true;
}
Exemplo n.º 10
0
/**
 * @NOTE if #flags.protocol_version is CF_PROTOCOL_UNDEFINED, then classic
 *       protocol is used by default.
 */
AgentConnection *ServerConnection(const char *server, const char *port,
                                  unsigned int connect_timeout,
                                  ConnectionFlags flags, int *err)
{
    AgentConnection *conn = NULL;
    int ret;
    *err = 0;

    conn = NewAgentConn(server, port, flags);

#if !defined(__MINGW32__)
    signal(SIGPIPE, SIG_IGN);

    sigset_t signal_mask;
    sigemptyset(&signal_mask);
    sigaddset(&signal_mask, SIGPIPE);
    pthread_sigmask(SIG_BLOCK, &signal_mask, NULL);

    /* FIXME: username is local */
    GetCurrentUserName(conn->username, sizeof(conn->username));
#else
    /* Always say "root" as username from windows. */
    strlcpy(conn->username, "root", sizeof(conn->username));
#endif

    if (port == NULL || *port == '\0')
    {
        port = CFENGINE_PORT_STR;
    }

    char txtaddr[CF_MAX_IP_LEN] = "";
    conn->conn_info->sd = SocketConnect(server, port, connect_timeout,
                                        flags.force_ipv4,
                                        txtaddr, sizeof(txtaddr));
    if (conn->conn_info->sd == -1)
    {
        Log(LOG_LEVEL_INFO, "No server is responding on port: %s",
            port);
        DisconnectServer(conn);
        *err = -1;
        return NULL;
    }

    assert(sizeof(conn->remoteip) >= sizeof(txtaddr));
    strcpy(conn->remoteip, txtaddr);

    switch (flags.protocol_version)
    {
    case CF_PROTOCOL_UNDEFINED:
    case CF_PROTOCOL_TLS:

        /* Set the version to request during protocol negotiation. After
         * TLSConnect() it will have the version we finally ended up with. */
        conn->conn_info->protocol = CF_PROTOCOL_LATEST;

        ret = TLSConnect(conn->conn_info, flags.trust_server,
                         conn->remoteip, conn->username);

        if (ret == -1)                                      /* Error */
        {
            DisconnectServer(conn);
            *err = -1;
            return NULL;
        }
        else if (ret == 0)                             /* Auth/ID error */
        {
            DisconnectServer(conn);
            errno = EPERM;
            *err = -2;
            return NULL;
        }
        assert(ret == 1);

        conn->conn_info->status = CONNECTIONINFO_STATUS_ESTABLISHED;
        LastSaw1(conn->remoteip, KeyPrintableHash(conn->conn_info->remote_key),
                 LAST_SEEN_ROLE_CONNECT);
        break;

    case CF_PROTOCOL_CLASSIC:

        conn->conn_info->protocol = CF_PROTOCOL_CLASSIC;
        conn->encryption_type = CfEnterpriseOptions();

        if (!IdentifyAgent(conn->conn_info))
        {
            Log(LOG_LEVEL_ERR, "Id-authentication for '%s' failed", VFQNAME);
            errno = EPERM;
            DisconnectServer(conn);
            *err = -2; // auth err
            return NULL;
        }

        if (!AuthenticateAgent(conn, flags.trust_server))
        {
            Log(LOG_LEVEL_ERR, "Authentication dialogue with '%s' failed", server);
            errno = EPERM;
            DisconnectServer(conn);
            *err = -2; // auth err
            return NULL;
        }
        conn->conn_info->status = CONNECTIONINFO_STATUS_ESTABLISHED;
        break;

    default:
        ProgrammingError("ServerConnection: ProtocolVersion %d!",
                         flags.protocol_version);
    }

    conn->authenticated = true;
    return conn;
}
Exemplo n.º 11
0
Sample::~Sample()
{
	DisconnectServer();
}
Exemplo n.º 12
0
void Sample:: OnServerBreak(void * param, void * call_back_object)
{
	// when the server break, disconenct server;
	cout << "server break, disconnect here" << endl;
	DisconnectServer();
}