Exemplo n.º 1
0
void AccountManager::serverInfoSuccess(const Account &account, const ServerInfo &info)
{
    setServerInfoKeyValue(db, account, kVersionKeyName, info.getVersionString());
    setServerInfoKeyValue(db, account, kFeaturesKeyName, info.getFeatureStrings().join(","));
    setServerInfoKeyValue(db, account, kCustomLogoKeyName, info.customLogo);
    setServerInfoKeyValue(db, account, kCustomBrandKeyName, info.customBrand);

    QUrl url(account.serverUrl);
    url.setPath("/");
    seafApplet->rpcClient()->setServerProperty(
        url.toString(), "is_pro", account.isPro() ? "true" : "false");

    bool changed = account.serverInfo != info;
    if (!changed)
        return;


    for (size_t i = 0; i < accounts_.size(); i++) {
        if (accounts_[i] == account) {
            if (i == 0)
                emit beforeAccountChanged();
            accounts_[i].serverInfo = info;
            if (i == 0)
                emit accountsChanged();
            break;
        }
    }
}
Exemplo n.º 2
0
void ServerInfoRequest::requestSuccess(QNetworkReply& reply)
{
    json_error_t error;
    json_t* root = parseJSON(reply, &error);
    if (!root) {
        qWarning("failed to parse json:%s\n", error.text);
        emit failed(ApiError::fromJsonError());
        return;
    }
    QScopedPointer<json_t, JsonPointerCustomDeleter> json(root);

    QMap<QString, QVariant> dict = mapFromJSON(json.data(), &error);

    ServerInfo ret;

    if (dict.contains("version")) {
        ret.parseVersionFromString(dict["version"].toString());
    }

    if (dict.contains("features")) {
        ret.parseFeatureFromStrings(dict["features"].toStringList());
    }

    if (dict.contains("desktop-custom-logo")) {
        ret.customLogo = dict["desktop-custom-logo"].toString();
    }

    if (dict.contains("desktop-custom-brand")) {
        ret.customBrand = dict["desktop-custom-brand"].toString();
    }

    emit success(account_, ret);
}
Exemplo n.º 3
0
// _GetServerInfo
status_t
NetFSServer::_GetServerInfo(ServerInfo& serverInfo)
{
	// set the server name and the connection method
	char hostName[1024];
	if (gethostname(hostName, sizeof(hostName)) < 0) {
		ERROR("NetFSServer::_GetServerInfo(): ERROR: Failed to get host "
			"name.");
		return B_ERROR;
	}
	status_t error = serverInfo.SetServerName(hostName);
// TODO: Set the actually used connection method!
	if (error == B_OK)
		error = serverInfo.SetConnectionMethod("insecure");
	if (error != B_OK)
		return error;

	// get the shares from the security context
	BMessage shares;
	error = fSecurityContext->GetShares(&shares);
	if (error != B_OK)
		return error;

	// add the shares
	const char* shareName;
	for (int32 i = 0; shares.FindString("shares", i, &shareName) == B_OK; i++) {
		error = serverInfo.AddShare(shareName);
		if (error != B_OK)
			return error;
	}
	return B_OK;
}
Exemplo n.º 4
0
void ServerDialog::loadCustomServers()
{
    for (int i = 0; i < MAX_SERVERLIST; ++i)
    {
        const std::string index = toString(i);
        const std::string nameKey = "MostUsedServerName" + index;
        const std::string typeKey = "MostUsedServerType" + index;
        const std::string portKey = "MostUsedServerPort" + index;

        ServerInfo server;
        server.hostname = config.getValue(nameKey, "");
        server.type = ServerInfo::parseType(config.getValue(typeKey, ""));

        const int defaultPort = defaultPortForServerType(server.type);
        server.port = (unsigned short) config.getValue(portKey, defaultPort);

        // Stop on the first invalid server
        if (!server.isValid())
            break;

        server.save = true;

        mServers.push_back(server);
    }
}
Exemplo n.º 5
0
void MPDConnection::connectToMPD(const ServerInfo &server) {
	if (d->connected) {
		if (d->server == server) // Trying to reconncet to same server, ignore
			return;
		// Trying to connect to another server. disconnect, then connect to it.
		disconnectFromMPD();
	}

	setCaller("MPDConnection::connectToMPD", "mpd_newConnection");
	d->connection = mpd_newConnection(server.address().toUtf8(), server.port(), Config::instance()->timeoutTime());
	if (!finishCommand()) {
		disconnectFromMPD(tr("Could not connect to server %1:%2").arg(server.address()).arg(server.port()));
		return;
	}

	if (!server.password().isEmpty()) {
		mpd_call(MPDConnection::connectToMPD, Password, server.password().toUtf8());
		if (!finishCommand()) {
			disconnectFromMPD(tr("Authentication failed"));
			return;
		}
	}

	d->connected = true;
	d->server = server;
	emit connected(server);
}
Exemplo n.º 6
0
    BaseProxy::BaseProxy(
            ServerInfo serverinfo,
            int32_t maxConn,
            bool initConsNow,
            ServiceManager* service_manager,
            int32_t tryCount,
            int32_t tryInterval)
        :_serverinfo(serverinfo.getIP(),serverinfo.getPort()),
        _service_manager(service_manager)
    {
        _name = StringUtil::generate_uuid();
        _nMaxConn = maxConn;
        _tryCount = tryCount;
        _tryInterval = tryInterval;
		_seqid=~0;
		_use_existing_socket=false;
#ifndef _WIN32
        signal(SIGPIPE, SIG_IGN);
#endif
        if(initConsNow){
            init(INIT_ALL);
        }
		else{
			init(INIT_CALLBACK);
		}
    }
