Example #1
0
void GameScene::runLogic(float deltaTime, Game& game) {
    if(game.server) {

        // SERVER

        cooldown -= deltaTime;
        enemySpawnCooldown -= deltaTime;
        enemyCooldown -= deltaTime;
        difficulty += deltaTime * 30.0f;

        bgMotion += deltaTime * bgSpeed;
        if(bgMotion > 256.0f)
            bgMotion -= 256.0f;
        bgSprite->setPosition(0.0f, -600.0f + bgMotion);

        shooting(deltaTime, game);
        spawningEnemies(deltaTime, game);
        flyEnemyPlasma(deltaTime, game);

        player.runLogic(deltaTime, game);

        std::string scoreString = std::to_string(score);
        scoreText.setString("Score: " + scoreString);
        scoreText.setFont(*game.font);
        escText.setFont(*game.font);

        std::string scoreString2 = std::to_string(score2);
        scoreText2.setString("Score: " + scoreString2);
        scoreText2.setFont(*game.font);

        sf::Packet packet;
        packet << player.position.x << player.position.y;
        sf::IpAddress clientAddress(game.clientAddress);
        game.socket->send(packet, clientAddress, game.udpPortClient);

    } else {

        // CLIENT

        sf::Packet packet;
        float x, y;
        sf::IpAddress serverAddress(game.serverAddress);
        game.socket->receive(packet, serverAddress, game.udpPortClient);
        if(packet >> x >> y) {
            player.position.x = x;
            player.position.y = y;
        }
    }
}
Example #2
0
int ClientServerMain()
{
    LocalMatcher matcher;

    uint64_t clientId = 1;

    uint8_t connectTokenData[ConnectTokenBytes];
    uint8_t connectTokenNonce[NonceBytes];

    uint8_t clientToServerKey[KeyBytes];
    uint8_t serverToClientKey[KeyBytes];

    int numServerAddresses;
    Address serverAddresses[MaxServersPerConnectToken];

    memset( connectTokenNonce, 0, NonceBytes );

    if ( !matcher.RequestMatch( clientId, connectTokenData, connectTokenNonce, clientToServerKey, serverToClientKey, numServerAddresses, serverAddresses ) )
    {
        printf( "error: request match failed\n" );
        return 1;
    }

    ClientServerPacketFactory packetFactory;

    Address clientAddress( "::1", ClientPort );
    Address serverAddress( "::1", ServerPort );

    GameNetworkTransport clientTransport( packetFactory, clientAddress );
    GameNetworkTransport serverTransport( packetFactory, serverAddress );

    if ( clientTransport.GetError() != SOCKET_ERROR_NONE || serverTransport.GetError() != SOCKET_ERROR_NONE )
    {
        printf( "error: failed to initialize sockets\n" );
        return 1;
    }
    
    const int NumIterations = 20;

    double time = 0.0;

    GameClient client( GetDefaultAllocator(), clientTransport );

    GameServer server( GetDefaultAllocator(), serverTransport );

    server.SetServerAddress( serverAddress );

    server.Start();
    
    client.Connect( serverAddress, connectTokenData, connectTokenNonce, clientToServerKey, serverToClientKey );

    for ( int i = 0; i < NumIterations; ++i )
    {
        client.SendPackets();
        server.SendPackets();

        clientTransport.WritePackets();
        serverTransport.WritePackets();

        clientTransport.ReadPackets();
        serverTransport.ReadPackets();

        client.ReceivePackets();
        server.ReceivePackets();

        client.CheckForTimeOut();
        server.CheckForTimeOut();

        if ( client.ConnectionFailed() )
        {
            printf( "error: client connect failed!\n" );
            break;
        }

        if ( client.IsConnected() && server.GetNumConnectedClients() == 1 )
            client.Disconnect();

        time += 0.1f;

        if ( !client.IsConnecting() && !client.IsConnected() && server.GetNumConnectedClients() == 0 )
            break;

        client.AdvanceTime( time );
        server.AdvanceTime( time );

        clientTransport.AdvanceTime( time );
        serverTransport.AdvanceTime( time );
    }

    client.Disconnect();

    server.Stop();

    return 0;
}
void TActionContext::execute()
{
    T_TRACEFUNC("");
    THttpResponseHeader responseHeader;
    accessLogger.open();

    try {
        if (!readRequest()) {
            return;
        }
        const THttpRequestHeader &hdr = httpReq->header();

        // Access log
        accessLogger.setTimestamp(QDateTime::currentDateTime());
        QByteArray firstLine = hdr.method() + ' ' + hdr.path();
        firstLine += QString(" HTTP/%1.%2").arg(hdr.majorVersion()).arg(hdr.minorVersion()).toLatin1();
        accessLogger.setRequest(firstLine);
        accessLogger.setRemoteHost( (Tf::app()->appSettings().value(LISTEN_PORT).toUInt() > 0) ? clientAddress().toString().toLatin1() : QByteArray("(unix)") );

        tSystemDebug("method : %s", hdr.method().data());
        tSystemDebug("path : %s", hdr.path().data());

        Tf::HttpMethod method = httpReq->method();
        QString path = THttpUtility::fromUrlEncoding(hdr.path().mid(0, hdr.path().indexOf('?')));

        // Routing info exists?
        TRouting rt = TUrlRoute::instance().findRouting(method, path);
        tSystemDebug("Routing: controller:%s  action:%s", rt.controller.data(),
                     rt.action.data());

        if (rt.isEmpty()) {
            // Default URL routing
            rt.params = path.split('/');
            if (path.startsWith(QLatin1Char('/')) && !rt.params.isEmpty()) {
                rt.params.removeFirst();  // unuse first item
            }
            if (path.endsWith(QLatin1Char('/')) && !rt.params.isEmpty()) {
                rt.params.removeLast();  // unuse last item
            }

            // Direct view render mode?
            if (Tf::app()->appSettings().value(DIRECT_VIEW_RENDER_MODE).toBool()) {
                // Direct view setting
                rt.controller = "directcontroller";
                rt.action = "show";
            } else {
                if (!rt.params.value(0).isEmpty()) {
                    rt.controller = rt.params.takeFirst().toLower().toLatin1() + "controller";

                    if (rt.controller == "applicationcontroller") {
                        rt.controller.clear();  // Can not call 'ApplicationController'
                    }

                    // Default action: index
                    rt.action = rt.params.value(0, QLatin1String("index")).toLatin1();
                    if (!rt.params.isEmpty()) {
                        rt.params.takeFirst();
                    }
                }
                tSystemDebug("Active Controller : %s", rt.controller.data());
            }
        }

        // Call controller method
        TDispatcher<TActionController> ctlrDispatcher(rt.controller);
        currController = ctlrDispatcher.object();
        if (currController) {
            currController->setActionName(rt.action);

            // Session
            if (currController->sessionEnabled()) {
                TSession session;
                QByteArray sessionId = httpReq->cookie(TSession::sessionName());
                if (!sessionId.isEmpty()) {
                    // Finds a session
                    session = TSessionManager::instance().findSession(sessionId);
                }
                currController->setSession(session);

                // Exports flash-variant
                currController->exportAllFlashVariants();
            }

            // Verify authenticity token
            if (Tf::app()->appSettings().value(ENABLE_CSRF_PROTECTION_MODULE, true).toBool()
                && currController->csrfProtectionEnabled() && !currController->exceptionActionsOfCsrfProtection().contains(rt.action)) {

                if (method == Tf::Post || method == Tf::Put || method == Tf::Delete) {
                    if (!currController->verifyRequest(*httpReq)) {
                        throw SecurityException("Invalid authenticity token", __FILE__, __LINE__);
                    }
                }
            }

            if (currController->sessionEnabled()) {
                if (currController->session().id().isEmpty() || Tf::app()->appSettings().value(AUTO_ID_REGENERATION).toBool()) {
                    TSessionManager::instance().remove(currController->session().sessionId); // Removes the old session
                    // Re-generate session ID
                    currController->session().sessionId = TSessionManager::instance().generateId();
                    tSystemDebug("Re-generate session ID: %s", currController->session().sessionId.data());
                }
                // Sets CSRF protection informaion
                TActionController::setCsrfProtectionInto(currController->session());
            }

            // Database Transaction
            transactions.setEnabled(currController->transactionEnabled());

            // Do filters
            if (currController->preFilter()) {

                // Dispathes
                bool dispatched = ctlrDispatcher.invoke(rt.action, rt.params);
                if (dispatched) {
                    autoRemoveFiles << currController->autoRemoveFiles;  // Adds auto-remove files

                    // Post fileter
                    currController->postFilter();

                    if (currController->rollbackRequested()) {
                        rollbackTransactions();
                    } else {
                        // Commits a transaction to the database
                        commitTransactions();
                    }

                    // Session store
                    if (currController->sessionEnabled()) {
                        bool stored = TSessionManager::instance().store(currController->session());
                        if (stored) {
                            QDateTime expire;
                            if (TSessionManager::sessionLifeTime() > 0) {
                                expire = QDateTime::currentDateTime().addSecs(TSessionManager::sessionLifeTime());
                            }

                            // Sets the path in the session cookie
                            QString cookiePath = Tf::app()->appSettings().value(SESSION_COOKIE_PATH).toString();
                            currController->addCookie(TSession::sessionName(), currController->session().id(), expire, cookiePath);
                        }
                    }
                }
            }

            // Sets charset to the content-type
            QByteArray ctype = currController->response.header().contentType().toLower();
            if (ctype.startsWith("text") && !ctype.contains("charset")) {
                ctype += "; charset=";
                ctype += Tf::app()->codecForHttpOutput()->name();
                currController->response.header().setContentType(ctype);
            }

            // Sets the default status code of HTTP response
            accessLogger.setStatusCode( (!currController->response.isBodyNull()) ? currController->statusCode() : Tf::InternalServerError );
            currController->response.header().setStatusLine(accessLogger.statusCode(), THttpUtility::getResponseReasonPhrase(accessLogger.statusCode()));

            // Writes a response and access log
            int bytes = writeResponse(currController->response.header(), currController->response.bodyIODevice(),
                                      currController->response.bodyLength());
            accessLogger.setResponseBytes(bytes);

            // Session GC
            TSessionManager::instance().collectGarbage();

        } else {
            accessLogger.setStatusCode( Tf::BadRequest );

            if (method == Tf::Get) {  // GET Method
                path.remove(0, 1);
                QFile reqPath(Tf::app()->publicPath() + path);
                QFileInfo fi(reqPath);

                if (fi.isFile() && fi.isReadable()) {
                    // Check "If-Modified-Since" header for caching
                    bool sendfile = true;
                    QByteArray ifModifiedSince = hdr.rawHeader("If-Modified-Since");

                    if (!ifModifiedSince.isEmpty()) {
                        QDateTime dt = THttpUtility::fromHttpDateTimeString(ifModifiedSince);
                        sendfile = (!dt.isValid() || dt != fi.lastModified());
                    }

                    if (sendfile) {
                        // Sends a request file
                        responseHeader.setRawHeader("Last-Modified", THttpUtility::toHttpDateTimeString(fi.lastModified()));
                        QByteArray type = Tf::app()->internetMediaType(fi.suffix());
                        int bytes = writeResponse(Tf::OK, responseHeader, type, &reqPath, reqPath.size());
                        accessLogger.setResponseBytes( bytes );
                    } else {
                        // Not send the data
                        int bytes = writeResponse(Tf::NotModified, responseHeader);
                        accessLogger.setResponseBytes( bytes );
                    }
                } else {
                    int bytes = writeResponse(Tf::NotFound, responseHeader);
                    accessLogger.setResponseBytes( bytes );
                }
                accessLogger.setStatusCode( responseHeader.statusCode() );

            } else if (method == Tf::Post) {
                // file upload?
            } else {
                // HEAD, DELETE, ...
            }
        }

    } catch (ClientErrorException &e) {
        tWarn("Caught ClientErrorException: status code:%d", e.statusCode());
        int bytes = writeResponse(e.statusCode(), responseHeader);
        accessLogger.setResponseBytes( bytes );
        accessLogger.setStatusCode( e.statusCode() );
    } catch (SqlException &e) {
        tError("Caught SqlException: %s  [%s:%d]", qPrintable(e.message()), qPrintable(e.fileName()), e.lineNumber());
        tSystemError("Caught SqlException: %s  [%s:%d]", qPrintable(e.message()), qPrintable(e.fileName()), e.lineNumber());
        closeHttpSocket();
    } catch (KvsException &e) {
        tError("Caught KvsException: %s  [%s:%d]", qPrintable(e.message()), qPrintable(e.fileName()), e.lineNumber());
        tSystemError("Caught KvsException: %s  [%s:%d]", qPrintable(e.message()), qPrintable(e.fileName()), e.lineNumber());
        closeHttpSocket();
    } catch (SecurityException &e) {
        tError("Caught SecurityException: %s  [%s:%d]", qPrintable(e.message()), qPrintable(e.fileName()), e.lineNumber());
        tSystemError("Caught SecurityException: %s  [%s:%d]", qPrintable(e.message()), qPrintable(e.fileName()), e.lineNumber());
        closeHttpSocket();
    } catch (RuntimeException &e) {
        tError("Caught RuntimeException: %s  [%s:%d]", qPrintable(e.message()), qPrintable(e.fileName()), e.lineNumber());
        tSystemError("Caught RuntimeException: %s  [%s:%d]", qPrintable(e.message()), qPrintable(e.fileName()), e.lineNumber());
        closeHttpSocket();
    } catch (...) {
        tError("Caught Exception");
        tSystemError("Caught Exception");
        closeHttpSocket();
    }

    // Push to the pool
    TActionContext::releaseSqlDatabases();
    TActionContext::releaseKvsDatabases();

    TActionContext::accessLogger.write();  // Writes access log
    releaseHttpSocket();
}
Example #4
0
void ProcessServer::onReceive( dword client, byte message, const InStream & input )
{
	//LOG_STATUS( "ProcessServer","onReceive, client = %u (%s), message = 0x%x", client, clientAddress(client), message );

	switch( message )
	{
	case ProcessClient::SERVER_LOGIN:
		{
			dword job;
			input >> job;
			CharString uid;
			input >> uid;
			CharString md5;
			input >> md5;

			bool result = false;

			MetaClient::Profile profile;
			if ( m_MetaClient.loginByProxy( uid, md5, profile ) > 0 )
			{
				LOG_STATUS( "ProcessServer", CharString().format("Login %s, client %u (%s)", profile.name.cstr(), client, clientAddress(client)) );
				result = (profile.flags & (MetaClient::ADMINISTRATOR|MetaClient::SERVER)) != 0;
			}
			else
				LOG_STATUS( "ProcessServer", CharString().format("Login failed, client %u (%s)", client, clientAddress(client)) );

			AutoLock lock( &m_Lock );

			m_ClientValid[ client ] = result;
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << result;
		}
		break;
	case ProcessClient::SERVER_SESSION_LOGIN:
		{
			dword job;
			input >> job;
			dword sessionId;
			input >> sessionId;

			bool result = false;

			MetaClient::Profile profile;
			if ( m_MetaClient.loginByProxy( sessionId, profile ) > 0 )
			{
				LOG_STATUS( "ProcessServer", CharString().format("Login %s, client %u (%s)", profile.name.cstr(), client, clientAddress(client)) );
				result = (profile.flags & MetaClient::ADMINISTRATOR) != 0;
			}
			else
				LOG_STATUS( "ProcessServer", CharString().format("Login failed, client %u (%s)", client, clientAddress(client)) );

			AutoLock lock( &m_Lock );

			m_ClientValid[ client ] = result;
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << result;
		}
		break;
	case ProcessClient::SERVER_SEND_PROCESS_LIST:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			// send process list to the server
			AutoLock lock( &m_Lock );
			send( client, ProcessClient::CLIENT_RECV_PROCESS_LIST ) << job << m_ProcessList;
		}
		break;
	case ProcessClient::SERVER_SEND_CONFIG:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			CharString config;
			CharString configFile;

			if ( processId != 0 )
			{
				Process proc;
				if ( findProcess( processId, proc ) )
					configFile = proc.config;
			}
			else
				configFile = m_Context.config;

			LOG_STATUS( "ProcessServer", CharString().format("Send Config, client %u (%s), configFile = %s", 
				client, clientAddress(client), configFile.cstr()) );

			// attempt to load the configuration file
			char * pConfig = FileDisk::loadTextFile( configFile );
			if ( pConfig != NULL )
			{
				config = pConfig;
				delete [] pConfig;
			}

			send( client, ProcessClient::CLIENT_RECV_CONFIG ) << job << config;
		}
		break;
	case ProcessClient::SERVER_RECV_CONFIG:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;
			CharString config;
			input >> config;

			bool jobDone = false;

			CharString configFile;
			if ( processId != 0 )
			{
				Process proc;
				if ( findProcess( processId, proc ) )
					configFile = proc.config;
			}
			else
				configFile = m_Context.config;

			LOG_STATUS( "ProcessServer", "Recv Config, client %u (%s), configFile = %s", 
				client, clientAddress(client), configFile.cstr() );

			// save the new file
			jobDone = FileDisk::saveTextFile( configFile, CharString( config ) );

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_SEND_LOG:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			CharString log;
			CharString logFile;
			if ( processId != 0 )
			{
				// send log of one of our processes
				Process proc;
				if ( findProcess( processId, proc ) )
					logFile = proc.log;
			}
			else
				logFile = m_Context.logFile;

			FileDisk file;
			if ( file.open( logFile ) )
			{
				dword size = file.size();
				if ( size > MAX_LOG_SIZE )
				{
					file.setPosition( size - MAX_LOG_SIZE );
					size = MAX_LOG_SIZE;
				}

				char * pLog = new char[ size + 1];
				pLog[ size ] = 0;

				file.read( pLog, size );
				file.close();

				// save to string
				log = pLog;
				// release allocated memory
				delete [] pLog;
			}
			else
				log = "Failed to open log file!";


			send( client, ProcessClient::CLIENT_RECV_LOG ) << job << log;
		}
		break;
	case ProcessClient::SERVER_ADD_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			Process proc;
			input >> proc;

			AutoLock lock( &m_Lock );

			proc.processId = m_NextProcessId++;
			m_ProcessList.push( proc );

			LOG_STATUS( "ProcessServer", "Add Process, client = %u (%s), processId = %u, name = %s, exec = %s", 
				client, clientAddress(client), proc.processId, proc.name.cstr(), proc.executable.cstr() );

			saveProcessList();
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << true;
		}
		break;
	case ProcessClient::SERVER_SET_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			Process proc;
			input >> proc;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			int pi = findProcess( proc.processId );
			if ( pi >= 0 )
			{
				m_ProcessList[pi] = proc;
				jobDone = true;

				LOG_STATUS( "ProcessServer", "Set Process, client = %u (%s), processId = %u, name = %s, exec = %s", 
					client, clientAddress(client), proc.processId, proc.name.cstr(), proc.executable.cstr() );

				saveProcessList();
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_DEL_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			int pi = findProcess( processId );
			if ( pi >= 0 )
			{
				LOG_STATUS( "ProcessServer", "Delete Process, name = %s, client = %u (%s), processId = %u", 
					m_ProcessList[pi].name.cstr(), client, clientAddress(client), processId );

				// stop the actual process if any
				if ( m_ProcessInfo.find( processId ).valid() )
				{
					::Process::stop( m_ProcessInfo[ processId ].m_pHandle );
					m_ProcessInfo.remove( processId );
				}

				// remove from the list
				m_ProcessList.remove( pi );
				jobDone = true;

				saveProcessList();
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_STOP_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			int pi = findProcess( processId );
			if ( pi >= 0 )
			{
				m_ProcessList[ pi ].flags |= ProcessClient::PF_DISABLED;
				jobDone = true;

				LOG_STATUS( "ProcessServer", "Stop Process, name = %s, client = %u (%s), processId = %u", 
					m_ProcessList[pi].name.cstr(), client, clientAddress(client), processId );

				saveProcessList();
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_START_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			int pi = findProcess( processId );
			if ( pi >= 0 )
			{
				m_ProcessList[ pi ].flags &= ~ProcessClient::PF_DISABLED;
				jobDone = true;

				LOG_STATUS( "ProcessServer", "Start Process, name = %s, client = %u (%s), processId = %u", 
					m_ProcessList[pi].name.cstr(), client, clientAddress(client), processId );
				saveProcessList();
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_RESTART_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			Process proc;
			if ( findProcess( processId, proc ) )
			{
				if ( m_ProcessInfo.find( processId ).valid() )
				{
					jobDone = stopProcess( processId );

					LOG_STATUS( "ProcessServer", "Restart Process, name = %s, client = %u (%s), processId = %u,", 
						proc.name.cstr(), client, clientAddress(client), processId );
				}
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_SEND_STATUS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			AutoLock lock( &m_Lock );

			ProcessClient::Status status;
			status.processGroup = m_Context.processGroup;
			status.networkGroup = m_Context.networkGroup;
			status.cpuUsage = cpuUsage();
			status.memoryUsage = memoryUsage();	
			status.processCount = 0;

			for(int i=0;i<m_ProcessList.size();i++)
				if ( (m_ProcessList[i].flags & ProcessClient::PF_RUNNING) != 0 )
					status.processCount++;

			send( client, ProcessClient::CLIENT_RECV_STATUS ) << job << status;
		}
		break;
	case ProcessClient::SERVER_STOP_ALL:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			bool jobDone = false;

			AutoLock lock( &m_Lock );
			for(int i=0;i<m_ProcessList.size();i++)
				m_ProcessList[i].flags |= ProcessClient::PF_DISABLED;
			saveProcessList();

			jobDone = true;

			LOG_STATUS( "ProcessServer", CharString().format("Stop All, client = %u (%s)", client, clientAddress(client)) );
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_START_ALL:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			bool jobDone = false;

			AutoLock lock( &m_Lock );
			for(int i=0;i<m_ProcessList.size();i++)
				m_ProcessList[i].flags &= ~ProcessClient::PF_DISABLED;
			saveProcessList();

			jobDone = true;
			LOG_STATUS( "ProcessServer", CharString().format("Start All, client = %u (%s)", client, clientAddress(client)) );
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_RESTART_ALL:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			bool jobDone = false;

			AutoLock lock( &m_Lock );
			for(int i=0;i<m_ProcessList.size();i++)
				stopProcess( m_ProcessList[i].processId );

			jobDone = true;
			LOG_STATUS( "ProcessServer", CharString().format("Restart All, client = %u (%s)", client, clientAddress(client)) );
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_REBOOT:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			bool jobDone = reboot();
			if ( jobDone )
				LOG_STATUS( "ProcessServer", CharString().format("Server Rebooting, client = %u (%s)", client, clientAddress(client)) );

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_EXIT:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			// signal all running processes to stop
			bool jobDone = shutdown();
			if ( jobDone )
				LOG_STATUS( "ProcessServer", CharString().format("Server Exiting, client = %u (%s)", client, clientAddress(client)) );

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_TERMINATE_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			Process proc;
			if ( findProcess( processId, proc ) )
			{
				// just terminate the process
				if ( m_ProcessInfo.find( processId ).valid() )
				{
					::Process::stop( m_ProcessInfo[ processId ].m_pHandle );
					jobDone = true;

					LOG_STATUS( "ProcessServer", "Terminated Process, name = %s, client = %u (%s), processId = %u,", 
						proc.name.cstr(), client, clientAddress(client), processId );
				}
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_OPEN_LOG:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			CharString logFile;
			if ( processId != 0 )
			{
				// send log of one of our processes
				Process proc;
				if ( findProcess( processId, proc ) )
					logFile = proc.log;
			}
			else
				logFile = m_Context.logFile;

			dword logId = m_NextLogId++;

			AutoLock lock( &m_Lock );

			FileDisk & file = m_LogFile[ logId ];
			if ( file.open( logFile ) )
			{
				LOG_STATUS( "ProcessServer", "Open Log, logFile = %s, logId = %u, clientId = %u", logFile.cstr(), logId, client );

				m_ActiveLog.push( logId );
				m_LogClient[ logId ] = client;
				m_ClientLog[ client ].push( logId );
			}
			else
			{
				LOG_STATUS( "ProcessServer", "Open Log Failed, logFile = %s, clientId = %u", logFile.cstr(), client );

				// failed to open file
				m_LogFile.remove( logId );
				// set id to 0 for error
				logId = 0;
			}

			send( client, ProcessClient::CLIENT_RECV_LOG_ID ) << job << logId;
		}
		break;
	case ProcessClient::SERVER_CLOSE_LOG:
		if ( validateClient( client ) )
		{
			dword logId;
			input >> logId;

			AutoLock lock( &m_Lock );

			LOG_STATUS( "ProcessServer", CharString().format("Close Log, logId = %u, client = %u", logId, client) );

			m_ActiveLog.removeSearch( logId );
			m_LogFile.remove( logId );
			m_LogClient.remove( logId );
			m_ClientLog[ client ].removeSearch( logId );
		}
		break;
	case ProcessClient::SERVER_SEARCH_LOGS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			ProcessClient::SearchLogRequest req;
			input >> req;

			LOG_STATUS( "ProcessServer", CharString().format("Search Log, clientId = %u", client) );

			CharString result;
			if( req.filemask.find('/') >= 0 || req.filemask.find('\\') >= 0 )
			{	// this should never happen, unless the user has a hacked client
				LOG_STATUS( "ProcessServer", CharString().format("Search Log, invalid filemask received from clientId = %u", client) );
				result = "Failed";
			}
			else
			{
				result = searchLogFiles( req.filemask, req.searchString, req.isRegExp, req.searchLevel, req.resolveClientId );
			}

			send( client, ProcessClient::CLIENT_RECV_SEARCHRESULT ) << job << result;
		}
		break;
	case ProcessClient::PING:
		send( client, ProcessClient::PONG );
		break;
	case ProcessClient::PONG:
		break;
	default:
		{
			LOG_ERROR( "ProcessServer", CharString().format("Bad Message, client = %u (%s), message = %d", client, clientAddress(client), message) );
			removeClient( client );
		}
		break;
	}
}
Example #5
0
void ProcessServer::onConnect( dword client )
{
	LOG_STATUS( "ProcessServer", CharString().format("Connecting client %u from %s", client, clientAddress( client )) );

	AutoLock lock( &m_Lock );
	m_ClientValid[ client ] = false;
}
Example #6
0
bool ProcessServer::validateClient( dword client )
{
	AutoLock lock( &m_Lock );
	Hash<dword,bool>::Iterator find = m_ClientValid.find( client );
	if ( find.valid() && *find )
		return true;

	LOG_STATUS( "ProcessServer", CharString().format("Failed validation, client = %d (%s)", client, clientAddress(client)) );
	removeClient( client );

	return false;
}
Example #7
0
// called by updateClients() normally... server is already expected to be locked
void WorldServer::receiveMessage( ClientContext & context, bool bUDP, byte nMessage, const InStream & input )
{
#if MESSAGE_WARNING_TIME > 0
	dword nStart = Time::milliseconds();
#endif

	dword nClientId = context.nClientId;
	if ( nClientId == 0 )
		throw FileSocket::FileError();			// client has been disconnected, force this to stop..

	switch( nMessage )
	{
	case WorldClient::SERVER_SEND_VERSION:
		{
			TRACE( "SERVER_SEND_VERSION" );

			dword job;
			input >> job;

			// send our version to the client
			send( context.nClientId, WorldClient::CLIENT_RECV_VERSION ) 
				<< job << version() << context.nClientId;
		}
		break;
	case WorldClient::SERVER_LOGIN:
		{
			TRACE( "SERVER_LOGIN" );

			dword nVersion;
			input >> nVersion;

			if ( version() == nVersion )
			{
				LoginJob & job = m_LoginQueue.push();
				job.bDone = false;
				job.nClientId = context.nClientId;

				input >> job.nSessionId;		// client is sending it's key from the MetaServer
				input >> job.bTransfer;
				input >> job.bProxy;

				if ( job.bProxy )
				{
					input >> job.nProxyId;
					input >> job.nProxyFaction;
				}
				
				input >> job.bServer;

				// if we are in tutorial mode or session id is 0 and from the localhost, then run without login information..
				if ( m_Context.bTutorial || (job.nSessionId == 0 
					&& strcmp( clientAddress( context.nClientId ), "127.0.0.1" ) == 0) )
				{
					// initialize "Cadet" account, allowed on tutorial servers only!
					job.bDone = true;
					job.profile.userId = 0xffffffff;
					job.profile.sessionId = job.nSessionId;
					job.profile.clanId = 0;
					job.profile.flags = MetaClient::DEMO|MetaClient::SUBSCRIBED|MetaClient::ADMINISTRATOR;
					job.profile.name = "Cadet";
					job.profile.score = 0.0f;
				}
			}
			else
			{