示例#1
0
bool CLocalServer::Save ( void )
{
    if ( m_pConfig && m_pConfig->GetRootNode() )
    {
        StoreConfigValue ( "servername", ( m_pEditName->GetText().length() > 0 ) ? m_pEditName->GetText().c_str() : "MTA Local Server" );
        StoreConfigValue ( "maxplayers", ( atoi ( m_pEditPlayers->GetText().c_str() ) ) ? m_pEditPlayers->GetText().c_str() : "32" );
        StoreConfigValue ( "donotbroadcastlan", ( m_pBroadcastLan->IsActive () ) ? "0" : "1" );
        StoreConfigValue ( "ase", ( m_pBroadcastInternet->IsActive () ) ? "1" : "0" );
        StoreConfigValue ( "password", m_pEditPass->GetText().c_str() );

        // Remove old resources from the config
        CXMLNode* pRoot = m_pConfig->GetRootNode();
        list < CXMLNode* > ::const_iterator iter = pRoot->ChildrenBegin ();
        for ( ; iter != pRoot->ChildrenEnd (); iter++ )
        {
            CXMLNode* pNode = reinterpret_cast < CXMLNode* > ( *iter );
            if ( pNode->GetTagName().compare ( "resource" ) == 0 )
            {
                pRoot->DeleteSubNode ( pNode );
                iter = pRoot->ChildrenBegin ();
            }
        }

        // Add new resources to the config
        for ( int i = 0; i < m_pResourcesCur->GetRowCount(); i++ )
        {
            CXMLNode* pResourceNode = pRoot->CreateSubNode ( "resource" );
            pResourceNode->GetAttributes().Create ( "src" )->SetValue ( m_pResourcesCur->GetItemText ( i, 1 ) );
            pResourceNode->GetAttributes().Create ( "startup" )->SetValue ( "1" );
            pResourceNode->GetAttributes().Create ( "protected" )->SetValue ( "0" );
        }
        m_pConfig->Write ();
    }
    return true;
}
示例#2
0
int CLuaXMLDefs::xmlNodeGetAttributes ( lua_State* luaVM )
{
    // pNode, Attribute Name, [Buffer Size]
    if ( lua_type ( luaVM, 1 ) == LUA_TLIGHTUSERDATA )
    {
        CXMLNode* pNode = lua_toxmlnode ( luaVM, 1 );
        if ( pNode )
        {
            lua_newtable ( luaVM );
            list < class CXMLAttribute * > ::iterator iter = pNode->GetAttributes().ListBegin();
            for ( ; iter != pNode->GetAttributes().ListEnd() ; iter++ )
            {
                lua_pushstring ( luaVM, ( *iter )->GetName().c_str () );
                lua_pushstring ( luaVM, ( *iter )->GetValue().c_str () );
                lua_settable ( luaVM, -3 );
            }
            return 1;
        }
        else
            m_pScriptDebugging->LogBadType ( luaVM, "xmlNodeGetAttributes" );
    }
    else
        m_pScriptDebugging->LogBadType ( luaVM, "xmlNodeGetAttributes" );

    lua_pushboolean ( luaVM, false );
    return 1;
}
示例#3
0
bool CServerBrowser::SaveServerList ( CXMLNode* pNode, std::string strTagName, CServerList *pList )
{
    if ( !pNode )
        return false;

    // Start by clearing out all previous nodes
    pNode->DeleteAllSubNodes ();

    // Iterate through the list, adding any items to our node
    CServerListIterator i, i_b = pList->IteratorBegin (), i_e = pList->IteratorEnd ();
    int j = 0;
    int k = pList->GetServerCount ();
    if ( k > 0 )
    {
        for ( CServerListIterator i = i_b; i != i_e; i++ )
        {
            CServerListItem * pServer = *i;

            // Add the item to the node
            CXMLNode * pSubNode = pNode->CreateSubNode ( strTagName.c_str () );
            if ( pSubNode )
            {
                CXMLAttribute* pHostAttribute = pSubNode->GetAttributes ().Create ( "host" );
				pHostAttribute->SetValue ( pServer->strHost.c_str () );
                
                CXMLAttribute* pPortAttribute = pSubNode->GetAttributes ().Create ( "port" );
				pPortAttribute->SetValue ( pServer->usGamePort );
            }
            j++;
        }
    }
    return true;
}
int CLuaFunctionDefs::XMLNodeGetAttributes ( lua_State* luaVM )
{
    // pNode, Attribute Name, [Buffer Size]
    CXMLNode* pNode = NULL;
    CScriptArgReader argStream ( luaVM );
    argStream.ReadUserData ( pNode );

    if ( !argStream.HasErrors ( ) )
    {
        if ( pNode )
        {
            lua_newtable ( luaVM );
            unsigned int uiIndex = 0;
            list < CXMLAttribute * > ::iterator iter = pNode->GetAttributes ().ListBegin ();
            for ( ; iter != pNode->GetAttributes ().ListEnd () ; iter++ )
            {
                lua_pushstring ( luaVM, ( *iter )->GetName ().c_str () );
                lua_pushstring ( luaVM, ( *iter )->GetValue ().c_str () );
                lua_settable ( luaVM, -3 );
            }
            return 1;
        }
        else
            m_pScriptDebugging->LogBadType ( luaVM );
    }
    else
        m_pScriptDebugging->LogCustom ( luaVM, argStream.GetFullErrorMessage() );

    lua_pushboolean ( luaVM, false );
    return 1;
}
示例#5
0
void CServerBrowser::SetServerPassword ( std::string strHost, std::string strPassword )
{
    CXMLNode* pConfig = CCore::GetSingletonPtr ()->GetConfig ();
    CXMLNode* pServerPasswords = pConfig->FindSubNode ( CONFIG_NODE_SERVER_SAVED );
    if ( !pServerPasswords )
    {
        pServerPasswords = pConfig ->CreateSubNode ( CONFIG_NODE_SERVER_SAVED );
    }
    //Check if the server password already exists
    for ( unsigned int i = 0 ; i < pServerPasswords->GetSubNodeCount() ; i++ )
    {    
        CXMLAttributes* pAttributes = &(pServerPasswords->GetSubNode(i)->GetAttributes());
        if ( pAttributes->Find( "host" ) )
        {
            if ( CXMLAttribute* pHost = pAttributes->Find ( "host" ) )
            {
                std::string strXMLHost = pHost->GetValue();
                if ( strXMLHost == strHost )
                {
                    CXMLAttribute* pPassword = pAttributes->Create( "password" );
                    pPassword->SetValue(strPassword.c_str());
                    return;
                }
            }
        }
        
    }

    // Otherwise create the node from scratch
    CXMLNode* pNode = pServerPasswords->CreateSubNode( "server" );
    CXMLAttribute* pHostAttribute = pNode->GetAttributes().Create ( "host" );
    pHostAttribute->SetValue(strHost.c_str());
    CXMLAttribute* pPasswordAttribute = pNode->GetAttributes().Create ( "password" );
    pPasswordAttribute->SetValue(strPassword.c_str());
}
示例#6
0
int CLuaXMLDefs::xmlNodeGetAttributes ( lua_State* luaVM )
{  
    CXMLNode* pNode;
        
    CScriptArgReader argStream ( luaVM );
    argStream.ReadUserData ( pNode );

    if ( !argStream.HasErrors () )
    {
        lua_newtable ( luaVM );
        list < class CXMLAttribute * > ::iterator iter = pNode->GetAttributes().ListBegin();
        for ( ; iter != pNode->GetAttributes().ListEnd() ; ++iter )
        {
            lua_pushstring ( luaVM, ( *iter )->GetName().c_str () );
            lua_pushstring ( luaVM, ( *iter )->GetValue().c_str () );
            lua_settable ( luaVM, -3 );
        }
        return 1;
    }
    else
        m_pScriptDebugging->LogCustom ( luaVM, argStream.GetFullErrorMessage () );

    lua_pushboolean ( luaVM, false );
    return 1;
}
void CAccessControlListGroup::WriteToXMLNode ( CXMLNode* pNode )
{
    assert ( pNode );

    // Create the subnode for this
    CXMLNode* pSubNode = pNode->CreateSubNode ( "group" );
    assert ( pSubNode );

    // Create attribute for the name and set it
    CXMLAttribute* pAttribute = pSubNode->GetAttributes ().Create ( "name" );
    pAttribute->SetValue ( m_strGroupName );

    // Write the ACL's this group use
    ACLsList::iterator iterACL = m_ACLs.begin ();
    for ( ; iterACL != m_ACLs.end (); iterACL++ )
    {
        CAccessControlList* pACL = *iterACL;

        // Create the subnode for this object and write the name attribute we generated
        CXMLNode* pObjectNode = pSubNode->CreateSubNode ( "acl" );
        pAttribute = pObjectNode->GetAttributes ().Create ( "name" );
        pAttribute->SetValue ( pACL->GetName () );
    }

    // Write every object
    ObjectList::iterator iter = m_Objects.begin ();
    for ( ; iter != m_Objects.end (); iter++ )
    {
        CAccessControlListGroupObject* pObject = *iter;

        // Find out the object type string
        char szObjectType [255];
        switch ( pObject->GetObjectType () )
        {
            case CAccessControlListGroupObject::OBJECT_TYPE_RESOURCE:
                strcpy ( szObjectType, "resource" );
                break;

            case CAccessControlListGroupObject::OBJECT_TYPE_USER:
                strcpy ( szObjectType, "user" );
                break;

            default:
                strcpy ( szObjectType, "error" );
                break;
        }

        // Append a dot append the name of the node
        strcat ( szObjectType, "." );
        strncat ( szObjectType, pObject->GetObjectName (), NUMELMS( szObjectType ) - 1 );

        // Create the subnode for this object and write the name attribute we generated
        CXMLNode* pObjectNode = pSubNode->CreateSubNode ( "object" );
        pAttribute = pObjectNode->GetAttributes ().Create ( "name" );
        pAttribute->SetValue ( szObjectType );
    }
}
示例#8
0
int CLuaXMLDefs::xmlNodeSetAttribute ( lua_State* luaVM )
{
    // pNode, Attribute Name, Value
    int iType1 = lua_type ( luaVM, 1 );
    int iType2 = lua_type ( luaVM, 2 );
    int iType3 = lua_type ( luaVM, 3 );
    if ( ( iType1 == LUA_TLIGHTUSERDATA ) &&
         ( iType2 == LUA_TSTRING ) &&
         ( iType3 == LUA_TSTRING || iType3 == LUA_TNUMBER || iType3 == LUA_TNIL ) )
    {
        // Grab the xml node
        CXMLNode* pNode = lua_toxmlnode ( luaVM, 1 );
        if ( pNode )
        {
            // Grab the attribute name and value
            const char * szAttributeName = lua_tostring ( luaVM, 2 );

            // Are we going to set it to a value?
            if ( iType3 == LUA_TSTRING || iType3 == LUA_TNUMBER )
            {
                const char * szAttributeValue = lua_tostring ( luaVM, 3 );

                // Write the node
                CXMLAttribute* pAttribute = pNode->GetAttributes ().Create ( szAttributeName );
                if ( pAttribute )
                {
                    pAttribute->SetValue ( szAttributeValue );

                    lua_pushboolean ( luaVM, true );
                    return 1;
                }
            }
            else
            {
                // Delete the attribute if it exists
                CXMLAttribute* pAttribute = pNode->GetAttributes ().Find ( szAttributeName );
                if ( pAttribute )
                {
                    delete pAttribute;

                    lua_pushboolean ( luaVM, true );
                    return 1;
                }
            }
        }
    }
    else
    {
        m_pScriptDebugging->LogBadType ( luaVM, "xmlNodeSetAttribute" );

        lua_pushboolean ( luaVM, false );
        return 1;
    }

    lua_pushboolean ( luaVM, false );
    return 1;
}
int CLuaFunctionDefs::XMLNodeSetAttribute ( lua_State* luaVM )
{
    // pNode, Attribute Name, Value
    CXMLNode* pNode = NULL;
    SString strAttributeName = "";
    SString strAttributeValue = "";
    CScriptArgReader argStream ( luaVM );
    argStream.ReadUserData ( pNode );
    argStream.ReadString ( strAttributeName );
    argStream.ReadString ( strAttributeValue, "" );

    if ( !argStream.HasErrors ( ) )
    {
        if ( pNode )
        {
            // Are we going to set it to a value?
            if ( argStream.NextCouldBeString( -1 ) )
            {
                // Write the node
                CXMLAttribute* pAttribute = pNode->GetAttributes ().Create ( strAttributeName );
                if ( pAttribute )
                {
                    pAttribute->SetValue ( strAttributeValue );

                    lua_pushboolean ( luaVM, true );
                    return 1;
                }
            }
            else
            {
                // Delete the attribute if it exists
                CXMLAttribute* pAttribute = pNode->GetAttributes ().Find ( strAttributeName );
                if ( pAttribute )
                {
                    delete pAttribute;

                    lua_pushboolean ( luaVM, true );
                    return 1;
                }
            }
        }
    }
    else
        m_pScriptDebugging->LogCustom ( luaVM, argStream.GetFullErrorMessage() );

    lua_pushboolean ( luaVM, false );
    return 1;
}
示例#10
0
bool CServerBrowser::LoadServerList ( CXMLNode* pNode, std::string strTagName, CServerList *pList )
{
    CXMLNode* pSubNode = NULL;
    in_addr Address;
    int iPort;

    if ( !pNode )
        return false;

    // Loop through all subnodes looking for relevant nodes
    unsigned int uiCount = pNode->GetSubNodeCount ();
    for ( unsigned int i = 0; i < uiCount; i++ )
    {
        pSubNode = pNode->GetSubNode ( i );
        if ( pSubNode && pSubNode->GetTagName ().compare ( strTagName ) == 0 )
        {
            // This node is relevant, so get the attributes we need and add it to the list
            CXMLAttribute* pHostAttribute = pSubNode->GetAttributes ().Find ( "host" );
            CXMLAttribute* pPortAttribute = pSubNode->GetAttributes ().Find ( "port" );
            if ( pHostAttribute && pPortAttribute ) {
                if ( CServerListItem::Parse ( pHostAttribute->GetValue ().c_str (), Address ) )
                {
                    iPort = atoi ( pPortAttribute->GetValue ().c_str () ) + SERVER_LIST_QUERY_PORT_OFFSET;
                    if ( iPort > 0 )
                        pList->Add ( CServerListItem ( Address, iPort ) );
                }
            }
        }
    }
    pList->SetUpdated ( true );
    return true;
}
示例#11
0
//////////////////////////////////////////////////////////////////////
//
// Fetch multiple values for a named setting from the server config
//
//  <module src="module_test.dll" />
//  <resource src="admin" startup="1" protected="0" />
//
//////////////////////////////////////////////////////////////////////
bool CMainConfig::GetSettingTable ( const SString& strName, const char** szAttribNames, uint uiNumAttribNames, CLuaArguments* outTable )
{
    uint uiXMLIndex = 0;
    uint uiLuaIndex = 1;
    CXMLNode* pNode = NULL;
    do
    {
        // Grab the current script node
        pNode = m_pRootNode->FindSubNode ( strName, uiXMLIndex++ );
        if ( pNode )
        {
            CLuaArguments resultLine;
            CXMLAttributes& attributes = pNode->GetAttributes();
            for ( uint i = 0 ; i < attributes.Count() ; i++ )
            {
                CXMLAttribute* pAttribute = attributes.Get( i );
                resultLine.PushString( pAttribute->GetName() );
                resultLine.PushString( pAttribute->GetValue() );
            }

            if ( resultLine.Count() != 0 )
            {
                outTable->PushNumber( uiLuaIndex++ );
                outTable->PushTable( &resultLine );
            }
        }
    }
    while( pNode );

    return outTable->Count() != 0;
}
示例#12
0
///////////////////////////////////////////////////////////////
//
// CServerIdManagerImpl::StaticSaveServerIdMap
//
//
//
///////////////////////////////////////////////////////////////
void CServerIdManagerImpl::StaticSaveServerIdMap ( void )
{
    CXMLFile* pConfigFile = g_pCore->GetXML ()->CreateXML ( PathJoin ( g_pClientGame->GetFileCacheRoot(), MTA_SERVERID_LOOKUP_XML ) );
    if ( !pConfigFile )
        return;
    pConfigFile->Reset ();

    CXMLNode* pRoot = pConfigFile->GetRootNode ();
    if ( !pRoot )
        pRoot = pConfigFile->CreateRootNode ( "root" );

    // Transfer each item from m_ServerIdMap into the file
    for ( std::map < CServerIdKey, CServerIdInfo >::iterator it = ms_ServerIdMap.begin () ; it != ms_ServerIdMap.end () ; ++it )
    {
        const SString& strId = it->first.strId;
        const SString& strDir = it->second.strDir;

        CXMLNode* pSubNode = pRoot->CreateSubNode ( "id" );
        pSubNode->SetTagContent ( strId );
        pSubNode->GetAttributes().Create ( "dir" )->SetValue ( strDir );
    }

    pConfigFile->Write ();
    delete pConfigFile;
}
示例#13
0
int CLuaXMLDefs::xmlNodeGetAttribute ( lua_State* luaVM )
{
    CXMLNode* pNode = nullptr;
    SString strAttributeName = "";
    CScriptArgReader argStream ( luaVM );
    argStream.ReadUserData ( pNode );
    argStream.ReadString ( strAttributeName );

    if ( !argStream.HasErrors () )
    {
        // Find the attribute with that name
        CXMLAttribute * pAttribute = pNode->GetAttributes ().Find ( strAttributeName );
        if ( pAttribute )
        {
            // Read the attribute and return the string
            lua_pushstring ( luaVM, pAttribute->GetValue ().c_str () );
            return 1;
        }
    }
    else
        m_pScriptDebugging->LogCustom ( luaVM, argStream.GetFullErrorMessage () );

    lua_pushboolean ( luaVM, false );
    return 1;
}
示例#14
0
///////////////////////////////////////////////////////////////
//
// CServerIdManagerImpl::LoadServerIdMap
//
// Load server id data from xml file
//
///////////////////////////////////////////////////////////////
bool CServerIdManagerImpl::LoadServerIdMap ( void )
{
    // Load config XML file
    CXMLFile* pConfigFile = g_pCore->GetXML ()->CreateXML ( PathJoin ( g_pClientGame->GetFileCacheRoot(), MTA_SERVERID_LOOKUP_XML ) );
    if ( !pConfigFile )
        return false;
    pConfigFile->Parse ();

    CXMLNode* pRoot = pConfigFile->GetRootNode ();
    if ( !pRoot )
        pRoot = pConfigFile->CreateRootNode ( "root" );

    m_ServerIdMap.clear ();

    // Read each node
    for ( uint i = 0 ; i < pRoot->GetSubNodeCount () ; i++ )
    {
        CXMLNode* pSubNode = pRoot->GetSubNode ( i );

        CServerIdKey key;
        CServerIdInfo info;
        key.strId = pSubNode->GetTagContent ();
        if ( CXMLAttribute* pAttribute = pSubNode->GetAttributes().Find ( "dir" ) )
            info.strDir = pAttribute->GetValue ();

        if ( !info.strDir.empty () )
            MapSet ( m_ServerIdMap, key, info );
    }

    // Maybe one day remove unwanted directories

    delete pConfigFile;
    return true;
}
示例#15
0
// Creates a new setting and adds it to the destination node
CXMLNode *CSettings::CreateSetting(CXMLNode *pDst, const char *szName, const char *szContent)
{
    // Create the node
    CXMLNode *      pNode = pDst->CreateSubNode("setting");
    CXMLAttributes *pAttributes = &(pNode->GetAttributes());

    // Add the attributes with the corresponding values
    pAttributes->Create("name")->SetValue(szName);
    pAttributes->Create("value")->SetValue(szContent);

    return pNode;
}
示例#16
0
///////////////////////////////////////////////////////////////
//
// CResourceChecker::CheckMetaSourceForIssues
//
//
//
///////////////////////////////////////////////////////////////
void CResourceChecker::CheckMetaSourceForIssues ( CXMLNode* pRootNode, const string& strFileName, const string& strResourceName, ECheckerModeType checkerMode, bool* pbOutHasChanged )
{
    // Check min_mta_version is correct
    if ( m_strReqClientVersion > m_strMinClientReqFromMetaXml || m_strReqServerVersion > m_strMinServerReqFromMetaXml )
    {
        // It's not right. What to do?
        if ( checkerMode == ECheckerMode::WARNINGS )
        {
            SString strTemp = "<min_mta_version> section in the meta.xml is incorrect or missing (expected at least ";
            if ( m_strReqClientVersion > m_strMinClientReqFromMetaXml )
                strTemp += SString ( "client %s because of '%s')", *m_strReqClientVersion, *m_strReqClientReason );
            else
            if ( m_strReqServerVersion > m_strMinServerReqFromMetaXml )
                strTemp += SString ( "server %s because of '%s')", *m_strReqServerVersion, *m_strReqServerReason );

            CLogger::LogPrint ( SString ( "WARNING: %s %s\n", strResourceName.c_str (), *strTemp ) );
        }
        else
        if ( checkerMode == ECheckerMode::UPGRADE )
        {
            // Create min_mta_version node if required
            CXMLNode* pNodeMinMtaVersion = pRootNode->FindSubNode("min_mta_version", 0);
            if ( !pNodeMinMtaVersion )
                pNodeMinMtaVersion = pRootNode->CreateSubNode ( "min_mta_version" );

            CXMLAttributes& attributes = pNodeMinMtaVersion->GetAttributes ();
            attributes.Delete ( "server" );
            attributes.Delete ( "client" );
            attributes.Delete ( "both" );

            if ( !m_strReqServerVersion.empty () )
            {
                CXMLAttribute* pAttr = attributes.Create ( "server" );
                pAttr->SetValue ( m_strReqServerVersion );
            }

            if ( !m_strReqClientVersion.empty () )
            {
                CXMLAttribute* pAttr = attributes.Create ( "client" );
                pAttr->SetValue ( m_strReqClientVersion );
            }

            if ( pbOutHasChanged )
                *pbOutHasChanged = true;
        }
    }
}
示例#17
0
int CLuaXMLDefs::xmlNodeGetAttribute ( lua_State* luaVM )
{
    // pNode, Attribute Name, [Buffer Size]
    int iThirdVariableType = lua_type ( luaVM, 3 );
    if ( lua_type ( luaVM, 1 ) != LUA_TLIGHTUSERDATA ||
        !( iThirdVariableType == LUA_TNONE || iThirdVariableType == LUA_TNUMBER ) ||
        lua_type ( luaVM, 2 ) != LUA_TSTRING )
    {
        m_pScriptDebugging->LogBadType ( luaVM, "xmlNodeGetAttribute" );

        lua_pushboolean ( luaVM, false );
        return 1;
    }
    else
    {
        // Grab the XML node
        CXMLNode* pNode = lua_toxmlnode ( luaVM, 1 );
        if ( pNode )
        {
            // Find the attribute with that name
            const char * szAttributeName = lua_tostring ( luaVM, 2 );
            CXMLAttribute * pAttribute = pNode->GetAttributes().Find ( szAttributeName );
            if ( pAttribute )
            {
                // Limit reading to that many characters
                unsigned int iBufferSize = 255;
                if ( iThirdVariableType == LUA_TNUMBER )
                {
                    iBufferSize = static_cast < unsigned int > ( lua_tonumber ( luaVM, 3 ) );
                    if ( iBufferSize > 1024 )
                        iBufferSize = 255;
                }

                // Read the attribute and return the string
                lua_pushstring ( luaVM, pAttribute->GetValue ().c_str () );
                return 1;
            }
        }
    }

    lua_pushboolean ( luaVM, false );
    return 1;
}
示例#18
0
bool CLocalServer::Load ( void )
{
    // Get server module root
    SString strServerPath = CalcMTASAPath( PathJoin ( "server", "mods", "deathmatch" ) );

    m_pConfig = g_pCore->GetXML ()->CreateXML ( PathJoin ( strServerPath, m_strConfig ) );
    if ( m_pConfig && m_pConfig->Parse() )
    {
        CXMLNode* pRoot = m_pConfig->GetRootNode();
        CXMLNode* pServerName = pRoot->FindSubNode ( "servername", 0 );
        if ( pServerName ) m_pEditName->SetText ( pServerName->GetTagContent().c_str() );
        CXMLNode* pServerPass = pRoot->FindSubNode ( "password", 0 );
        if ( pServerPass ) m_pEditPass->SetText ( pServerPass->GetTagContent().c_str() );
        CXMLNode* pServerPlayers = pRoot->FindSubNode ( "maxplayers", 0 );
        if ( pServerPlayers ) m_pEditPlayers->SetText ( pServerPlayers->GetTagContent().c_str() );

        // Read the startup resources
        list < CXMLNode* > ::const_iterator iter = pRoot->ChildrenBegin ();
        for ( ; iter != pRoot->ChildrenEnd (); iter++ )
        {
            CXMLNode* pNode = reinterpret_cast < CXMLNode* > ( *iter );
            if ( pNode->GetTagName ().compare ( "resource" ) == 0 )
            {
                CXMLAttribute* src = pNode->GetAttributes().Find ( "src" );
                if ( src && src->GetValue()[1] )
                {
                    m_pResourcesCur->SetItemText ( m_pResourcesCur->AddRow (), m_hResourcesCur, src->GetValue().c_str() );
                }
            }
        }
    }

    // Get list of resource names
    std::vector < SString > resourceNameList;
    GetResourceNameList ( resourceNameList, strServerPath );

    // Put resource names into the GUI
    for ( std::vector < SString >::iterator iter = resourceNameList.begin () ; iter != resourceNameList.end () ; ++iter )
        HandleResource ( *iter );

    return true;
}
示例#19
0
void CAccessControlList::WriteToXMLNode ( CXMLNode* pNode )
{
    assert ( pNode );

    // Create the subnode for this
    CXMLNode* pSubNode = pNode->CreateSubNode ( "acl" );
    assert ( pSubNode );

    // Create attribute for the name and set it
    CXMLAttribute* pAttribute = pSubNode->GetAttributes ().Create ( "name" );
    pAttribute->SetValue ( m_strACLName );

    // Loop through each right and write it to the ACL
    list < CAccessControlListRight* > ::iterator iter = m_Rights.begin ();
    for ( ; iter != m_Rights.end (); iter++ )
    {
        CAccessControlListRight* pRight = *iter;
        pRight->WriteToXMLNode ( pSubNode );
    }
}
示例#20
0
bool CMainConfig::Load ( void )
{
    // Eventually destroy the previously loaded xml
    if ( m_pFile )
    {
        delete m_pFile;
        m_pFile = NULL;
    }

    // Load the XML
    m_pFile = g_pServerInterface->GetXML ()->CreateXML ( GetFileName ().c_str () );
    if ( !m_pFile )
    {
        CLogger::ErrorPrintf ( "Error loading config file\n" );
        return false;
    }

    // Parse it
    if ( !m_pFile->Parse () )
    {
        CLogger::ErrorPrintf ( "Error parsing config file\n" );
        return false;
    }

    // Grab the XML root node
    m_pRootNode = m_pFile->GetRootNode ();
    if ( !m_pRootNode )
    {
        CLogger::ErrorPrintf ( "Missing root node ('config')\n" );
        return false;
    }

    // Name
    int iResult = GetString ( m_pRootNode, "servername", m_strServerName, 1, 96 );
    if ( iResult == DOESNT_EXIST )
    {
        CLogger::ErrorPrintf ( "Server name not specified in config\n" );
        return false;
    }
    else if ( iResult == INVALID_VALUE )
    {
        CLogger::ErrorPrintf ( "Server name must be between 1 and 96 characters\n" );
        return false;
    }

    // Grab the script debuglog
    GetString ( m_pRootNode, "serverip", m_strServerIP, 1 );

    // Grab the port
    int iTemp;
    iResult = GetInteger ( m_pRootNode, "serverport", iTemp, 1, 65535 );
    if ( iResult == IS_SUCCESS )
    {
        m_usServerPort = static_cast < unsigned short > ( iTemp );
    }
    else
    {
        if ( iResult == DOESNT_EXIST )
            CLogger::ErrorPrintf ( "Server port not specified in config\n" );
        else
            CLogger::ErrorPrintf ( "Server port must be between 1 and 65535\n" );

        return false;
    }

    // Grab the max players
    iResult = GetInteger ( m_pRootNode, "maxplayers", iTemp, 1, MAX_PLAYER_COUNT );
    if ( iResult == IS_SUCCESS )
    {
        m_uiHardMaxPlayers = iTemp;
        m_uiSoftMaxPlayers = iTemp;
    }
    else
    {
        if ( iResult == DOESNT_EXIST )
            CLogger::ErrorPrintf ( "Max players not specified in config\n" );
        else
            CLogger::ErrorPrintf ( "Max players must be between 1 and %u\n", MAX_PLAYER_COUNT );

        return false;
    }

    // httpserver
    iResult = GetBoolean ( m_pRootNode, "httpserver", m_bHTTPEnabled );
    if ( iResult == INVALID_VALUE )
    {
        CLogger::LogPrint ( "WARNING: Invalid value specified in \"httpserver\" tag; defaulting to 1\n" );
        m_bHTTPEnabled = true;
    }
    else if ( iResult == DOESNT_EXIST )
    {
        m_bHTTPEnabled = false;
    }

    // HTTPD port
    iResult = GetInteger ( m_pRootNode, "httpport", iTemp, 1, 65535 );
    if ( iResult == IS_SUCCESS )
    {
        m_usHTTPPort = static_cast < unsigned short > ( iTemp );
    }
    else
    {
        if ( iResult == DOESNT_EXIST )
            CLogger::ErrorPrintf ( "HTTP port is not specified in config\n" );
        else
            CLogger::ErrorPrintf ( "HTTP server port must be between 1 and 65535\n" );

        return false;
    }

    // HTTPD Download URL (if we want to host externally)
    if ( GetString ( m_pRootNode, "httpdownloadurl", m_strHTTPDownloadURL, 5 ) == IS_SUCCESS )
    {
        m_ucHTTPDownloadType = HTTP_DOWNLOAD_ENABLED_URL;
        m_strHTTPDownloadURL = SString ( m_strHTTPDownloadURL ).TrimEnd ( "/" );
    }
    else
    {
        m_ucHTTPDownloadType = HTTP_DOWNLOAD_ENABLED_PORT;
        m_strHTTPDownloadURL = "";
    }

    // httpmaxconnectionsperclient
    GetInteger ( m_pRootNode, "httpmaxconnectionsperclient", m_iHTTPMaxConnectionsPerClient, 1, 8 );
    m_iHTTPMaxConnectionsPerClient = Clamp ( 1, m_iHTTPMaxConnectionsPerClient, 8 );

    // httpthreadcount
    GetInteger ( m_pRootNode, "httpthreadcount", m_iHTTPThreadCount, 1, 20 );
    m_iHTTPThreadCount = Clamp ( 1, m_iHTTPThreadCount, 20 );

    // httpdosthreshold
    GetInteger ( m_pRootNode, "httpdosthreshold", m_iHTTPDosThreshold, 1, 10000 );
    m_iHTTPDosThreshold = Clamp ( 1, m_iHTTPDosThreshold, 10000 );

    // verifyclientsettings
    GetInteger ( m_pRootNode, "verifyclientsettings", m_iEnableClientChecks );

    // Handle the <client_file> nodes
    CXMLNode* pNode = NULL;
    unsigned int uiCurrentIndex = 0;
    do
    {
        // Grab the current script node
        pNode = m_pRootNode->FindSubNode ( "client_file", uiCurrentIndex++ );
        if ( pNode )
        {
            // Grab its "name" attribute
            CXMLAttribute* pAttribute = pNode->GetAttributes ().Find ( "name" );
            SString strName = pAttribute ? pAttribute->GetValue () : "";
            strName = strName.Replace ( "\\", "/" ).ToLower ();

            // Grab its "verify" attribute
            pAttribute = pNode->GetAttributes ().Find ( "verify" );
            SString strVerify = pAttribute ? pAttribute->GetValue () : "";
            bool bVerify = strVerify == "true" || strVerify == "yes" || strVerify == "1";

            // Find bitnumber
            bool bFound = false;
            for ( uint i = 0 ; i < NUMELMS( gtaDataFiles ) ; i++ )
            {
                if ( strName == gtaDataFiles[i].szRealFilename )
                {
                    if ( bVerify )
                        m_iEnableClientChecks |= 1 << gtaDataFiles[i].iBitNumber;
                    else
                        m_iEnableClientChecks &= ~( 1 << gtaDataFiles[i].iBitNumber );
                    bFound = true;
                    break;
                }
            }

            if ( !bFound )
                CLogger::ErrorPrintf ( "Unknown client_file '%s'\n", *strName );
        }
    }
    while ( pNode );


    // hideac
    int iHideAC = 0;
    GetInteger ( m_pRootNode, "hideac", iHideAC );

    {
        std::set < SString > disableACMap;
        std::set < SString > enableSDMap;

        {
            SString strDisableAC;
            GetString ( m_pRootNode, "disableac", strDisableAC );
            std::vector < SString > tagACList;
            strDisableAC.Split ( ",", tagACList );
            for ( std::vector < SString >::iterator it = tagACList.begin () ; it != tagACList.end () ; ++it )
                if ( isdigit((uchar)***it) )
                {
                    MapInsert ( disableACMap, *it );
                    MapInsert ( m_DisableComboACMap, *it );
                }
        }

        // Add support for SD #12, #14, #15, #16, #20, #22 and #28 (defaults to disabled)
        MapInsert ( m_DisableComboACMap, "12" );
        MapInsert ( m_DisableComboACMap, "14" );
        MapInsert ( m_DisableComboACMap, "15" );
        MapInsert ( m_DisableComboACMap, "16" );
        MapInsert ( m_DisableComboACMap, "20" );
        MapInsert ( m_DisableComboACMap, "22" );
        MapInsert ( m_DisableComboACMap, "28" );

        {
            SString strEnableSD;
            GetString ( m_pRootNode, "enablesd", strEnableSD );
            std::vector < SString > tagSDList;
            strEnableSD.Split ( ",", tagSDList );
            for ( std::vector < SString >::iterator it = tagSDList.begin () ; it != tagSDList.end () ; ++it )
                if ( isdigit((uchar)***it) )
                {
                    MapInsert ( enableSDMap, *it );
                    MapRemove ( m_DisableComboACMap, *it );
                }

            // Also save initial value in transient settings, so we can update the config without anyone knowing
            MapSet ( m_TransientSettings, "enablesd", strEnableSD );
        }

        CArgMap argMap;
        for ( std::set < SString >::iterator it = m_DisableComboACMap.begin () ; it != m_DisableComboACMap.end () ; ++it )
            argMap.Set ( *it, "" );
        SString strDisableComboACMap = argMap.ToString ();

        argMap = CArgMap ();
        for ( std::set < SString >::iterator it = disableACMap.begin () ; it != disableACMap.end () ; ++it )
            argMap.Set ( *it, "" );
        SString strDisableACMap = argMap.ToString ();

        argMap = CArgMap ();
        for ( std::set < SString >::iterator it = enableSDMap.begin () ; it != enableSDMap.end () ; ++it )
            argMap.Set ( *it, "" );
        SString strEnableSDMap = argMap.ToString ();

        g_pNetServer->SetChecks ( strDisableComboACMap, strDisableACMap, strEnableSDMap, m_iEnableClientChecks, iHideAC != 0 );
    }

    {
        SString strEnable;
        GetString ( m_pRootNode, "enablediagnostic", strEnable );
        std::vector < SString > tagList;
        strEnable.Split ( ",", tagList );
        for ( std::vector < SString >::iterator it = tagList.begin () ; it != tagList.end () ; ++it )
            if ( (*it).length () )
                MapInsert ( m_EnableDiagnosticMap, *it );
    }

    // Grab the server password
    iResult = GetString ( m_pRootNode, "password", m_strPassword, 1, 32 );

    // Grab the server fps limit
    int iFPSTemp = 0;
    iResult = GetInteger ( m_pRootNode, "fpslimit", iFPSTemp, 0, 100 );
    if ( iResult == IS_SUCCESS )
    {
        if ( iFPSTemp == 0 || iFPSTemp >= 25 )
        {
             m_usFPSLimit = (unsigned short)iFPSTemp;
             SetInteger ( m_pRootNode, "fpslimit", (int)m_usFPSLimit );
        }
    }

    // Grab whether or not voice is enabled
    iResult = GetInteger ( m_pRootNode, "voice", iTemp, 0, 1 );
    if ( iResult == IS_SUCCESS )
    {
        m_bVoiceEnabled = iTemp ? true : false;
    }

    // Grab the Sample Rate for Voice
    iTemp = m_uiVoiceSampleRate;
    iResult = GetInteger ( m_pRootNode, "voice_samplerate", iTemp, 0, 2 );
    m_uiVoiceSampleRate = Clamp ( 0, iTemp, 2 );

    // Grab the Quality for Voice
    iTemp = m_ucVoiceQuality;
    iResult = GetInteger ( m_pRootNode, "voice_quality", iTemp, 0, 10 );
    m_ucVoiceQuality = Clamp ( 0, iTemp, 10 );

    // Grab the bitrate for Voice [optional]
    iResult = GetInteger ( m_pRootNode, "voice_bitrate", iTemp );
    if ( iResult == IS_SUCCESS )
    {
        m_uiVoiceBitrate = iTemp;
    }


    // Grab the serial verification
    /** ACHTUNG: Unsupported for release 1.0 (#4090)
    iResult = GetBoolean ( m_pRootNode, "verifyserials", m_bVerifySerials );
    if ( iResult == INVALID_VALUE )
    {
        m_bVerifySerials = true;
    }
    else if ( iResult == DOESNT_EXIST )
    */
    {
        m_bVerifySerials = false;
    }

    // Grab the server-id filename
    SString strIdFile = "server-id.keys";
    GetString ( m_pRootNode, "idfile", strIdFile, 1 );
    m_strIdFile = g_pServerInterface->GetModManager ()->GetAbsolutePath ( strIdFile );

    // Grab the server logfiles
    std::string strBuffer;
    if ( GetString ( m_pRootNode, "logfile", strBuffer, 1 ) == IS_SUCCESS )
        m_strLogFile = g_pServerInterface->GetModManager ()->GetAbsolutePath ( strBuffer.c_str () );

    if ( GetString ( m_pRootNode, "authfile", strBuffer, 1 ) == IS_SUCCESS )
        m_strAuthFile = g_pServerInterface->GetModManager ()->GetAbsolutePath ( strBuffer.c_str () );

    if ( GetString ( m_pRootNode, "dbfile", strBuffer, 1 ) == IS_SUCCESS )
        m_strDbLogFilename = g_pServerInterface->GetModManager ()->GetAbsolutePath ( strBuffer.c_str () );
    else
        m_strDbLogFilename = g_pServerInterface->GetModManager ()->GetAbsolutePath ( "logs/db.log" );

    if ( GetString ( m_pRootNode, "loadstringfile", strBuffer, 1 ) == IS_SUCCESS )
        m_strLoadstringLogFilename = g_pServerInterface->GetModManager ()->GetAbsolutePath ( strBuffer.c_str () );

    // Grab the server access control list
    if ( GetString ( m_pRootNode, "acl", strBuffer, 1, 255 ) == IS_SUCCESS )
    {
        m_strAccessControlListFile = g_pServerInterface->GetModManager ()->GetAbsolutePath ( strBuffer.c_str () );
    }
    else
    {
        m_strAccessControlListFile = g_pServerInterface->GetModManager ()->GetAbsolutePath ( "acl.xml" );
    }

    // Grab the global databases path
    if ( GetString ( m_pRootNode, "global_databases_path", strBuffer, 1, 255 ) != IS_SUCCESS )
        strBuffer = "databases/global";
    if ( !IsValidFilePath ( strBuffer.c_str () ) || strBuffer.empty () )
    {
        CLogger::ErrorPrintf ( "global_databases_path is not valid. Defaulting to 'databases/global'\n" );
        strBuffer = "databases/global";
    }
    m_strGlobalDatabasesPath = g_pServerInterface->GetModManager ()->GetAbsolutePath ( strBuffer.c_str () );

    // Grab the system databases path
    if ( GetString ( m_pRootNode, "system_databases_path", strBuffer, 1, 255 ) != IS_SUCCESS )
        strBuffer = "databases/system";
    if ( !IsValidFilePath ( strBuffer.c_str () ) || strBuffer.empty () )
    {
        CLogger::ErrorPrintf ( "system_databases_path is not valid. Defaulting to 'databases/system'\n" );
        strBuffer = "databases/system";
    }
    m_strSystemDatabasesPath = g_pServerInterface->GetModManager ()->GetAbsolutePath ( strBuffer.c_str () );

    // Grab the backup path
    if ( GetString ( m_pRootNode, "backup_path", strBuffer, 1, 255 ) != IS_SUCCESS )
        strBuffer = "backups";
    if ( !IsValidFilePath ( strBuffer.c_str () ) || strBuffer.empty () )
    {
        CLogger::ErrorPrintf ( "backup_path is not valid. Defaulting to 'backups'\n" );
        strBuffer = "backups";
    }
    m_strBackupPath = g_pServerInterface->GetModManager ()->GetAbsolutePath ( strBuffer.c_str () );

    // Grab the backup interval
    GetInteger ( m_pRootNode, "backup_interval", m_iBackupInterval );
    m_iBackupInterval = Clamp ( 0, m_iBackupInterval, 30 );

    // Grab the backup count
    GetInteger ( m_pRootNode, "backup_copies", m_iBackupAmount );
    m_iBackupAmount = Clamp ( 0, m_iBackupAmount, 100 );

    GetBoolean ( m_pRootNode, "autologin", m_bAutoLogin );

    // networkencryption - Encryption for Server <-> client communications
    GetBoolean ( m_pRootNode, "networkencryption", m_bNetworkEncryptionEnabled );

    // bandwidth_reduction
    GetString ( m_pRootNode, "bandwidth_reduction", m_strBandwidthReductionMode );
    ApplyBandwidthReductionMode ();

    // busy_sleep_time
    GetInteger ( m_pRootNode, "busy_sleep_time", m_iPendingWorkToDoSleepTime );
    m_iPendingWorkToDoSleepTime = Clamp ( -1, m_iPendingWorkToDoSleepTime, 50 );

    // idle_sleep_time
    GetInteger ( m_pRootNode, "idle_sleep_time", m_iNoWorkToDoSleepTime );
    m_iNoWorkToDoSleepTime = Clamp ( -1, m_iNoWorkToDoSleepTime, 50 );

    // threadnet - Default to on at startup
    m_bThreadNetEnabled = true;
    ApplyThreadNetEnabled ();

    // Check settings in this list here
    const std::vector < SIntSetting >& settingList = GetIntSettingList ();
    for ( uint i = 0 ; i < settingList.size () ; i++ )
    {
        const SIntSetting& item = settingList[i];
        int iValue = item.iDefault;
        GetInteger ( m_pRootNode, item.szName, iValue );
        *item.pVariable = Clamp ( item.iMin, iValue, item.iMax );
    }

    // Handle recently retired lightsync_rate
    if ( m_pRootNode->FindSubNode ( "lightweight_sync_interval" ) == NULL )
    {
        GetInteger ( m_pRootNode, "lightsync_rate", g_TickRateSettings.iLightSync );
        g_TickRateSettings.iLightSync = Clamp ( 200, g_TickRateSettings.iLightSync, 4000 );
    }

    ApplyNetOptions ();

    return true;
}
示例#21
0
// Get ( [xml node], [xml storage dummy node], [xml node owner resource name], [querying resource name], [setting identifier] )
//
// The XML storage dummy node is used to output all nodes to which we have access (instead of returning the entire root node with
// all nodes in it), and is only needed when you want to return tables with multiple entries.
// Be sure to ALWAYS remove the storage node after calling Get!
//
// Returns the XML node in pNode
//
// Status values: NotFound (none found), NoAccess (no access/error) or Found (found)
CXMLNode *CSettings::Get(CXMLNode *pSource, CXMLNode *pStorage, const char *szSourceResource, const char *szLocalResource, const char *szSetting,
                         bool &bDeleteNode, SettingStatus &eStatus, CXMLNode *pMultiresultParentNode)
{
    CXMLNode *   pNode = NULL;
    unsigned int uiCurrentIndex = 0, uiResourceNameLength = 0;
    char         szQueryResource[MAX_RESOURCE_LENGTH] = {0}, szResource[MAX_RESOURCE_LENGTH] = {0};
    const char * szName, *szQueryName = NULL;
    eStatus = NoAccess;
    bDeleteNode = false;

    // Return if there was no source
    if (pSource == NULL)
        return NULL;

    // Get the resource name from the specified setting
    if (!GetResourceName(szSetting, szQueryResource, MAX_RESOURCE_LENGTH - 1))
    {            // (something): No resource specified, so use the local resource name
        strncpy(szQueryResource, szLocalResource, MAX_RESOURCE_LENGTH - 1);
    }
    else
    {
        // Save GetName the hassle of calling GetResourceName again by calculating the resource name length ourselves
        uiResourceNameLength = strlen(szQueryResource) + 1;
    }

    // Extract attribute name if setting to be gotten has three parts i.e. resname.settingname.attributename
    SString         strSetting = szSetting;
    SString         strAttribute = "value";
    vector<SString> Result;
    strSetting.Split(".", Result);
    if (Result.size() == 3 && Result[2].length())
    {
        strSetting = Result[0] + "." + Result[1];
        strAttribute = Result[2];
    }

    // Get the actual name from the specified setting
    if (!(szQueryName = GetName(strSetting, uiResourceNameLength)))
    {
        // No name specified, so make sure we eventually return the entire node
        bDeleteNode = true;
    }

    // Iterate through all the setting subnodes
    while ((pNode = pSource->FindSubNode("setting", uiCurrentIndex++)))
    {
        std::string  strContent;
        unsigned int uiResourceNameLength = 0;

        CXMLAttribute *pName = pNode->GetAttributes().Find("name");
        CXMLAttribute *pValue = pNode->GetAttributes().Find(strAttribute);

        // Check if both attibutes exist (otherwise ignore the entry)
        if (pName && pValue)
        {
            // Read the settings name and see if its valid
            strContent = pName->GetValue();
            if (strContent.empty())
                continue;

            // Parse the settings name and store the resource name in szResource
            if (!GetResourceName(strContent.c_str(), szResource, MAX_RESOURCE_LENGTH - 1))
            {
                // If there was no resource name, copy the owner's name
                strncpy(szResource, szSourceResource, MAX_RESOURCE_LENGTH - 1);
            }
            else
            {
                // Save GetName the hassle of calling GetResourceName again by calculating the resource name length ourselves
                uiResourceNameLength = strlen(szResource) + 1;
            }

            // Get the access type
            AccessType eAccess = GetAccessType(strContent.at(0));

            // Parse the settings name and store the split off name in szName (skip the prefix, if any)
            szName = GetName(strContent.c_str(), uiResourceNameLength);

            // Compare the results
            if (bDeleteNode)
            {
                // If we're walking through all resources (no resource nor setting name was specified) - ...
                // Or if we're walking through a specific resource - ...
                if ((uiResourceNameLength == 0 && (stricmp(szResource, szLocalResource) == 0 || eAccess != CSettings::Private)) ||
                    (uiResourceNameLength > 0 &&
                     ((stricmp(szResource, szQueryResource) == 0 && (eAccess != CSettings::Private || stricmp(szResource, szLocalResource) == 0)))))
                {
                    if (pMultiresultParentNode == NULL)
                    {
                        // Create a new temporary node (in which we can put all nodes we have access to), and add it as temporary subnode of pSource
                        // The node itself will be deleted
                        pMultiresultParentNode = pStorage->CreateSubNode("setting");
                    }

                    // We are meant to return an entire node. Since we are allowed to read this node, copy it and add it to our storage node
                    eStatus = Found;
                    CreateSetting(pMultiresultParentNode, strContent.c_str(), pValue->GetValue().c_str());
                }
            }
            else if (stricmp(szName, szQueryName) == 0 && stricmp(szResource, szQueryResource) == 0)
            {            // If the query name/resource and found node name/resource combinations are equal
                eStatus = (stricmp(szResource, szLocalResource) == 0 || eAccess != CSettings::Private) ? Found : NoAccess;
                return pNode;
            }
        }
    }
    // If we have multiple entries, return the storage node
    if (bDeleteNode)
        return pMultiresultParentNode;

    // Otherwise, return NULL
    eStatus = NotFound;
    return NULL;
}
示例#22
0
bool CXMLNodeImpl::CopyChildrenInto ( CXMLNode* pDestination, bool bRecursive )
{
    // Delete all the children of the target
    pDestination->DeleteAllSubNodes ();

    // Iterate through our children if we have. Otherwize just copy the content
    if ( m_Children.size () > 0 )
    {
        std::list < CXMLNode* > ::iterator iter = m_Children.begin ();
        CXMLNode* pMyChildNode;
        CXMLNode* pNewChildNode;
        for ( ; iter != m_Children.end (); iter++ )
        {
            // Grab its tag name
            pMyChildNode = *iter;
            const std::string& strTagName = pMyChildNode->GetTagName ();

            // Create at the destination
            pNewChildNode = pDestination->CreateSubNode ( strTagName.c_str () );
            if ( pNewChildNode )
            {
                // Copy our child's attributes into it
                int iAttributeCount = pMyChildNode->GetAttributes ().Count ();
                int i = 0;
                CXMLAttribute* pAttribute;
                for ( ; i < iAttributeCount; i++ )
                {
                    // Create a copy of every attribute into our destination
                    pAttribute = pMyChildNode->GetAttributes ().Get ( i );
                    if ( pAttribute )
                    {
                        pNewChildNode->GetAttributes ().Create ( *pAttribute );
                    }
                }

                // Run it recursively if asked to. Copy child child nodes etc..
                if ( bRecursive )
                {
                    if ( !pMyChildNode->CopyChildrenInto ( pNewChildNode, true ) )
                    {
                        pDestination->DeleteAllSubNodes ();
                        return false;
                    }
                }
            }
            else
            {
                pDestination->DeleteAllSubNodes ();
                return false;
            }
        }
    }
    else
    {
        const char* szText = m_pNode->GetText ();
        if ( szText )
            pDestination->SetTagContent ( szText );
    }

    // Success
    return true;
}
示例#23
0
bool CAccountManager::LoadXML ( CXMLNode* pParent )
{
    CLogger::LogPrint ( "Converting Accounts.xml into internal.db\n" );

    //##Keep for backwards compatability with accounts.xml##
#define ACCOUNT_VALUE_LENGTH 128

    std::string strBuffer, strName, strPassword, strIP, strDataKey, strDataValue;

    if ( pParent )
    {
        CXMLNode* pAccountNode = NULL;
        unsigned int uiAccountNodesCount = pParent->GetSubNodeCount ();
        for ( unsigned int i = 0 ; i < uiAccountNodesCount ; i++ )
        {
            pAccountNode = pParent->GetSubNode ( i );
            if ( pAccountNode == NULL )
                continue;

            strBuffer = pAccountNode->GetTagName ();
            if ( strBuffer.compare ( "account" ) == 0 )
            {
                CXMLAttribute* pAttribute = pAccountNode->GetAttributes ().Find ( "name" );
                if ( pAttribute )
                {
                    strName = pAttribute->GetValue ();

                    pAttribute = pAccountNode->GetAttributes ().Find ( "password" );
                    if ( pAttribute )
                    {
                        strPassword = pAttribute->GetValue ();
                        if ( !strName.empty () && !strPassword.empty () )
                        {
                            pAttribute = pAccountNode->GetAttributes ().Find ( "ip" );
                            if ( pAttribute )
                            {
                                strIP = pAttribute->GetValue ();
                                CAccount* pAccount = NULL;
                                pAttribute = pAccountNode->GetAttributes ().Find ( "serial" );
                                if ( pAttribute )
                                {
                                    //Insert the entry into the accounts database
                                    m_pDatabaseManager->Execf ( m_hDbConnection, "INSERT INTO accounts (name, ip, serial, password) VALUES(?,?,?,?)", SQLITE_TEXT, strName.c_str(), SQLITE_TEXT, strIP.c_str(), SQLITE_TEXT, pAttribute->GetValue ().c_str(), SQLITE_TEXT, strPassword.c_str() );
                                    pAccount = new CAccount ( this, true, strName, strPassword, strIP, m_iAccounts++, pAttribute->GetValue () );

                                }
                                else
                                {
                                    //Insert the entry into the accounts database
                                    m_pDatabaseManager->Execf ( m_hDbConnection, "INSERT INTO accounts (name, ip, password) VALUES(?,?,?)", SQLITE_TEXT, strName.c_str(), SQLITE_TEXT, strIP.c_str(), SQLITE_TEXT, strPassword.c_str() );
                                    pAccount = new CAccount ( this, true, strName, strPassword, strIP, m_iAccounts++ );
                                }

                                // Grab the data on this account
                                CXMLNode* pDataNode = NULL;
                                int iType = LUA_TNIL;
                                unsigned int uiDataNodesCount = pAccountNode->GetSubNodeCount ();
                                for ( unsigned int j = 0 ; j < uiDataNodesCount ; j++ )
                                {
                                    pDataNode = pAccountNode->GetSubNode ( j );
                                    if ( pDataNode == NULL )
                                        continue;
                                    strBuffer = pDataNode->GetTagName ();
                                    if ( strBuffer == "nil_data" )
                                        iType = LUA_TNIL;
                                    else if ( strBuffer == "boolean_data" )
                                        iType = LUA_TBOOLEAN;
                                    else if ( strBuffer == "string_data" )
                                        iType = LUA_TSTRING;
                                    else if ( strBuffer == "number_data" )
                                        iType = LUA_TNUMBER;

                                    CXMLAttributes* pAttributes = &(pDataNode->GetAttributes ());
                                    CXMLAttribute* pAttribute = NULL;
                                    unsigned int uiDataValuesCount = pAttributes->Count ();
                                    for ( unsigned int a = 0 ; a < uiDataValuesCount ; a++ )
                                    {
                                        pAttribute = pAttributes->Get ( a );
                                        strDataKey = pAttribute->GetName ();
                                        strDataValue = pAttribute->GetValue ();
                                        char szKey[128];
                                        STRNCPY( szKey, strDataKey.c_str(), 128 );
                                        SetAccountData( pAccount, szKey, strDataValue, iType );
                                    }
                                }
                            }
                            else
                            {
                                CAccount* pAccount = NULL;
                                pAttribute = pAccountNode->GetAttributes ().Find ( "serial" );
                                if ( pAttribute )
                                {
                                    //Insert the entry into the accounts database
                                    m_pDatabaseManager->Execf ( m_hDbConnection, "INSERT INTO accounts (name, password, serial) VALUES(?,?,?)", SQLITE_TEXT, strName.c_str(), SQLITE_TEXT, strPassword.c_str(), SQLITE_TEXT, pAttribute->GetValue().c_str() );
                                    pAccount = new CAccount ( this, true, strName, strPassword, "", m_iAccounts++, pAttribute->GetValue () );
                                }
                                else
                                {
                                    //Insert the entry into the accounts database
                                    m_pDatabaseManager->Execf ( m_hDbConnection, "INSERT INTO accounts (name, password) VALUES(?,?)", SQLITE_TEXT, strName.c_str(), SQLITE_TEXT, strPassword.c_str() );
                                    pAccount = new CAccount ( this, true, strName, strPassword, "", m_iAccounts++, "" );
                                }
                            }
                        }
                        else
                        {
                            if ( strName == CONSOLE_ACCOUNT_NAME )
                            {
                                //Add Console to the SQL Database (You don't need to create an account since the server takes care of that
                                m_pDatabaseManager->Execf ( m_hDbConnection, "INSERT INTO accounts (name, password) VALUES(?,?)", SQLITE_TEXT, "Console", SQLITE_TEXT, "" );
                                ++m_iAccounts;
                            }
                        }
                    }
                }
            }
            else
            {
                //Load the settings from XML
                LoadSetting ( pAccountNode );
            }
        }
        //Save the settings to SQL
        SaveSettings();
        CLogger::LogPrint ( "Conversion Complete.\n" );
        m_bChangedSinceSaved = false;
        return true;
    }

    return false;
}
示例#24
0
bool CMainConfig::LoadExtended ( void )
{
    std::string strBuffer;
    int iTemp = 0, iResult = 0;

	// Grab the script debuglog
    if ( GetString ( m_pRootNode, "scriptdebuglogfile", strBuffer, 255, 1 ) == IS_SUCCESS )
    {
        m_strScriptDebugLogFile = g_pServerInterface->GetModManager ()->GetAbsolutePath ( strBuffer.c_str () );
        m_bScriptDebugLogEnabled = true;
    }
    else
    {
        m_bScriptDebugLogEnabled = false;
    }

    // Grab the script debuglog level
    iResult = GetInteger ( m_pRootNode, "scriptdebugloglevel", iTemp, 0, 3 );
    if ( iResult == IS_SUCCESS )
    {
        m_uiScriptDebugLogLevel = iTemp;
    }
    else
    {
        if ( iResult == INVALID_VALUE )
        {
            CLogger::LogPrint ( "WARNING: Invalid value specified in \"scriptdebugloglevel\" tag; defaulting to 0\n" );
        }

        m_uiScriptDebugLogLevel = 0;
    }

    iResult = GetInteger ( m_pRootNode, "htmldebuglevel", iTemp, 0, 3 );
    if ( iResult == IS_SUCCESS )
    {
        g_pGame->GetScriptDebugging()->SetHTMLLogLevel ( iTemp );
    }
    else
    {
        if ( iResult == INVALID_VALUE )
        {
            CLogger::LogPrint ( "WARNING: Invalid value specified in \"htmldebuglevel\" tag; defaulting to 0\n" );
        }

        g_pGame->GetScriptDebugging()->SetHTMLLogLevel ( 0 );
    }

	// Handle the <module> nodes
    CXMLNode* pNode = NULL;
    unsigned int uiCurrentIndex = 0;
    do
    {
        pNode = m_pRootNode->FindSubNode ( "module", uiCurrentIndex++ );
        if ( pNode )
        {
            CXMLAttribute* pAttribute = pNode->GetAttributes ().Find ( "src" );
            if ( pAttribute )
            {
                std::string strBuffer = pAttribute->GetValue ();
                SString strFilename ( "%s/modules/%s", g_pServerInterface->GetModManager ()->GetModPath (), strBuffer.c_str () );

                if ( IsValidFilePath ( strBuffer.c_str () ) )
                {
                    m_pLuaManager->GetLuaModuleManager ()->_LoadModule ( strBuffer.c_str (), strFilename, false );
                }
            }
        }
    }
	while ( pNode );
    
    // Handle the <resource> nodes
    pNode = NULL;
    uiCurrentIndex = 0;
    bool bFoundDefault = false;
    bool bFirst = true;
    bool bNoProgress = false;

    do
    {
        // Grab the current script node
        pNode = m_pRootNode->FindSubNode ( "resource", uiCurrentIndex++ );
        if ( pNode )
        {
            // Grab its "src" attribute
            CXMLAttribute* pAttribute = pNode->GetAttributes ().Find ( "src" );
            if ( pAttribute )
            {
                // Grab the text in it and convert iwt to a path inside "scripts"
                std::string strBuffer = pAttribute->GetValue ();

                CResource * loadedResource = g_pGame->GetResourceManager ()->GetResource ( strBuffer.c_str () );
                if ( !loadedResource )
                {
                    CLogger::LogPrintNoStamp ( "\n" );
                    CLogger::ErrorPrintf ( "Couldn't find resource %s. Check it exists.\n", strBuffer.c_str () );
                    bNoProgress = true;
                }
                else
                {
                    loadedResource->SetPersistent ( true );

                    pAttribute = pNode->GetAttributes ().Find ( "startup" );
                    if ( pAttribute )
                    {
                        std::string strStartup = pAttribute->GetValue ();
                        if ( strStartup.compare ( "true" ) == 0 ||
                             strStartup.compare ( "yes" ) == 0 ||
                             strStartup.compare ( "1" ) == 0 )
                        {
                            CLogger::SetOutputEnabled ( false );
                            if ( loadedResource->Start( NULL, true ) )
                            {
                                CLogger::SetOutputEnabled ( true );
                                if ( !bNoProgress )
                                {
                                    if ( bFirst )
                                        CLogger::LogPrint ( "Starting resources..." );
                                    else
                                        CLogger::LogPrintNoStamp ( "." );

                                    bFirst = false;
                                }
                            }
                            else
                            {
                                CLogger::SetOutputEnabled ( true );
                                CLogger::LogPrintNoStamp ( "\n" );
                                CLogger::ErrorPrintf ( "Unable to start resource %s; %s\n", strBuffer.c_str (), loadedResource->GetFailureReason ().c_str () );
                                bNoProgress = true;
                            }
                        }
                    }

					pAttribute = pNode->GetAttributes ().Find ( "protected" );
                    if ( pAttribute )
                    {
                        std::string strProtected = pAttribute->GetValue ();
                        if ( strProtected.compare ( "true" ) == 0 ||
                             strProtected.compare ( "yes" ) == 0 ||
                             strProtected.compare ( "1" ) == 0 )
                            loadedResource->SetProtected ( true );
                    }

                    // Default resource
                    pAttribute = pNode->GetAttributes ().Find ( "default" );
                    if ( pAttribute )
                    {
                        if ( !bFoundDefault )
                        {
                            std::string strProtected = pAttribute->GetValue ();
                            if ( strProtected.compare ( "true" ) == 0 ||
                                strProtected.compare ( "yes" ) == 0 ||
                                strProtected.compare ( "1" ) == 0 )
                            {
                                std::string strName = loadedResource->GetName ();
                                if ( !strName.empty () )
                                {
                                    g_pGame->GetHTTPD ()->SetDefaultResource ( strName.c_str () );
                                }

                                bFoundDefault = true;
                            }
                        }
                        else
                        {
                            CLogger::LogPrintNoStamp ( "\n" );
                            CLogger::ErrorPrintf ( "More than one default resource specified!\n" );
                            bNoProgress = true;
                        }
                    }
                }
            }
        }
    }
    while ( pNode );

    if ( !bNoProgress ) CLogger::LogPrintNoStamp ( "\n" );

    // Register the commands
    RegisterCommand ( "update", CConsoleCommands::Update, false );
    RegisterCommand ( "start", CConsoleCommands::StartResource, false );
    RegisterCommand ( "stop", CConsoleCommands::StopResource, false );
	RegisterCommand ( "stopall", CConsoleCommands::StopAllResources, false );
    RegisterCommand ( "restart", CConsoleCommands::RestartResource, false );
    RegisterCommand ( "refresh", CConsoleCommands::RefreshResources, false );
    RegisterCommand ( "refreshall", CConsoleCommands::RefreshAllResources, false );
    RegisterCommand ( "list", CConsoleCommands::ListResources, false );
    RegisterCommand ( "info", CConsoleCommands::ResourceInfo, false );
    RegisterCommand ( "install", CConsoleCommands::InstallResource, false );
    RegisterCommand ( "upgrade", CConsoleCommands::UpgradeResources, false );

    RegisterCommand ( "say", CConsoleCommands::Say, false );
    RegisterCommand ( "teamsay", CConsoleCommands::TeamSay, false );
    RegisterCommand ( "asay", CConsoleCommands::ASay, false );
    RegisterCommand ( "msg", CConsoleCommands::Msg, false );
    RegisterCommand ( "amsg", CConsoleCommands::AMsg, false );
    RegisterCommand ( "me", CConsoleCommands::Me, false );
    RegisterCommand ( "nick", CConsoleCommands::Nick, false );

    RegisterCommand ( "login", CConsoleCommands::LogIn, false );
    RegisterCommand ( "logout", CConsoleCommands::LogOut, false );
    RegisterCommand ( "chgmypass", CConsoleCommands::ChgMyPass, false );

    RegisterCommand ( "addaccount", CConsoleCommands::AddAccount, false );
    RegisterCommand ( "delaccount", CConsoleCommands::DelAccount, false );
    RegisterCommand ( "chgpass", CConsoleCommands::ChgPass, false );
    RegisterCommand ( "shutdown", CConsoleCommands::Shutdown, false );

    RegisterCommand ( "aexec", CConsoleCommands::AExec, false );

    RegisterCommand ( "whois", CConsoleCommands::WhoIs, false );
    RegisterCommand ( "whowas", CConsoleCommands::WhoWas, false );

    RegisterCommand ( "debugscript", CConsoleCommands::DebugScript, false );

	RegisterCommand ( "sudo", CConsoleCommands::Sudo, false );

    RegisterCommand ( "help", CConsoleCommands::Help, false );

	RegisterCommand ( "loadmodule", CConsoleCommands::LoadModule, false );
	//RegisterCommand ( "unloadmodule", CConsoleCommands::UnloadModule, false );
	//RegisterCommand ( "reloadmodule", CConsoleCommands::ReloadModule, false );

    RegisterCommand ( "ver", CConsoleCommands::Ver, false );
    RegisterCommand ( "sver", CConsoleCommands::Ver, false );

	return true;
}
示例#25
0
bool CLocalServer::Load ( void )
{
    // Get server module root
    SString strServerPath = g_pCore->GetInstallRoot ();
    strServerPath += "/server/mods/deathmatch";

    SString strConfigPath ( "%s/%s", strServerPath.c_str (), m_strConfig.c_str () );
    m_pConfig = g_pCore->GetXML ()->CreateXML ( strConfigPath );
    if ( m_pConfig && m_pConfig->Parse() )
    {
        CXMLNode* pRoot = m_pConfig->GetRootNode();
        CXMLNode* pServerName = pRoot->FindSubNode ( "servername", 0 );
        if ( pServerName ) m_pEditName->SetText ( pServerName->GetTagContent().c_str() );
        CXMLNode* pServerPass = pRoot->FindSubNode ( "password", 0 );
        if ( pServerPass ) m_pEditPass->SetText ( pServerPass->GetTagContent().c_str() );
        CXMLNode* pServerPlayers = pRoot->FindSubNode ( "maxplayers", 0 );
        if ( pServerPlayers ) m_pEditPlayers->SetText ( pServerPlayers->GetTagContent().c_str() );

        // Read the startup resources
        list < CXMLNode* > ::const_iterator iter = pRoot->ChildrenBegin ();
        for ( ; iter != pRoot->ChildrenEnd (); iter++ )
        {
            CXMLNode* pNode = reinterpret_cast < CXMLNode* > ( *iter );
            if ( pNode->GetTagName ().compare ( "resource" ) == 0 )
            {
                CXMLAttribute* src = pNode->GetAttributes().Find ( "src" );
                if ( src && src->GetValue()[1] )
                {
                    m_pResourcesCur->SetItemText ( m_pResourcesCur->AddRow (), m_hResourcesCur, src->GetValue().c_str() );
                }
            }
        }
    }
    //

    SString strResourceDirectoryPath ( "%s/resources/*", strServerPath.c_str () );

    unsigned int uiCount = 0;

    #ifdef WIN32

        // Find all .map files in the maps folder
        WIN32_FIND_DATA FindData;
        HANDLE hFind = FindFirstFile ( strResourceDirectoryPath, &FindData );
        if ( hFind != INVALID_HANDLE_VALUE )
        {
            // Remove the extension and store the time
            FindData.cFileName [ strlen ( FindData.cFileName ) - 4 ] = 0;
            // Add each file
            do
            {
                if ( strcmp ( FindData.cFileName, ".." ) != 0 && strcmp ( FindData.cFileName, "." ) != 0 )
                {
                    char * extn = NULL;
                    if ( ( FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != FILE_ATTRIBUTE_DIRECTORY )
                    {
                        extn = &FindData.cFileName [ strlen ( FindData.cFileName ) - 3 ];
                        FindData.cFileName [ strlen ( FindData.cFileName ) - 4 ] = 0;
                    }

                    if ( extn == NULL || strcmp ( extn, "zip" ) == 0 )
                    {
                        // Add the resource
                        HandleResource ( FindData.cFileName );

                        // Increment the counter
                        uiCount++;
                    }
                }
            } while ( FindNextFile ( hFind, &FindData ) );

            // Close the search
            FindClose ( hFind );
        }
    #else
        DIR *Dir;
		struct dirent *DirEntry;
		time_t llHighestTime = 0;
		char szPath[MAX_PATH] = {0};

		if ( ( Dir = opendir ( strResourceDirectoryPath ) ) )
		{
			while ( ( DirEntry = readdir ( Dir ) ) != NULL )
			{
                // Skip . and .. entry
                if ( strcmp ( DirEntry->d_name, "." ) != 0 && 
                     strcmp ( DirEntry->d_name, ".." ) != 0 )
                {
				    struct stat Info;
				    bool bDir = false;

				    // Get the path
				    if ( strlen(szBuffer) + strlen(DirEntry->d_name) < MAX_PATH )
                    {
					    strcpy ( szPath, szBuffer );
					    unsigned long ulPathLength = strlen ( szPath );

					    if ( szPath [ ulPathLength-1 ] != '/') strcat ( szPath, "/" );

					    strcat ( szPath, DirEntry->d_name );

					    // Determine the file stats
					    if ( lstat ( szPath, &Info ) != -1 )
						    bDir = S_ISDIR ( Info.st_mode );
					    else
						    CLogger::ErrorPrintf ( "Unable to stat %s\n", szPath );

				        // Chop off the extension if it's not a dir
				        char * extn = NULL;
				        if ( !bDir )
                        {
					        extn = &(DirEntry->d_name [ strlen ( DirEntry->d_name ) - 3 ]);
					        DirEntry->d_name [ strlen ( DirEntry->d_name ) - 4 ] = 0;
				        }
                        if ( extn == NULL || strcmp ( extn, "zip" ) == 0 )
                        {
                            // Add the resource
                            HandleResource ( DirEntry->d_name );

                            // Increment the counter
                            uiCount++;
                        }

				    }
                }


			}

			// Close the directory handle
			closedir ( Dir );
		}
    #endif
    return true;
}
示例#26
0
bool CMainConfig::LoadExtended ( void )
{
    std::string strBuffer;
    int iTemp = 0, iResult = 0;

    // minclientversion - Minimum client version or kick
    GetString ( m_pRootNode, "minclientversion", m_strMinClientVersion );
    if ( m_strMinClientVersion != "" && !IsValidVersionString ( m_strMinClientVersion ) )
    {
        CLogger::LogPrint ( "WARNING: Invalid value specified in \"minclientversion\"\n" );
        m_strMinClientVersion = "";
    }

    // recommendedclientversion - Minimum client version or spam
    GetString ( m_pRootNode, "recommendedclientversion", m_strRecommendedClientVersion );
    if ( m_strRecommendedClientVersion != "" && !IsValidVersionString ( m_strRecommendedClientVersion ) )
    {
        CLogger::LogPrint ( "WARNING: Invalid value specified in \"recommendedclientversion\"\n" );
        m_strRecommendedClientVersion = "";
    }

    // Grab the script debuglog
    if ( GetString ( m_pRootNode, "scriptdebuglogfile", strBuffer, 1, 255 ) == IS_SUCCESS )
    {
        m_strScriptDebugLogFile = g_pServerInterface->GetModManager ()->GetAbsolutePath ( strBuffer.c_str () );
        m_bScriptDebugLogEnabled = true;
    }
    else
    {
        m_bScriptDebugLogEnabled = false;
    }

    // Grab the script debuglog level
    iResult = GetInteger ( m_pRootNode, "scriptdebugloglevel", iTemp, 0, 3 );
    if ( iResult == IS_SUCCESS )
    {
        m_uiScriptDebugLogLevel = iTemp;
    }
    else
    {
        if ( iResult == INVALID_VALUE )
        {
            CLogger::LogPrint ( "WARNING: Invalid value specified in \"scriptdebugloglevel\" tag; defaulting to 0\n" );
        }

        m_uiScriptDebugLogLevel = 0;
    }

    iResult = GetInteger ( m_pRootNode, "htmldebuglevel", iTemp, 0, 3 );
    if ( iResult == IS_SUCCESS )
    {
        g_pGame->GetScriptDebugging()->SetHTMLLogLevel ( iTemp );
    }
    else
    {
        if ( iResult == INVALID_VALUE )
        {
            CLogger::LogPrint ( "WARNING: Invalid value specified in \"htmldebuglevel\" tag; defaulting to 0\n" );
        }

        g_pGame->GetScriptDebugging()->SetHTMLLogLevel ( 0 );
    }

    // Handle the <module> nodes
    CXMLNode* pNode = NULL;
    unsigned int uiCurrentIndex = 0;
    do
    {
        pNode = m_pRootNode->FindSubNode ( "module", uiCurrentIndex++ );
        if ( pNode )
        {
            CXMLAttribute* pAttribute = pNode->GetAttributes ().Find ( "src" );
            if ( pAttribute )
            {
                std::string strBuffer = pAttribute->GetValue ();
                SString strFilename ( "%s/modules/%s", g_pServerInterface->GetModManager ()->GetModPath (), strBuffer.c_str () );

                if ( IsValidFilePath ( strBuffer.c_str () ) )
                {
                    m_pLuaManager->GetLuaModuleManager ()->_LoadModule ( strBuffer.c_str (), strFilename, false );
                }
            }
        }
    }
    while ( pNode );
    
    // Handle the <resource> nodes
    pNode = NULL;
    uiCurrentIndex = 0;
    bool bFoundDefault = false;

    CLogger::SetMinLogLevel ( LOGLEVEL_MEDIUM );
    CLogger::LogPrint ( "Starting resources..." );
    CLogger::ProgressDotsBegin ();

    do
    {
        if ( g_pServerInterface->IsRequestingExit () )
            return false;

        // Grab the current script node
        pNode = m_pRootNode->FindSubNode ( "resource", uiCurrentIndex++ );
        if ( pNode )
        {
            // Grab its "src" attribute
            CXMLAttribute* pAttribute = pNode->GetAttributes ().Find ( "src" );
            if ( pAttribute )
            {
                // Grab the text in it and convert iwt to a path inside "scripts"
                std::string strBuffer = pAttribute->GetValue ();

                CResource * loadedResource = g_pGame->GetResourceManager ()->GetResource ( strBuffer.c_str () );
                if ( !loadedResource )
                {
                    CLogger::ErrorPrintf ( "Couldn't find resource %s. Check it exists.\n", strBuffer.c_str () );
                }
                else
                {
                    loadedResource->SetPersistent ( true );

                    pAttribute = pNode->GetAttributes ().Find ( "startup" );
                    if ( pAttribute )
                    {
                        std::string strStartup = pAttribute->GetValue ();
                        if ( strStartup.compare ( "true" ) == 0 ||
                             strStartup.compare ( "yes" ) == 0 ||
                             strStartup.compare ( "1" ) == 0 )
                        {
                            if ( loadedResource->Start( NULL, true ) )
                            {
                                CLogger::ProgressDotsUpdate ();
                            }
                            else
                            {
                                CLogger::ErrorPrintf ( "Unable to start resource %s; %s\n", strBuffer.c_str (), loadedResource->GetFailureReason ().c_str () );
                            }
                        }
                    }

                    pAttribute = pNode->GetAttributes ().Find ( "protected" );
                    if ( pAttribute )
                    {
                        std::string strProtected = pAttribute->GetValue ();
                        if ( strProtected.compare ( "true" ) == 0 ||
                             strProtected.compare ( "yes" ) == 0 ||
                             strProtected.compare ( "1" ) == 0 )
                            loadedResource->SetProtected ( true );
                    }

                    // Default resource
                    pAttribute = pNode->GetAttributes ().Find ( "default" );
                    if ( pAttribute )
                    {
                        if ( !bFoundDefault )
                        {
                            std::string strDefault = pAttribute->GetValue ();
                            if ( strDefault.compare ( "true" ) == 0 ||
                                strDefault.compare ( "yes" ) == 0 ||
                                strDefault.compare ( "1" ) == 0 )
                            {
                                std::string strName = loadedResource->GetName ();
                                if ( !strName.empty () )
                                {
                                    g_pGame->GetHTTPD ()->SetDefaultResource ( strName.c_str () );
                                }

                                bFoundDefault = true;
                            }
                        }
                        else
                        {
                            CLogger::ErrorPrintf ( "More than one default resource specified!\n" );
                        }
                    }
                }
            }
        }
    }
    while ( pNode );

    CLogger::ProgressDotsEnd ();
    CLogger::SetMinLogLevel ( LOGLEVEL_LOW );

    // Register the commands
    RegisterCommand ( "start", CConsoleCommands::StartResource, false );
    RegisterCommand ( "stop", CConsoleCommands::StopResource, false );
    RegisterCommand ( "stopall", CConsoleCommands::StopAllResources, false );
    RegisterCommand ( "restart", CConsoleCommands::RestartResource, false );
    RegisterCommand ( "refresh", CConsoleCommands::RefreshResources, false );
    RegisterCommand ( "refreshall", CConsoleCommands::RefreshAllResources, false );
    RegisterCommand ( "list", CConsoleCommands::ListResources, false );
    RegisterCommand ( "info", CConsoleCommands::ResourceInfo, false );
    RegisterCommand ( "upgrade", CConsoleCommands::UpgradeResources, false );
    RegisterCommand ( "check", CConsoleCommands::CheckResources, false );

    RegisterCommand ( "say", CConsoleCommands::Say, false );
    RegisterCommand ( "teamsay", CConsoleCommands::TeamSay, false );
    //RegisterCommand ( "asay", CConsoleCommands::ASay, false );    // Not working
    RegisterCommand ( "msg", CConsoleCommands::Msg, false );
    //RegisterCommand ( "amsg", CConsoleCommands::AMsg, false );    // Not working
    RegisterCommand ( "me", CConsoleCommands::Me, false );
    RegisterCommand ( "nick", CConsoleCommands::Nick, false );

    RegisterCommand ( "login", CConsoleCommands::LogIn, false );
    RegisterCommand ( "logout", CConsoleCommands::LogOut, false );
    RegisterCommand ( "chgmypass", CConsoleCommands::ChgMyPass, false );

    RegisterCommand ( "addaccount", CConsoleCommands::AddAccount, false );
    RegisterCommand ( "delaccount", CConsoleCommands::DelAccount, false );
    RegisterCommand ( "chgpass", CConsoleCommands::ChgPass, false );
    RegisterCommand ( "shutdown", CConsoleCommands::Shutdown, false );

    RegisterCommand ( "aexec", CConsoleCommands::AExec, false );

    RegisterCommand ( "whois", CConsoleCommands::WhoIs, false );
    RegisterCommand ( "whowas", CConsoleCommands::WhoWas, false );

    RegisterCommand ( "debugscript", CConsoleCommands::DebugScript, false );

    //RegisterCommand ( "sudo", CConsoleCommands::Sudo, false );    // Not working

    RegisterCommand ( "help", CConsoleCommands::Help, false );

    RegisterCommand ( "loadmodule", CConsoleCommands::LoadModule, false );
    //RegisterCommand ( "unloadmodule", CConsoleCommands::UnloadModule, false );
    //RegisterCommand ( "reloadmodule", CConsoleCommands::ReloadModule, false );

    RegisterCommand ( "ver", CConsoleCommands::Ver, false );
    RegisterCommand ( "sver", CConsoleCommands::Ver, false );
    RegisterCommand ( "ase", CConsoleCommands::Ase, false );
    RegisterCommand ( "openports", CConsoleCommands::OpenPortsTest, false );

    RegisterCommand ( "debugdb", CConsoleCommands::SetDbLogLevel, false );

    RegisterCommand ( "reloadbans", CConsoleCommands::ReloadBans, false );

    RegisterCommand ( "aclrequest", CConsoleCommands::AclRequest, false );
    RegisterCommand ( "debugjoinflood", CConsoleCommands::DebugJoinFlood, false );
#if defined(MTA_DEBUG) || defined(MTA_BETA)
    RegisterCommand ( "sfakelag", CConsoleCommands::FakeLag, false );
#endif
    return true;
}
示例#27
0
int CLuaXMLDefs::xmlCopyFile ( lua_State* luaVM )
{
#ifndef MTA_CLIENT
    if ( lua_type ( luaVM, 3 ) == LUA_TLIGHTUSERDATA )
        m_pScriptDebugging->LogCustom ( luaVM, "xmlCopyFile may be using an outdated syntax. Please check and update." );
#endif // !MTA_CLIENT

    // Grab our resource
    CLuaMain* pLUA = m_pLuaManager->GetVirtualMachine ( luaVM );
    if ( pLUA )
    {
        SString strFile;
        CXMLNode* pSourceNode;

        CScriptArgReader argStream ( luaVM );
        argStream.ReadUserData ( pSourceNode );
        argStream.ReadString ( strFile );

        if ( !argStream.HasErrors () )
        {
            SString strPath;
            CResource* pThisResource = pLUA->GetResource ();
            CResource* pOtherResource = pThisResource;

            // Resolve other resource from name
            if ( CResourceManager::ParseResourcePathInput ( strFile, pOtherResource, &strPath, NULL ) )
            {
#ifndef MTA_CLIENT
                // We have access to modify other resource?
                if ( pOtherResource == pThisResource ||
                    m_pACLManager->CanObjectUseRight ( pThisResource->GetName ().c_str (),
                        CAccessControlListGroupObject::OBJECT_TYPE_RESOURCE,
                        "ModifyOtherObjects",
                        CAccessControlListRight::RIGHT_TYPE_GENERAL,
                        false ) )
#endif // !MTA_CLIENT
                {
                    if ( pSourceNode ) {

                        // Make sure the dir exists so we can successfully make the file
                        MakeSureDirExists ( strPath );

                        // Grab the roots tag name
                        std::string strRootTagName;
                        strRootTagName = pSourceNode->GetTagName ();

                        // Create the new XML file and its root node
                        CXMLFile* pNewXML = pLUA->CreateXML ( strPath.c_str () );
                        if ( pNewXML )
                        {
                            // Grab the root of the new XML
                            CXMLNode* pNewRoot = pNewXML->CreateRootNode ( strRootTagName );
                            if ( pNewRoot )
                            {
                                // Copy over the attributes from the root
                                int iAttributeCount = pSourceNode->GetAttributes ().Count ();
                                int i = 0;
                                CXMLAttribute* pAttribute;
                                for ( ; i < iAttributeCount; i++ )
                                {
                                    pAttribute = pSourceNode->GetAttributes ().Get ( i );
                                    if ( pAttribute )
                                        pNewRoot->GetAttributes ().Create ( *pAttribute );
                                }

                                // Copy the stuff from the given source node to the destination root
                                if ( pSourceNode->CopyChildrenInto ( pNewRoot, true ) )
                                {
                                    lua_pushxmlnode ( luaVM, pNewRoot );
                                    return 1;
                                }
                            }

                            // Delete the XML again
                            pLUA->DestroyXML ( pNewXML );
                        }
                    }
                    else
                        argStream.SetCustomError ( SString ( "Unable to copy XML file %s", strFile.c_str () ), "Bad filepath" );
                }
#ifndef MTA_CLIENT
                else
                    argStream.SetCustomError ( SString ( "ModifyOtherObjects in ACL denied resource '%s' to access '%s'", pThisResource->GetName ().c_str (), pOtherResource->GetName ().c_str () ), "Access denied" );
#endif
            }
        }

        if ( argStream.HasErrors () )
            m_pScriptDebugging->LogCustom ( luaVM, argStream.GetFullErrorMessage () );
    }

    // Error
    lua_pushboolean ( luaVM, false );
    return 1;
}
示例#28
0
// Set ( resource requesting the query, setting name, content )
bool CSettings::Set(const char *szLocalResource, const char *szSetting, const char *szContent)
{
    CXMLNode *      pNode;
    CResource *     pResource;
    CXMLAttributes *pAttributes;
    char            szBuffer[MAX_SETTINGS_LENGTH] = {0};
    char            szQueryResource[MAX_RESOURCE_LENGTH] = {0};
    SettingStatus   eStatus;
    bool            bDeleteNode, bExists;
    SString         strOldValue;

    // Check for empty strings
    if (strlen(szSetting) < 1)
        return false;

    // Get the actual resource name from the specified setting, and get the resource class
    if (!GetResourceName(szSetting, szQueryResource, MAX_RESOURCE_LENGTH - 1))
    {
        // No name was specified, so use the local resource
        pResource = m_pResourceManager->GetResource(szLocalResource);
    }
    else
        pResource = m_pResourceManager->GetResource(szQueryResource);

    // If we have a valid resource
    if (pResource)
    {
        CXMLNode *pSource = pResource->GetSettingsNode();

        // Check whether the setting exists in the settings registry
        pNode = Get(m_pNodeGlobalSettings, NULL, "", szLocalResource, szSetting, bDeleteNode, eStatus);
        bExists = true;            // Default value

        // Try to get the value for the appropriate setting from the resource's meta XML file
        if (eStatus == NotFound && pSource)
        {
            pNode = Get(pSource, NULL, pResource->GetName().c_str(), szLocalResource, szSetting, bDeleteNode, eStatus);
            bExists = false;            // There's no node in the settings registry, so we create one
        }

        // See if we have access
        if (eStatus != NoAccess)
        {
            // See if we have a prefix
            bool bPrefix = HasPrefix(szSetting[0]);

            // If no resource name was specified, use the local resource name
            if (!HasResourceName(szSetting))
            {
                // If we have a prefix, move it from szSetting and put it at the beginning
                if (bPrefix)
                    snprintf(szBuffer, MAX_SETTINGS_LENGTH - 1, "%c%s.%s", szSetting[0], szLocalResource, szSetting + 1);
                else
                    snprintf(szBuffer, MAX_SETTINGS_LENGTH - 1, "%s.%s", szLocalResource, szSetting);
            }
            else
            {
                // If we have a prefix, move it from szSetting and put it at the beginning
                if (bPrefix)
                    snprintf(szBuffer, MAX_SETTINGS_LENGTH - 1, "%c%s", szSetting[0], szSetting + 1);
                else
                    strncpy(szBuffer, szSetting, MAX_SETTINGS_LENGTH - 1);
            }

            if (!bExists || !pNode)
            {            // No existing settings registry entry, so create a new setting
                CreateSetting(m_pNodeGlobalSettings, szBuffer, szContent);
            }
            else
            {            // Existing settings registry entry
                // Get the attributes
                pAttributes = &(pNode->GetAttributes());

                // Abort if this value isnt public (but protected or private), and if the local resource
                // (doing the query) doesn't equal the setting's resource name
                if (GetAccessType(pAttributes->Find("name")->GetValue()[0]) != CSettings::Public && stricmp(pResource->GetName().c_str(), szLocalResource) != 0)
                    return false;

                // Get the node's current value
                strOldValue = pAttributes->Find("value")->GetValue();

                // Set the node's value
                pAttributes->Find("value")->SetValue(szContent);

                // If a prefix was given, set the node's name (to override any access operators)
                if (bPrefix)
                    pAttributes->Find("name")->SetValue(szBuffer);
            }

            // Trigger onSettingChange
            CLuaArguments Arguments;
            Arguments.PushString(szSetting);

            if (strOldValue.length() > 0)
                Arguments.PushString(strOldValue.c_str());
            else
                Arguments.PushNil();

            Arguments.PushString(szContent);

            g_pGame->GetMapManager()->GetRootElement()->CallEvent("onSettingChange", Arguments);

            // Save the XML file
            if (m_pFile->Write())
                return true;
            CLogger::ErrorPrintf("Error saving '%s'\n", FILENAME_SETTINGS);
        }
    }

    return false;
}
bool CAccessControlListManager::Load ( void )
{
    // Eventually destroy the previously loaded xml
    if ( m_pXML )
    {
        delete m_pXML;
    }

    // Load the XML
    m_pXML = g_pServerInterface->GetXML ()->CreateXML ( GetFileName ().c_str () );
    if ( !m_pXML )
    {
        CLogger::ErrorPrintf ( "Error loading Access Control List file\n" );
        return false;
    }

    // Parse it
    if ( !m_pXML->Parse () )
    {
        CLogger::ErrorPrintf ( "Error parsing Access Control List file\n" );
        return false;
    }

    // Grab the XML root node
    m_pRootNode = m_pXML->GetRootNode ();
    if ( !m_pRootNode )
    {
        CLogger::ErrorPrintf ( "Missing root node ('ACL')\n" );
        return false;
    }

    // Clear previous ACL stuff
    ClearACLs ();
    ClearGroups ();

    // load the acl's
    CXMLNode* pSubNode = NULL;
    unsigned int uiSubNodesCount = m_pRootNode->GetSubNodeCount ();
    for ( unsigned int i = 0 ; i < uiSubNodesCount ; i++ )
    {
        pSubNode = m_pRootNode->GetSubNode ( i );
        if ( !pSubNode ) continue;

        if ( pSubNode->GetTagName ().compare ( "acl" ) == 0 )
        {
            CXMLAttribute* pAttribute = pSubNode->GetAttributes ().Find ( "name" );
            if ( pAttribute )
            {
                CAccessControlList* pACL = AddACL ( pAttribute->GetValue ().c_str () );

                CXMLNode* pSubSubNode = NULL;
                unsigned int uiSubSubNodesCount = pSubNode->GetSubNodeCount ();
                for ( unsigned int j = 0 ; j < uiSubSubNodesCount ; j++ )
                {
                    // If this subnode doesn't exist, return to the for loop and continue it
                    pSubSubNode = pSubNode->GetSubNode ( j );
                    if ( !pSubSubNode ) continue;

                    // Check that this subsub node is named "right"
                    if ( pSubSubNode->GetTagName ().compare ( "right" ) == 0 )
                    {
                        // Grab the name and the access attributes
                        CXMLAttribute* pNameAttribute = pSubSubNode->GetAttributes ().Find ( "name" );
                        CXMLAttribute* pAccessAttribute = pSubSubNode->GetAttributes ().Find ( "access" );
                        if ( pNameAttribute && pAccessAttribute )
                        {
                            // See if the access attribute is true or false
                            bool bAccess = false;
                            std::string strAccess = pAccessAttribute->GetValue ();

                            if ( stricmp ( strAccess.c_str (), "true" ) == 0 ||
                                 stricmp ( strAccess.c_str (), "yes" ) == 0 ||
                                 strcmp ( strAccess.c_str (), "1" ) == 0 )
                            {
                                bAccess = true;
                            }

                            // Grab the name of the 'right' name
                            const char *szRightName = pNameAttribute->GetValue ().c_str ();

                            // Create the rights control list
                            CAccessControlListRight* pRight = NULL;
                            if ( StringBeginsWith ( szRightName, "command." ) )
                            {
                                pRight = pACL->AddRight ( &szRightName[8], CAccessControlListRight::RIGHT_TYPE_COMMAND, bAccess );
                            }
                            else if ( StringBeginsWith ( szRightName, "function." ) )
                            {
                                pRight = pACL->AddRight ( &szRightName[9], CAccessControlListRight::RIGHT_TYPE_FUNCTION, bAccess );
                            }
                            else if ( StringBeginsWith ( szRightName, "resource." ) )
                            {
                                pRight = pACL->AddRight ( &szRightName[9], CAccessControlListRight::RIGHT_TYPE_RESOURCE, bAccess );
                            }
                            else if ( StringBeginsWith ( szRightName, "general." ) )
                            {
                                pRight = pACL->AddRight ( &szRightName[8], CAccessControlListRight::RIGHT_TYPE_GENERAL, bAccess );
                            }
                            else continue;

                            // Set all the extra attributes
                            for ( uint i = 0 ; i < pSubSubNode->GetAttributes ().Count () ; i++ )
                            {
                                CXMLAttribute* pAttribute = pSubSubNode->GetAttributes ().Get ( i );
                                pRight->SetAttributeValue ( pAttribute->GetName (), pAttribute->GetValue () );
                            }
                        }
                    }
                }
            }
        }
    }

    // Load the groups
    pSubNode = NULL;
    uiSubNodesCount = m_pRootNode->GetSubNodeCount ();
    for ( unsigned int i = 0 ; i < uiSubNodesCount ; i++ )
    {
        pSubNode = m_pRootNode->GetSubNode ( i );
        if ( !pSubNode ) continue;

        if ( pSubNode->GetTagName ().compare ( "group" ) == 0 )
        {
            CXMLAttribute* pAttribute = pSubNode->GetAttributes ().Find ( "name" );
            if ( pAttribute )
            {
                CAccessControlListGroup* pGroup = AddGroup ( pAttribute->GetValue ().c_str () );

                CXMLNode* pSubSubNode = NULL;
                unsigned int uiSubSubNodesCount = pSubNode->GetSubNodeCount ();
                for ( unsigned int j = 0 ; j < uiSubSubNodesCount ; j++ )
                {
                    pSubSubNode = pSubNode->GetSubNode ( j );
                    if ( !pSubSubNode ) continue;

                    if ( pSubSubNode->GetTagName ().compare ( "object" ) == 0 )
                    {
                        CXMLAttribute* pSubAttribute = pSubSubNode->GetAttributes ().Find ( "name" );
                        if ( pSubAttribute )
                        {
                            const char *szAccountName = pSubAttribute->GetValue ().c_str ();

                            if ( StringBeginsWith ( szAccountName, "user." ) )
                            {
                                pGroup->AddObject ( &szAccountName[5], CAccessControlListGroupObject::OBJECT_TYPE_USER );
                            }
                            else if ( StringBeginsWith ( szAccountName, "resource." ) )
                            {
                                pGroup->AddObject ( &szAccountName[9], CAccessControlListGroupObject::OBJECT_TYPE_RESOURCE );
                            }
                        }
                    }
                    else if ( pSubSubNode->GetTagName ().compare ( "acl" ) == 0 )
                    {
                        CXMLAttribute* pSubAttribute = pSubSubNode->GetAttributes ().Find ( "name" );
                        if ( pSubAttribute )
                        {
                            CAccessControlList* pACL = GetACL ( pSubAttribute->GetValue ().c_str () );
                            if ( pACL )
                            {
                                pGroup->AddACL ( pACL );
                            }
                        }
                    }
                }
            }
        }
    }

    m_bNeedsSave = false;
    return true;
}
int CLuaFunctionDefs::XMLCopyFile ( lua_State* luaVM )
{
//  xmlnode xmlCopyFile ( xmlnode nodeToCopy, string newFilePath )
    CXMLNode* pSourceNode; SString newFilePath;

    CScriptArgReader argStream ( luaVM );
    argStream.ReadUserData ( pSourceNode );
    argStream.ReadString ( newFilePath );

    if ( !argStream.HasErrors () )
    {
        // Grab the virtual machine for this luastate
        CLuaMain* pLUA = m_pLuaManager->GetVirtualMachine ( luaVM );
        if ( pLUA )
        {
            CResource* pResource = pLUA->GetResource();
            SString strFilename;
            if ( CResourceManager::ParseResourcePathInput( newFilePath, pResource, strFilename ) )
            {
                if ( pSourceNode )
                {
                    // Grab the roots tag name
                    std::string strRootTagName;
                    strRootTagName = pSourceNode->GetTagName ();

                    // Grab our lua VM
                    CLuaMain* pLUA = m_pLuaManager->GetVirtualMachine ( luaVM );

                    // Create the new XML file and its root node
                    CXMLFile* pNewXML = pLUA->CreateXML ( strFilename );
                    if ( pNewXML )
                    {
                        // Create root for new XML
                        CXMLNode* pNewRoot = pNewXML->CreateRootNode ( strRootTagName );
                        if ( pNewRoot )
                        {
                            // Copy over the attributes from the root
                            int iAttributeCount = pSourceNode->GetAttributes ().Count ();
                            int i = 0;
                            CXMLAttribute* pAttribute;
                            for ( ; i < iAttributeCount; i++ )
                            {
                                pAttribute = pSourceNode->GetAttributes ().Get ( i );
                                if ( pAttribute )
                                    pNewRoot->GetAttributes ().Create ( *pAttribute );
                            }

                            // Copy the stuff from the given source node to the destination root
                            if ( pSourceNode->CopyChildrenInto ( pNewRoot, true ) )
                            {
                                lua_pushxmlnode ( luaVM, pNewRoot );
                                return 1;
                            }
                        }

                        // Delete the XML again
                        pLUA->DestroyXML ( pNewXML );
                    }
                }
            }
            else
                CLogger::ErrorPrintf ( "Unable to copy xml file; bad filepath" );
        }
    }
    else
        m_pScriptDebugging->LogCustom ( luaVM, argStream.GetFullErrorMessage() );

    // Error
    lua_pushboolean ( luaVM, false );
    return 1;
}