Exemplo n.º 7
0
bool NetworkRoleMenu::joinAGame() {
    try {
        ServerInfo *game = servers.at(selectedGame);
        if (game->getLastPong() > 1) return false;
        return networkingMgr->connectToGame(game);
    } catch (...) { return false; }
}
Exemplo n.º 8
0
bool ServerModel::setData(const QModelIndex &idx, const QVariant &value, int role) {
	if (role != Qt::EditRole || !idx.isValid())
		return false;
	ServerInfo si = m_servers.at(idx.row());

	bool ok = false;
	switch (idx.column()) {
		case 0:
			si.setName(value.toString());
			ok = true;
			break;
		case 1:
			si.setAddress(value.toString());
			ok = true;
			break;
		case 2:
			si.setPort(value.toInt(&ok));
			break;
		case 3:
			si.setPassword(value.toString());
			ok = true;
			break;
	}

	if (ok) {
		m_servers.replace(idx.row(), si);
		Config::instance()->setServers(m_servers);
		emit dataChanged(index(idx.row(), 0), index(idx.row(), 3));
		return true;
	}

	return false;
}
Exemplo n.º 9
0
/**
 * Throws NSPRException upon NSPR error
 */
Connection::Connection(const ServerInfo& server,
		       const std::string &certDBPasswd,
		       const std::string &certNickName,
		       bool alwaysTrustServerCert) 
    : socket(NULL), certdbpasswd(NULL), certnickname(NULL)
{
    char      buffer[PR_NETDB_BUF_SIZE];
    PRNetAddr address;
    PRHostEnt hostEntry;
    PRIntn    hostIndex;
    PRStatus	prStatus;
    SECStatus	secStatus;

    prStatus = PR_GetHostByName(server.getHost().c_str(), buffer,
				sizeof(buffer), &hostEntry);
    if (PR_SUCCESS != prStatus) {
        throw NSPRException("Connection::Connection", "PR_GetHostByName");
    }

    hostIndex = PR_EnumerateHostEnt(0, &hostEntry, server.getPort(), &address);
    if (hostIndex < 0) {
        throw NSPRException("Connection::Connection", "PR_EnumerateHostEnt");
    }

    socket = createSocket(address, server.useSSL(),
			  certDBPasswd,
			  certNickName,
			  alwaysTrustServerCert);

    if (server.useSSL()) {
	secStatus = SSL_SetURL(socket, server.getHost().c_str());
	if (SECSuccess != secStatus) {
	    PRErrorCode error = PR_GetError();

	    PR_Shutdown(socket, PR_SHUTDOWN_BOTH);
	    PR_Close(socket);
	    Log::log(Log::ALL_MODULES, Log::LOG_ERROR,
		     "SSL_SetURL() returned error: %s",
		     PR_ErrorToString(error, PR_LANGUAGE_I_DEFAULT));
	    throw NSPRException("Connection::Connection",
				"SSL_SetURL", error);
	}
    }

    prStatus = PR_Connect(socket, &address, connect_timeout);

    if (prStatus != PR_SUCCESS) {
	PRErrorCode error = PR_GetError();

	PR_Shutdown(socket, PR_SHUTDOWN_BOTH);
	PR_Close(socket);
	throw NSPRException("Connection::Connection PR_Connect", "PR_Connect", error);
    }
}
Exemplo n.º 10
0
void ServerGrp::SyncGroupInfo(int32 nSocketID)
{
	PacketAddSrvInfo pkt;

	for (SrvInfoMap::iterator itr = m_SrvMap.begin(); itr != m_SrvMap.end(); ++itr)
	{
		ServerInfo* pInfo = itr->second;

		pInfo->FillPacket( &pkt );
		PeerSend( nSocketID, &pkt);
	}
}
Exemplo n.º 11
0
void ServerDialog::saveCustomServers(const ServerInfo &currentServer, int index)
{
    ServerInfos::iterator it, it_end = mServers.end();

    // Make sure the current server is mentioned first
    if (currentServer.isValid())
    {
        if (index > -1)
        {
            mServers[index] = currentServer;
        }
        else
        {
            for (it = mServers.begin(); it != it_end; ++it)
            {
                if (*it == currentServer)
                {
                    mServers.erase(it);
                    break;
                }
            }
            mServers.push_front(currentServer);
        }
    }

    int savedServerCount = 0;

    for (it = mServers.begin(), it_end = mServers.end();
         it != it_end && savedServerCount < MAX_SERVERLIST; ++it)
    {
        const ServerInfo &server = *it;

        // Only save servers that were loaded from settings
        if (!(server.save && server.isValid()))
            continue;

        const std::string index = toString(savedServerCount);
        const std::string nameKey = "MostUsedServerDescName" + index;
        const std::string hostNameKey = "MostUsedServerName" + index;
        const std::string typeKey = "MostUsedServerType" + index;
        const std::string portKey = "MostUsedServerPort" + index;
        const std::string descriptionKey = "MostUsedServerDescription" + index;

        config.setValue(hostNameKey, toString(server.hostname));
        config.setValue(typeKey, serverTypeToString(server.type));
        config.setValue(portKey, toString(server.port));
        config.setValue(nameKey, server.name);
        config.setValue(descriptionKey, server.description);
        ++savedServerCount;
    }

    // Insert an invalid entry at the end to make the loading stop there
    if (savedServerCount < MAX_SERVERLIST)
        config.setValue("MostUsedServerName" + toString(savedServerCount), "");

    // Restore the correct description
    if (index < 0)
        index = 0;
    mDescription->setCaption(mServers[index].description);
}
Exemplo n.º 12
0
    BaseProxy::BaseProxy(
            ServerInfo serverinfo,
            int32_t nprotocols,
            ServiceManager* service_manager,
            int32_t tryCount,
            int32_t tryInterval)
        :_serverinfo(serverinfo.getIP(),serverinfo.getPort()),
        _service_manager(service_manager)
    {
        _name = StringUtil::generate_uuid();
        _nProtocols = nprotocols;
        _tryCount = tryCount;
        _tryInterval = tryInterval;

        init();
    }
Exemplo n.º 13
0
QVariant ServerModel::data(const QModelIndex &index, int role) const {
	if ((role != Qt::DisplayRole && role != Qt::EditRole) || !index.isValid())
		return QVariant();

	ServerInfo si = m_servers.at(index.row());
	switch (index.column()) {
		case 0:
			return si.name();
		case 1:
			return si.address();
		case 2:
			return si.port();
		case 3:
			return role == Qt::EditRole ? "" : si.password().isEmpty() ? "" : "********";
	}
	return QVariant();
}
Exemplo n.º 14
0
bool AccountManager::loadServerInfoCB(sqlite3_stmt *stmt, void *data)
{
    ServerInfo *info = static_cast<ServerInfo*>(data);
    const char *key = (const char *)sqlite3_column_text (stmt, 0);
    const char *value = (const char *)sqlite3_column_text (stmt, 1);
    QString key_string = key;
    QString value_string = value;
    if (key_string == kVersionKeyName) {
        info->parseVersionFromString(value_string);
    } else if (key_string == kFeaturesKeyName) {
        info->parseFeatureFromStrings(value_string.split(","));
    } else if (key_string == kCustomBrandKeyName) {
        info->customBrand = value_string;
    } else if (key_string == kCustomLogoKeyName) {
        info->customLogo = value_string;
    }
    return true;
}
Exemplo n.º 15
0
void NetworkRoleMenu::refreshGameList() {
   
    servers = networkingMgr->discoveryAgent->getServerList();
    gameList->resetList();
    for(std::vector<ServerInfo*>::const_iterator it=servers.begin();it!=servers.end(); ++it) {
        ServerInfo *server =  *it;
        //server->print();

        // Don't list games which are not responding (possibly full)
        if (server->getLastPong() > 0) continue;
        addGameToList(server);
    }

    if (selectedGame > (int) gameList->getRowCount()  -1) return;

    CEGUI::MCLGridRef ref = CEGUI::MCLGridRef(selectedGame,0);
    gameList->setItemSelectState(gameList->getItemAtGridReference(ref),true);
}
Exemplo n.º 16
0
void ServerGrp::InitDogDetailsPools(PacketSender* pSender, int32 nDogSrvID)
{
	SrvInfoMap& map = m_SrvMap;

	for (SrvInfoMap::iterator itr = map.begin(); itr != map.end(); ++itr)
	{
		ServerInfo* pInfo = (ServerInfo*)itr->second;

		PacketDogData pkt;

		ParamPool*& pPool = pInfo->m_pParamDetails;
		if(!pPool)
			pInfo->UpdateDetailsPool();

		pkt.nParamType = pPool->GetParamTypeID();
		pkt.SyncParam2Dog( pSender, nDogSrvID, pPool, eParam_Flag_Server, eParam_Sync_All);
	}
}
Exemplo n.º 17
0
void GameNetwork::Start(ServerInfo server)
{
	this->mServer = server;
	for(int i = 0; i < PLAYER_CAP; i++)
	{
		this->mNetBalls[i]->SetPos(this->mNetBalls[i]->GetStartPos());
		this->mNetBalls[i]->SetHP(((WARLOCKInfo*)server.GetGameModeInfo())->GetStartHealth());
	}
	this->mNetBalls[this->mIndex]->GetPlayerHistory()->Reset(this->mNetBalls[this->mIndex]->GetStartPos());

	if(!this->mOnline)
	{

		if(this->mServer.GetIP() == "")
		{
			mConn->Host(server);
		}
		else 
		{
			mConn->Connect(server);
		}
	}
	else
	{
		if(server.GetID() == -1)
		{
			char create[1024] = "CREATE GAME";
			int offset = 12;
			server.GetBuffer(create, offset);
			create[offset++] = 10;
			this->mOnlineHandler->Send(create, offset);
		}
		else
		{
			char join[55] = "JOIN GAME";
			int offset = 10;
			AddToBuf(join, offset, server.GetID());
			join[offset++] = 10;
			this->mOnlineHandler->Send(join, offset);
		}
	}
	
}
Exemplo n.º 18
0
Warlock::Warlock(GraphicsEngine* ge, GameNetwork* net, ServerInfo server)
{
	this->mGe = ge;
	this->mNumberOfPlayers = 0;
	this->mNumberOfRounds = 3;
	this->mGameMode = server.GetGameMode();
	this->mNet = net;
	this->mServerInfo = server;
	this->mTimeElapsed = 0.0f;
	this->mProgressBars = NULL;
}
Exemplo n.º 19
0
void LoginHandler::chooseServer(unsigned int server)
{
    if (server >= mWorlds.size())
        return;

    charServer.clear();
    charServer.hostname = ipToString(mWorlds[server]->address);
    charServer.port = mWorlds[server]->port;

    Client::setState(STATE_UPDATE);
}
Exemplo n.º 20
0
void AccountManager::serverInfoSuccess(const Account &account, const ServerInfo &info)
{
    setServerInfoKeyValue(db, account, kVersionKeyName, info.getVersionString());
    setServerInfoKeyValue(db, account, kFeaturesKeyName, info.getFeatureStrings().join(","));
    setServerInfoKeyValue(db, account, kCustomLogoKeyName, info.customLogo);
    setServerInfoKeyValue(db, account, kCustomBrandKeyName, info.customBrand);

    bool changed = account.serverInfo != info;
    if (!changed)
        return;

    for (size_t i = 0; i < accounts_.size(); i++) {
        if (accounts_[i] == account) {
            if (i == 0)
                emit beforeAccountChanged();
            accounts_[i].serverInfo = info;
            if (i == 0)
                emit accountsChanged();
            break;
        }
    }
}
Exemplo n.º 21
0
void ServerDialog::saveCustomServers(const ServerInfo &currentServer)
{
    // Make sure the current server is mentioned first
    if (currentServer.isValid())
    {
        ServerInfos::iterator i, i_end = mServers.end();
        for (i = mServers.begin(); i != i_end; ++i)
        {
            if (*i == currentServer)
            {
                mServers.erase(i);
                break;
            }
        }
        mServers.insert(mServers.begin(), currentServer);
    }

    int savedServerCount = 0;

    for (unsigned i = 0;
         i < mServers.size() && savedServerCount < MAX_SERVERLIST; ++i)
    {
        const ServerInfo &server = mServers.at(i);

        // Only save servers that were loaded from settings
        if (!(server.save && server.isValid()))
            continue;

        const std::string index = toString(savedServerCount);
        const std::string nameKey = "MostUsedServerName" + index;
        const std::string typeKey = "MostUsedServerType" + index;
        const std::string portKey = "MostUsedServerPort" + index;

        config.setValue(nameKey, toString(server.hostname));
        config.setValue(typeKey, serverTypeToString(server.type));
        config.setValue(portKey, toString(server.port));
        ++savedServerCount;
    }

    // Insert an invalid entry at the end to make the loading stop there
    if (savedServerCount < MAX_SERVERLIST)
        config.setValue("MostUsedServerName" + toString(savedServerCount), "");
}
Exemplo n.º 22
0
CaptureTheFlag::CaptureTheFlag(GraphicsEngine* ge, GameNetwork* net, ServerInfo server)
{
		this->mGe = ge;
		this->mNumberOfPlayers = 0;
		this->mNumberOfRounds = 3;
		this->mGameMode = server.GetGameMode();
		this->mNet = net;
		this->mServerInfo = server;
		this->mTimeElapsed = 0.0f;

	this->mTeam = (int)TEAM::NOTEAM;

	this->mEnemyFlag = NULL;
	this->mFriendlyFlag = NULL;
	this->mRedFlag = NULL;		
	this->mBlueFlag = NULL;	
	this->mRedScore = 0;
	this->mBlueScore = 0;
	this->mRedScoreText = NULL;
	this->mBlueScoreText = NULL;
	this->mIntermediateText = NULL;
}
Exemplo n.º 23
0
am_status_t
BaseService::doRequest(const ServiceInfo& service,
		       const BodyChunk& headerPrefix,
		       const std::string& uriParameters,
		       const Http::CookieList& cookieList,
		       const BodyChunk& headerSuffix,
		       const BodyChunkList& bodyChunkList,
		       Http::Response& response,
		       std::size_t initialBufferLen,
		       const std::string &cert_nick_name,
		       const ServerInfo** serverInfo) const
{
    am_status_t status = AM_SERVICE_NOT_AVAILABLE;
    std::size_t dataLen = 0;
    // Create a temporary buffer for the Content-Line header
    // the extra '2' is for the <CR><LF> at the end.  The
    // sizeof the CONTENT_LENGTH_HDR includes space for the
    // terminating NUL.
    char contentLine[sizeof(CONTENT_LENGTH_HDR) +
		     (sizeof(dataLen) * DIGITS_PER_BYTE) + 2];
    std::size_t contentLineLen;

    for (unsigned int i = 0; i < bodyChunkList.size(); ++i) {
	dataLen += bodyChunkList[i].data.size();
    }

    contentLineLen = snprintf(contentLine, sizeof(contentLine), "%s%d\r\n",
			      CONTENT_LENGTH_HDR, dataLen);
    if (sizeof(contentLine) > contentLineLen) {
	BodyChunk contentLineChunk(contentLine, contentLineLen);
	ServiceInfo::const_iterator iter;

	for (iter = service.begin(); iter != service.end(); ++iter) {
            ServerInfo svrInfo = ServerInfo((const ServerInfo&)(*iter));
	    if (!svrInfo.isHealthy(poll_primary_server)) {
		Log::log(logModule, Log::LOG_WARNING,
			"BaseService::doRequest(): "
			"Server is unavailable: %s.",
			svrInfo.getURL().c_str());
		continue;
	    } else {
		Log::log(logModule, Log::LOG_DEBUG,
			"BaseService::doRequest(): Using server: %s.",
			iter->getURL().c_str());
            }

            Http::HeaderList headerList, proxyHeaderList;
            Http::Cookie hostHeader("Host", svrInfo.getHost());
            headerList.push_back(hostHeader);

            if (useProxy) {
                proxyHeaderList.push_back(hostHeader);
                // Override (temporarily) server credentials if using proxy
                svrInfo.setHost(proxyHost);
                svrInfo.setPort(proxyPort);
                // We don't use SSL for initial proxy connection
		svrInfo.setUseSSL(false);
                Log::log(logModule, Log::LOG_DEBUG,
                         "BaseService::doRequest(): Using proxy: %s:%d",
                         proxyHost.c_str(),proxyPort);
                // Add Proxy-Authorization header if user defined
                if (useProxyAuth) {
                    // allocate enough for a base64-encoded digest
                    int authSize = proxyUser.size() + 
                                   proxyPassword.size() + 1;
                    // 11 extra bytes for prefix and terminator
                    char * digest = (char *)malloc(authSize * 4/3 + 11);
                    strcpy(digest, "Basic ");
                    encode_base64((proxyUser + ":" + proxyPassword).c_str(),
                                   authSize,(digest + 6));
                    Log::log(logModule, Log::LOG_MAX_DEBUG,
                         "BaseService::doRequest(): Using proxy auth as: %s",
                         proxyUser.c_str());
                    hostHeader = Http::Cookie("Proxy-Authorization", digest);
                    proxyHeaderList.push_back(hostHeader);
                    free(digest);
                }
            }

            // retry to connect to server before marking it as down.
            // making the number of attempts configurable may have a negative
            // side effect on performance, if the the value is a high number.
            int retryAttempts = 3;
            int retryCount = 0;
            while(retryCount < retryAttempts) {
                retryCount++;
	        try {
                    Connection conn(svrInfo, certDBPasswd,
                      (cert_nick_name.size()>0)?cert_nick_name:certNickName,
                         alwaysTrustServerCert);
		    const char *operation = "sending to";
                    // in case proxy is defined and target URL is HTTPS, 
                    // establish an SSL tunnel first send 
                    // CONNECT host:port string
                    if (useProxy && iter->useSSL()) {
                        SECStatus   secStatus = SECFailure;
                        // All the other parameters would be empty for a 
                        // proxy CONNECT
                        Http::CookieList emptyCookieList;
                        BodyChunk emptyChunk;
                        BodyChunkList emptyChunkList;

                        // Add a Keep-alive header since we're using HTTP/1.0
                        hostHeader = Http::Cookie("Connection", 
                                                  "Keep-Alive\r\n");
                        proxyHeaderList.push_back(hostHeader);
                        status = sendRequest(conn, 
                                        BodyChunk(std::string("CONNECT ")), 
                                        iter->getHost() + ":" +
					Utils::toString(iter->getPort()), 
                                        std::string(""), proxyHeaderList, 
                                        emptyCookieList, emptyChunk, 
                                        emptyChunk, emptyChunkList);
                        if (status == AM_SUCCESS) {
                            // Retrieve proxie's response if tunnel 
                            // established
                            (void) response.readAndIgnore(logModule, conn);
                            // Secure the tunnel now by upgrading the socket
                            PRFileDesc *sock = conn.secureSocket(
                                                  certDBPasswd, 
                                                  (cert_nick_name.size()>0)?
                                            cert_nick_name:certNickName, 
				            alwaysTrustServerCert, NULL);
                            if (sock != static_cast<PRFileDesc *>(NULL)) {
                                secStatus = SSL_SetURL(sock, 
                                                  iter->getHost().c_str());
                            }
                        }

                        if (status != AM_SUCCESS || SECSuccess != secStatus){
                            Log::log(logModule, Log::LOG_ERROR,
                                "BaseService::doRequest(): could not "
				"establish a secure proxy tunnel");
                            // Can't continue and mark server as down as 
                            // it was a  proxy failure
                            return AM_FAILURE;
                        }
                    }

		    if(Log::isLevelEnabled(logModule, Log::LOG_MAX_DEBUG)) {
		        std::string commString;
		        for(std::size_t i = 0; i<bodyChunkList.size(); ++i) {
			    if(!bodyChunkList[i].secure) {
			        commString.append(bodyChunkList[i].data);
			    } else {
			        commString.append("<secure data>");
			    }
		        }
		        for(std::size_t commPos = commString.find("%");
		    	    commPos != std::string::npos &&
			    commPos < commString.size();
			    commPos = commString.find("%", commPos)) {
			    commString.replace(commPos, 1, "%%");
			    commPos += 2;
		        }
		        Log::log(logModule, Log::LOG_MAX_DEBUG,
			     commString.c_str());
		    }

                    std::string requestString = iter->getURI();
                    /*
                     * In case the following request would go to a proxy
                     * we need to use full URL and special headers.
                     * If the resource is HTTPS, we're not posting our
                     * request to the proxy, but to the server 
                     * through proxy tunnel
                     */

                    if (useProxy && !(iter->useSSL())) {
                        requestString = iter->getURL();
                        headerList = proxyHeaderList;
                    }
		    status = sendRequest(conn, headerPrefix, requestString,
				     uriParameters, headerList, cookieList,
				     contentLineChunk, headerSuffix,
				     bodyChunkList);
		    if (AM_SUCCESS == status) {
		        operation = "receiving from";
		        status = response.readAndParse(logModule, conn,
						   initialBufferLen);
		        if (AM_SUCCESS == status) {
			    Log::log(logModule, Log::LOG_MAX_DEBUG, "%.*s",
				 response.getBodyLen(), response.getBodyPtr());
		        }
		    }

		    if (AM_NSPR_ERROR == status) {
		        PRErrorCode nspr_code = PR_GetError();
		        Log::log(logModule, Log::LOG_ALWAYS,
			     "BaseService::doRequest() NSPR failure while "
			     "%s %s, error = %s", operation,
			     (*iter).toString().c_str(), 
			     PR_ErrorToName(nspr_code));
		    }
		
		    if (AM_SUCCESS == status) {
		        if(serverInfo != NULL) *serverInfo = &(*iter);
		            break;
		    } else {
                        if(retryCount < retryAttempts) {
                            continue;
                        } else {
                           Log::log(logModule, Log::LOG_DEBUG,
                               "BaseService::doRequest() Invoking markSeverDown");
                           svrInfo.markServerDown(poll_primary_server);
                        }
		    }
	        } catch (const NSPRException& exc) {
		    Log::log(logModule, Log::LOG_DEBUG,
			 "BaseService::doRequest() caught %s: %s called by %s "
			 "returned %s", exc.what(), exc.getNsprMethod(),
			 exc.getThrowingMethod(), 
			 PR_ErrorToName(exc.getErrorCode()));

                   if(retryCount < retryAttempts) {
		       status = AM_NSPR_ERROR;
                       continue;
                    } else {
                       Log::log(logModule, Log::LOG_DEBUG,
                           "BaseService::doRequest() Invoking markSeverDown");
                       svrInfo.markServerDown(poll_primary_server);
		       status = AM_NSPR_ERROR;
                    }
	        }
            } //end of while

            if (AM_SUCCESS == status) {
               if(serverInfo != NULL) *serverInfo = &(*iter);
                    break;
            }
            if (status = AM_NSPR_ERROR) {
               continue;
            }

	} // end of for
    } else {
	status = AM_BUFFER_TOO_SMALL;
    }

    return status;
}
Exemplo n.º 24
0
void NinjamController::start(const ServerInfo& server)
{
    qCDebug(jtNinjamCore) << "starting ninjam controller...";
    QMutexLocker locker(&mutex);

    //schedule an update in internal attributes
    scheduledEvents.append(new BpiChangeEvent(this, server.getBpi()));
    scheduledEvents.append(new BpmChangeEvent(this, server.getBpm()));
    preparedForTransmit = false; // the xmit start after the first interval is received
    emit preparingTransmission();

    // schedule the encoders creation (one encoder for each channel)
    int channels = mainController->getInputTrackGroupsCount();
    for (int channelIndex = 0; channelIndex < channels; ++channelIndex) {
        scheduledEvents.append(new InputChannelChangedEvent(this, channelIndex));
    }

    processScheduledChanges();

    if (!running) {

        encodingThread = new NinjamController::EncodingThread(this);

        // add a sine wave generator as input to test audio transmission
        //mainController->addInputTrackNode(new Audio::LocalInputTestStreamer(440, mainController->getAudioDriverSampleRate()));


        mainController->addTrack(METRONOME_TRACK_ID, this->metronomeTrackNode);
        mainController->setTrackMute(METRONOME_TRACK_ID, mainController->getSettings().getMetronomeMuteStatus());
        mainController->setTrackGain(METRONOME_TRACK_ID,mainController->getSettings().getMetronomeGain());
        mainController->setTrackPan(METRONOME_TRACK_ID,  mainController->getSettings().getMetronomePan());

        this->intervalPosition  = lastBeat = 0;


        auto ninjamService = mainController->getNinjamService();
        connect(ninjamService, &Service::serverBpmChanged, this, &NinjamController::scheduleBpmChangeEvent);
        connect(ninjamService, &Service::serverBpiChanged, this, &NinjamController::scheduleBpiChangeEvent);
        connect(ninjamService, &Service::audioIntervalCompleted, this, &NinjamController::handleIntervalCompleted);

        connect(ninjamService, &Service::userChannelCreated, this, &NinjamController::addNinjamRemoteChannel);
        connect(ninjamService, &Service::userChannelRemoved, this, &NinjamController::removeNinjamRemoteChannel);
        connect(ninjamService, &Service::userChannelUpdated, this, &NinjamController::updateNinjamRemoteChannel);
        connect(ninjamService, &Service::audioIntervalDownloading, this, &NinjamController::handleIntervalDownloading);
        connect(ninjamService, &Service::userExited, this, &NinjamController::handleNinjamUserExiting);
        connect(ninjamService, &Service::userEntered, this, &NinjamController::handleNinjamUserEntering);

        connect(ninjamService, &Service::publicChatMessageReceived, this, &NinjamController::handleReceivedPublicChatMessage);
        connect(ninjamService, &Service::privateChatMessageReceived, this, &NinjamController::handleReceivedPrivateChatMessage);
        connect(ninjamService, &Service::serverTopicMessageReceived, this, &NinjamController::topicMessageReceived);

        // add tracks for users connected in server
        auto users = server.getUsers();
        for (const auto &user : users) {
            for (const auto &channel : user.getChannels()) {
                addTrack(user, channel);
            }
        }

        this->running = true;

        emit started();
    }
    qCDebug(jtNinjamCore) << "ninjam controller started!";
}
Exemplo n.º 25
0
namespace TmwAthena {

extern ServerInfo charServer;

LoginHandler::LoginHandler():
        mVersionResponse(false),
        mRegistrationEnabled(true)
{
    static const Uint16 _messages[] = {
        SMSG_UPDATE_HOST,
        SMSG_LOGIN_DATA,
        SMSG_LOGIN_ERROR,
        SMSG_CHAR_PASSWORD_RESPONSE,
        SMSG_SERVER_VERSION_RESPONSE,
        0
    };
    handledMessages = _messages;
    loginHandler = this;
}

LoginHandler::~LoginHandler()
{
    delete_all(mWorlds);
}

void LoginHandler::handleMessage(Net::MessageIn &msg)
{
    int code, worldCount;

    switch (msg.getId())
    {
        case SMSG_CHAR_PASSWORD_RESPONSE:
        {
            // 0: acc not found, 1: success, 2: password mismatch, 3: pass too short
            int errMsg = msg.readInt8();
            // Successful pass change
            if (errMsg == 1)
            {
                Client::setState(STATE_CHANGEPASSWORD_SUCCESS);
            }
            // pass change failed
            else
            {
                switch (errMsg)
                {
                    case 0:
                        errorMessage = _("Account was not found. Please re-login.");
                        break;
                    case 2:
                        errorMessage = _("Old password incorrect.");
                        break;
                    case 3:
                        errorMessage = _("New password too short.");
                        break;
                    default:
                        errorMessage = _("Unknown error.");
                        break;
                }
                Client::setState(STATE_ACCOUNTCHANGE_ERROR);
            }
        }
            break;

        case SMSG_UPDATE_HOST:
             int len;

             len = msg.readInt16() - 4;
             mUpdateHost = msg.readString(len);
             loginData.updateHost = mUpdateHost;

             logger->log("Received update host \"%s\" from login server.",
                     mUpdateHost.c_str());
             break;

        case SMSG_LOGIN_DATA:
            // Skip the length word
            msg.skip(2);

            clearWorlds();

            worldCount = (msg.getLength() - 47) / 32;

            mToken.session_ID1 = msg.readInt32();
            mToken.account_ID = msg.readInt32();
            mToken.session_ID2 = msg.readInt32();
            msg.skip(30);                           // unknown
            mToken.sex = msg.readInt8() ? GENDER_MALE : GENDER_FEMALE;

            for (int i = 0; i < worldCount; i++)
            {
                WorldInfo *world = new WorldInfo;

                world->address = msg.readInt32();
                world->port = msg.readInt16();
                world->name = msg.readString(20);
                world->online_users = msg.readInt32();
                world->updateHost = mUpdateHost;
                msg.skip(2);                        // unknown

                logger->log("Network: Server: %s (%s:%d)",
                        world->name.c_str(),
                        ipToString(world->address),
                        world->port);

                mWorlds.push_back(world);
            }
            Client::setState(STATE_WORLD_SELECT);
            break;

        case SMSG_LOGIN_ERROR:
            code = msg.readInt8();
            logger->log("Login::error code: %i", code);

            switch (code)
            {
                case 0:
                    errorMessage = _("Unregistered ID.");
                    break;
                case 1:
                    errorMessage = _("Wrong password.");
                    break;
                case 2:
                    errorMessage = _("Account expired.");
                    break;
                case 3:
                    errorMessage = _("Rejected from server.");
                    break;
                case 4:
                    errorMessage = _("You have been permanently banned from "
                                     "the game. Please contact the GM team.");
                    break;
                case 5:
                    errorMessage = _("Client too old.");
                    break;
                case 6:
                    errorMessage = strprintf(_("You have been temporarily "
                                               "banned from the game until "
                                               "%s.\nPlease contact the GM "
                                               "team via the forums."),
                                               msg.readString(20).c_str());
                    break;
                case 7:
                    errorMessage = _("Server overpopulated.");
                    break;
                case 9:
                    errorMessage = _("This user name is already taken.");
                    break;
                case 99:
                    errorMessage = _("Username permanently erased.");
                    break;
                default:
                    errorMessage = _("Unknown error.");
                    break;
            }
            Client::setState(STATE_ERROR);
            break;

        case SMSG_SERVER_VERSION_RESPONSE:
            {
                // TODO: verify these!

                msg.readInt8(); // -1
                msg.readInt8(); // T
                msg.readInt8(); // M
                msg.readInt8(); // W

                unsigned int options = msg.readInt32();

                mRegistrationEnabled = (options & 1);

                // Leave this last
                mVersionResponse = true;
            }
            break;
    }
}

void LoginHandler::connect()
{
    mNetwork->connect(mServer);
    MessageOut outMsg(CMSG_SERVER_VERSION_REQUEST);
}

bool LoginHandler::isConnected()
{
    return mVersionResponse && mNetwork->isConnected();
}

void LoginHandler::disconnect()
{
    if (mNetwork->getServer() == mServer)
        mNetwork->disconnect();
}

bool LoginHandler::isRegistrationEnabled()
{
    return mRegistrationEnabled;
}

void LoginHandler::getRegistrationDetails()
{
    // Not supported, so move on
    Client::setState(STATE_REGISTER);
}

void LoginHandler::loginAccount(LoginData *loginData)
{
    loginData->characterSlots = 9;

    sendLoginRegister(loginData->username, loginData->password);
}

void LoginHandler::logout()
{
    // TODO
}

void LoginHandler::changeEmail(const std::string &email)
{
    // TODO
}

void LoginHandler::changePassword(const std::string &username,
                                  const std::string &oldPassword,
                                  const std::string &newPassword)
{
    MessageOut outMsg(CMSG_CHAR_PASSWORD_CHANGE);
    outMsg.writeString(oldPassword, 24);
    outMsg.writeString(newPassword, 24);
}

void LoginHandler::chooseServer(unsigned int server)
{
    if (server >= mWorlds.size())
        return;

    charServer.clear();
    charServer.hostname = ipToString(mWorlds[server]->address);
    charServer.port = mWorlds[server]->port;

    Client::setState(STATE_UPDATE);
}

void LoginHandler::registerAccount(LoginData *loginData)
{
    std::string username = loginData->username;
    username.append((loginData->gender == GENDER_FEMALE) ? "_F" : "_M");

    sendLoginRegister(username, loginData->password);
}

void LoginHandler::unregisterAccount(const std::string &username,
                                     const std::string &password)
{
    // TODO
}

void LoginHandler::sendLoginRegister(const std::string &username,
                                     const std::string &password)
{
    MessageOut outMsg(0x0064);
    outMsg.writeInt32(0); // client version
    outMsg.writeString(username, 24);
    outMsg.writeString(password, 24);

    /*
     * eAthena calls the last byte "client version 2", but it isn't used at
     * at all. We're retasking it, as a bit mask:
     *  0 - can handle the 0x63 "update host" packet
     *  1 - defaults to the first char-server (instead of the last)
     */
    outMsg.writeInt8(0x03);
}

Worlds LoginHandler::getWorlds() const
{
    return mWorlds;
}

void LoginHandler::clearWorlds()
{
    delete_all(mWorlds);
    mWorlds.clear();
}

} // namespace TmwAthena
//初始化获取服务器
void connectToBalanceServer()
{
	
	WORD wVersionRequested;
    WSADATA wsaData;
    int err;
	wVersionRequested = MAKEWORD(1, 1);
    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0) {                                 
        //printf("WSAStartup failed with error: %d\n", err);
        return ;
    }
    if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) {
        //printf("Could not find a usable version of Winsock.dll\n");
        WSACleanup();
        return ;
    }
    /*
	else
        printf("The Winsock 1.1 dll was found okay\n");
	*/

	SOCKET sockClient=socket(AF_INET,SOCK_DGRAM,0);
	
	//send
	SOCKADDR_IN balanceServerAddr;
	balanceServerAddr.sin_addr.S_un.S_addr=inet_addr(BalanceServIP);
	balanceServerAddr.sin_family = AF_INET;
	balanceServerAddr.sin_port = htons(BalanceServPort);
	//addrSrv.sin_port = htons(balanceListenPort);
/*
	clientConnectRequst cliConReq;
	cliConReq.bitRate=bitRate;
	cliConReq.flag=1;
	cliConReq.frame_rate=frame_rate;
	cliConReq.resolution=resolution;
*/	
	//发送请求设置
	clientConnectRequst cliConReq;
	cliConReq.bitRate=5000;
	cliConReq.flag=FLAG_CLIENT_CONNECT_REQUEST;
	cliConReq.frame_rate=5000;
	cliConReq.resolution=5000;
	cliConReq.reConPort=10001;
	cliConReq.channel = channel;
	cliConReq.cameraID = cameraID;
	//初始频道不正确
	if (cliConReq.channel < 1)
	{
		cout << "频道为0,设置错误" << endl;
		isStop = 1;
		cin.get();
		exit(0);
	}
	char sendBuf[SEND_TO_BALANCE_SERVER_BUFFER_SIZE];
	for(int i=0;i<sizeof(clientConnectRequst);i++)
	{
		sendBuf[i]=((char*)(&cliConReq))[i];
	}
	
	sendto(sockClient,sendBuf,SEND_TO_BALANCE_SERVER_BUFFER_SIZE,0,(SOCKADDR *)&balanceServerAddr,sizeof(balanceServerAddr));

	//reconnect thread
	SOCKET * reConnectSock = &sockClient; 
	HANDLE hThread5;
	DWORD  ThreadID5;
	hThread5=CreateThread(NULL,0,reConnect,reConnectSock,0,&ThreadID5);
	isConnect=0;
	//listen
	int len = sizeof(SOCKADDR);
	char recBuff[RECEIVE_FROM_BALANCE_SERVER_BUFFER_SIZE];
	while(isConnect!=1)
	{
		memset(recBuff,0,RECEIVE_FROM_BALANCE_SERVER_BUFFER_SIZE);
		recvfrom(sockClient,recBuff,sizeof(recBuff),0,(SOCKADDR *)&addrSrv,&len);
		//receive ok          serge
		//cout<<" receive data\n";
		ServerInfoBlock * pServerBlock;
 		pServerBlock =((ServerInfoBlock *)recBuff);	
		if((*pServerBlock).flag==FLAG_SERVER_INFO)
		{
			isConnect=1;
			if (pServerBlock->server_id<0)
			{
				//std::cout << "no server avalible now\n";
				//	cin.get();
				//调整为默认频道
				channel = 1;
				cameraID = 1;
				connectToBalanceServer();
				return;
				//exit(0);
			}
			serverFromBalance=ServerInfo(*pServerBlock);
			//tempServer.showInfo();
			//std::cout<<"the server ID is : "<<serverFromBalance.getServerID()<<std::endl;
		}
		else
		{
			//std::cout<<"recieve error server info\n";
		}
	}
	//printf("the %s says: %s \n",inet_ntoa(addrClient.sin_addr),recBuff);
		std::string temp =serverFromBalance.getServerPublicIP();
	
	unsigned int i;
	for(i=0;i<temp.length();i++)
	{
		ServIP[i]=temp[i];
	}
	ServIP[i]='\0';
	
		/*
	char aa[20]="192.168.1.109\0";
	int i;
	for(i=0;i<temp.length();i++)
	{
		ServIP[i]=aa[i];
	}
	ServIP[i]='\0';
	*/
	ServPort=serverFromBalance.getServerDataPort();
	retranport=serverFromBalance.getServerRetransmitPort();
	commandport=serverFromBalance.getServerCommandPort();
	//cout<<"serverIP: "<<ServIP<<endl;
	//cout<<"tranport: "<<ServPort<<endl;
	//cout<<"retranport: "<<retranport<<endl;
	//cout<<"commandport: "<<commandport<<endl;
	
}
Exemplo n.º 27
0
/** Fetch a split from remote worker and keep it in the shared memory region
 * @param dest a memory pointer where the split will be written (usually shared mem)
 * @param name a name of split to fetch
 * @param size the size of split to fetch
 * @param client a worker information from where we will fetch the split
 * @param myhostname a name of worker who initiate the transfer request
 * @param store a location other than dram where the split will be written. It can be zero-length
 * @return return code from server
 */
int32_t TransferServer::transfer_blob(void *dest, const string &name,
                                      size_t size, WorkerInfo* client,
                                      const string& myhostname,
                                      const string &store) {
  // Setup the transfer
  this->dest_ = dest;
  this->size_ = size;
  bytes_fetched_ = 0;

  // Initialize semaphore to zero. Server thread will increment
  // when it is ready
  sem_init(&server_ready, 0, 0);

  // Setup a receicing thread.
  // Later, we will send a Fetch request,
  // and the data will arrive to this thread
  pthread_t server_thread;
  pthread_create(&server_thread, 0, transfer_pthread, this);

  // fprintf(stderr,
  //   "Waiting for server to be ready for transfer array %s from %s\n",
  //   a.name.c_str(), a.location.name.c_str());
  // Wait till server is ready
  sem_wait(&server_ready);

  // FIXME(shivaram): This doesn't work on bfc machines
  // char hostname[64]; // HOST_NAME_MAX is 64 in Linux
  // int ret = gethostname(hostname, 64);
  // if (ret < 0) {
  //   return ret;
  // }

  // Information of the requester
  ServerInfo location;
  location.set_name(myhostname);
  location.set_presto_port(server_socket_port);
  // Create a fetch request
  FetchRequest req;
  req.mutable_location()->CopyFrom(location);
  req.set_size(size);
  req.set_name(name);
  if (!store.empty()) {
    req.set_store(store);
  }

  client->NewTransfer(req);  // request transfer to remote workers

  void* server_ret;
  pthread_join(server_thread, &server_ret);
  sem_destroy(&server_ready);
  return *reinterpret_cast<int32_t*>(server_ret);

  // TODO(erik): error handling

// } else {
//     // Cancel the server thread if transfer failed.
//     // TODO(shivaram): Check if this behaves correctly or use signals.
//     fprintf(stderr, "Transfer failed, cancelling server\n");
//     sem_destroy(&server_ready);
//     pthread_cancel(server_thread);
//     shutdown(serverfd, SHUT_RDWR);
//     close(serverfd);
//     return -1;
//   }
}