void DefaultResourceProvider::loadRawDataContainer(const String& filename, RawDataContainer& output, const String& resourceGroup)
    {
        if (filename.empty() || (filename == (utf8*)""))
        {
            throw InvalidRequestException((utf8*)
                "DefaultResourceProvider::load - Filename supplied for data loading must be valid");
        }


        std::wstring strFilename1 = filename.c_wstring ();
        std::wstring strFilename2 = System::getSingleton ().GetGuiWorkingDirectory().c_wstring () + strFilename1;

        // If supplied filename looks like it is absolute, try that first
        bool bIsAbsolutePath = false;
        {
            SString strTemp = PathConform ( filename.c_str () );
            if ( strTemp.Contains ( ":" ) || strTemp.BeginsWith ( "\\" ) )
                std::swap ( strFilename1, strFilename2 );
        }


        std::ifstream dataFile;
        dataFile.open(strFilename2.c_str (), std::ios::binary|std::ios::ate);

        if( dataFile.fail())
        {
            dataFile.clear();
            dataFile.open(strFilename1.c_str (), std::ios::binary|std::ios::ate);
            if( dataFile.fail())
            {
                throw InvalidRequestException((utf8*)
                    "DefaultResourceProvider::load - " + filename + " does not exist");
            }
        }
        std::streampos size = dataFile.tellg();
        dataFile.seekg (0, std::ios::beg);

        unsigned char* buffer = new unsigned char [(uint)size];

        try {
            dataFile.read(reinterpret_cast<char*>(buffer), size);
        }
        catch(std::ifstream::failure e) {
            delete [] buffer;
            throw GenericException((utf8*)
                "DefaultResourceProvider::loadRawDataContainer - Problem reading " + filename);
        }

        dataFile.close();

        //memcpy(container->getDataPtr(), buffer, size);
        output.setData(buffer);
        output.setSize((size_t)size);
        //delete [] buffer;
    }
Exemple #2
0
// Return true if path is not relative
bool SharedUtil::IsAbsolutePath ( const SString& strInPath )
{
    const SString strPath = PathConform ( strInPath );

    if ( strPath.BeginsWith( PATH_SEPERATOR ) )
        return true;
#ifdef WIN32
    if ( strPath.length() > 0 && strPath[1] == ':' )
        return true;
#endif
    return false;
}
Exemple #3
0
//////////////////////////////////////////////////////////
//
// HandleCustomStartMessage
//
//
//
//////////////////////////////////////////////////////////
void HandleCustomStartMessage ( void )
{
    SString strStartMessage = GetApplicationSetting( "diagnostics", "start-message" );
    SString strTrouble = GetApplicationSetting( "diagnostics", "start-message-trouble" );

    if ( strStartMessage.empty() )
        return;

    SetApplicationSetting( "diagnostics", "start-message", "" );
    SetApplicationSetting( "diagnostics", "start-message-trouble", "" );

    if ( strStartMessage.BeginsWith( "vdetect" ) )
    {
        SString strFilename = strStartMessage.SplitRight( "name=" );
        strStartMessage = _( "WARNING\n\n"
                             "MTA:SA has detected unusual activity.\n"
                             "Please run a virus scan to ensure your system is secure.\n\n" );
        strStartMessage += SString( _( "The detected file was:  %s\n" ), *strFilename );
    }

    DisplayErrorMessageBox( strStartMessage, _E("CL37"), strTrouble );
}
Exemple #4
0
// If compiled script, make sure correct chunkname is embedded
void CLuaShared::EmbedChunkName(SString strChunkName, const char** pcpOutBuffer, uint* puiOutSize)
{
    const char*& cpBuffer = *pcpOutBuffer;
    uint&        uiSize = *puiOutSize;

    if (!IsLuaCompiledScript(cpBuffer, uiSize))
        return;

    if (uiSize < 12)
        return;

    // Get size of name in original
    uint uiStringSizeOrig = *(uint*)(cpBuffer + 12);
    if (uiSize < 12 + 4 + uiStringSizeOrig)
        return;

    static CBuffer store;
    store.Clear();
    CBufferWriteStream stream(store);

    // Ensure name starts with @ and ends with NULL
    if (!strChunkName.BeginsWith("@"))
        strChunkName = "@" + strChunkName;
    if (strChunkName[strChunkName.length() - 1] != '\0')
        strChunkName.push_back('\0');

    // Header
    stream.WriteBytes(cpBuffer, 12);
    // New name size
    stream.Write(strChunkName.length());
    // New name bytes incl zero termination
    stream.WriteBytes(strChunkName.c_str(), strChunkName.length());
    // And the rest
    stream.WriteBytes(cpBuffer + 12 + 4 + uiStringSizeOrig, uiSize - 12 - 4 - uiStringSizeOrig);

    cpBuffer = store.GetData();
    uiSize = store.GetSize();
}
Exemple #5
0
//
// Scan resource directories
//
void CLocalServer::GetResourceNameList ( std::vector < SString >& outResourceNameList, const SString& strModPath )
{
    // Make list of potential active resources
    std::map < SString, SResInfo > resInfoMap;

    // Initial search dir
    std::vector < SString > resourcesPathList;
    resourcesPathList.push_back ( "resources" );

    //SString strModPath = g_pServerInterface->GetModManager ()->GetModPath ();
    for ( uint i = 0 ; i < resourcesPathList.size () ; i++ )
    {
        // Enumerate all files and directories
        SString strResourcesRelPath = resourcesPathList[i];
        SString strResourcesAbsPath = PathJoin ( strModPath, strResourcesRelPath, "/" );
        std::vector < SString > itemList = FindFiles ( strResourcesAbsPath, true, true );

        // Check each item
        for ( uint i = 0 ; i < itemList.size () ; i++ )
        {
            SString strName = itemList[i];

            // Ignore items that start with a dot
            if ( strName[0] == '.' )
                continue;

            bool bIsDir = DirectoryExists ( PathJoin ( strResourcesAbsPath, strName ) );

            // Recurse into [directories]
            if ( bIsDir && ( strName.BeginsWith( "#" ) || ( strName.BeginsWith( "[" ) && strName.EndsWith( "]" ) ) ) )
            {
                resourcesPathList.push_back ( PathJoin ( strResourcesRelPath, strName ) );
                continue;
            }

            // Extract file extention
            SString strExt;
            if ( !bIsDir )
                ExtractExtention ( strName, &strName, &strExt );

            // Ignore files that are not .zip
            if ( !bIsDir && strExt != "zip" )
                continue;

            // Ignore items that have dot or space in the name
            if ( strName.Contains ( "." ) || strName.Contains ( " " ) )
            {
                CLogger::LogPrintf ( "WARNING: Not loading resource '%s' as it contains illegal characters\n", *strName );
                continue;
            }

            // Ignore dir items with no meta.xml (assume it's the result of saved files from a zipped resource)
            if ( bIsDir && !FileExists ( PathJoin ( strResourcesAbsPath, strName, "meta.xml" ) ) )
                continue;

            // Add potential resource to list
            SResInfo newInfo;
            newInfo.strAbsPath = strResourcesAbsPath;
            newInfo.strName = strName;
            newInfo.bIsDir = bIsDir;
            newInfo.bPathIssue = false;

            // Check for duplicate
            if ( SResInfo* pDup = MapFind ( resInfoMap, strName ) )
            {
                // Is path the same?
                if ( newInfo.strAbsPath == pDup->strAbsPath )
                {
                    if ( newInfo.bIsDir )
                    {
                        // If non-zipped item, replace already existing zipped item on the same path
                        assert ( !pDup->bIsDir );
                        *pDup = newInfo;
                    }
                }
                else
                {
                    // Don't load resource if there are duplicates on different paths
                    pDup->bPathIssue = true;
                    pDup->strAbsPathDup = newInfo.strAbsPath;
                }
            }
            else
            {
                // No duplicate found
                MapSet ( resInfoMap, strName, newInfo );
            }
        }
    }

    // Print important errors
    for ( std::map < SString, SResInfo >::const_iterator iter = resInfoMap.begin () ; iter != resInfoMap.end () ; ++iter )
    {
        const SResInfo& info = iter->second;
        if ( info.bPathIssue )
        {
            CLogger::ErrorPrintf ( "Not processing resource '%s' as it has duplicates on different paths:\n", *info.strName );
            CLogger::LogPrintfNoStamp ( "                  Path #1: \"%s\"\n", *PathJoin ( PathMakeRelative ( strModPath, info.strAbsPath ), info.strName ) );
            CLogger::LogPrintfNoStamp ( "                  Path #2: \"%s\"\n", *PathJoin ( PathMakeRelative ( strModPath, info.strAbsPathDup ), info.strName ) );
        }
        else
        {
            outResourceNameList.push_back ( info.strName );
        }
    }
}
int CLuaDatabaseDefs::DbConnect ( lua_State* luaVM )
{
    //  element dbConnect ( string type, string host, string username, string password, string options )
    SString strType; SString strHost; SString strUsername; SString strPassword; SString strOptions;

    CScriptArgReader argStream ( luaVM );
    argStream.ReadString ( strType );
    argStream.ReadString ( strHost );
    argStream.ReadString ( strUsername, "" );
    argStream.ReadString ( strPassword, "" );
    argStream.ReadString ( strOptions, "" );

    if ( !argStream.HasErrors () )
    {
        CResource* pThisResource = m_pLuaManager->GetVirtualMachineResource ( luaVM );
        if ( pThisResource )
        {
            // If type is sqlite, and has a host, try to resolve path
            if ( strType == "sqlite" && !strHost.empty () )
            {
                // If path starts with :/ then use global database directory
                if ( strHost.BeginsWith ( ":/" ) )
                {
                    strHost = strHost.SubStr ( 1 );
                    if ( !IsValidFilePath ( strHost ) )
                    {
                        argStream.SetCustomError( SString( "host path %s not valid", *strHost ) );
                    }
                    else
                    {
                        strHost = PathJoin ( g_pGame->GetConfig ()->GetGlobalDatabasesPath (), strHost );
                    }
                }
                else
                {
                    std::string strAbsPath;

                    // Parse path
                    CResource* pPathResource = pThisResource;
                    if ( CResourceManager::ParseResourcePathInput ( strHost, pPathResource, &strAbsPath ) )
                    {
                        strHost = strAbsPath;
                        CheckCanModifyOtherResource( argStream, pThisResource, pPathResource );
                    }
                    else
                    {
                        argStream.SetCustomError( SString( "host path %s not found", *strHost ) );
                    }
                }
            }

            if ( !argStream.HasErrors() )
            {
                if ( strType == "mysql" )
                    pThisResource->SetUsingDbConnectMysql( true );

                // Add logging options
                bool bLoggingEnabled;
                SString strLogTag;
                SString strQueueName;
                // Set default values if required
                GetOption < CDbOptionsMap > ( strOptions, "log", bLoggingEnabled, 1 );
                GetOption < CDbOptionsMap > ( strOptions, "tag", strLogTag, "script" );
                GetOption < CDbOptionsMap > ( strOptions, "queue", strQueueName, (strType == "mysql") ? strHost : DB_SQLITE_QUEUE_NAME_DEFAULT );
                SetOption < CDbOptionsMap > ( strOptions, "log", bLoggingEnabled );
                SetOption < CDbOptionsMap > ( strOptions, "tag", strLogTag );
                SetOption < CDbOptionsMap > ( strOptions, "queue", strQueueName );
                // Do connect
                SConnectionHandle connection = g_pGame->GetDatabaseManager ()->Connect ( strType, strHost, strUsername, strPassword, strOptions );
                if ( connection == INVALID_DB_HANDLE )
                {
                    argStream.SetCustomError( g_pGame->GetDatabaseManager()->GetLastErrorMessage() );
                }
                else
                {
                    // Use an element to wrap the connection for auto disconnected when the resource stops
                    // Don't set a parent because the element should not be accessible from other resources
                    CDatabaseConnectionElement* pElement = new CDatabaseConnectionElement ( NULL, connection );
                    CElementGroup * pGroup = pThisResource->GetElementGroup ();
                    if ( pGroup )
                    {
                        pGroup->Add ( pElement );
                    }

                    lua_pushelement ( luaVM, pElement );
                    return 1;
                }
            }
        }
    }

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

    lua_pushboolean ( luaVM, false );
    return 1;
}
Exemple #7
0
bool CChat::CharacterKeyHandler(CGUIKeyEventArgs KeyboardArgs)
{
    // If we can take input
    if (!CLocalGUI::GetSingleton().GetConsole()->IsVisible() && IsInputVisible())
    {
        // Check if it's a special key like enter and backspace, if not, add it as a character to the message
        switch (KeyboardArgs.codepoint)
        {
            case VK_BACK:
            {
                if (m_strInputText.size() > 0)
                {
                    // Convert our string to UTF8 before resizing, then back to ANSI.
                    std::wstring strText = MbUTF8ToUTF16(m_strInputText);
                    strText.resize(strText.size() - 1);
                    SetInputText(UTF16ToMbUTF8(strText).c_str());
                }
                break;
            }

            case VK_RETURN:
            {
                // Empty the chat and hide the input stuff
                // If theres a command to call, call it
                if (!m_strCommand.empty() && !m_strInputText.empty())
                    CCommands::GetSingleton().Execute(m_strCommand.c_str(), m_strInputText.c_str());

                SetInputVisible(false);

                m_fSmoothScrollResetTime = GetSecondCount();
                break;
            }
            case VK_TAB:
            {
                if (m_bNickCompletion && m_strInputText.size() > 0)
                {
                    bool bSuccess = false;

                    SString strCurrentInput = GetInputText();
                    size_t  iFound;
                    iFound = strCurrentInput.find_last_of(" ");
                    if (iFound == std::string::npos)
                        iFound = 0;
                    else
                        ++iFound;

                    SString strPlayerNamePart = strCurrentInput.substr(iFound);

                    CModManager* pModManager = CModManager::GetSingletonPtr();
                    if (pModManager && pModManager->GetCurrentMod())
                    {
                        // Create vector and get playernames from deathmatch module
                        std::vector<SString> vPlayerNames;
                        pModManager->GetCurrentMod()->GetPlayerNames(vPlayerNames);

                        for (std::vector<SString>::iterator iter = vPlayerNames.begin(); iter != vPlayerNames.end(); ++iter)
                        {
                            SString strPlayerName = *iter;

                            // Check if there is another player after our last result
                            if (m_strLastPlayerName.size() != 0)
                            {
                                if (strPlayerName.CompareI(m_strLastPlayerName))
                                {
                                    m_strLastPlayerName.clear();
                                    if (*iter == vPlayerNames.back())
                                    {
                                        CharacterKeyHandler(KeyboardArgs);
                                        return true;
                                    }
                                }
                                continue;
                            }

                            // Already a part?
                            if (m_strLastPlayerNamePart.size() != 0)
                            {
                                strPlayerNamePart = m_strLastPlayerNamePart;
                            }

                            // Check namepart
                            if (!strPlayerName.BeginsWith(strPlayerNamePart))
                                continue;
                            else
                            {
                                // Check size if it's ok, then output
                                SString strOutput = strCurrentInput.replace(iFound, std::string::npos, strPlayerName);
                                if (MbUTF8ToUTF16(strOutput).size() < CHAT_MAX_CHAT_LENGTH)
                                {
                                    bSuccess = true;
                                    m_strLastPlayerNamePart = strPlayerNamePart;
                                    m_strLastPlayerName = strPlayerName;
                                    SetInputText(strOutput);
                                }

                                break;
                            }
                        }

                        // No success? Try again!
                        if (!bSuccess)
                            m_strLastPlayerName.clear();
                    }
                }
                break;
            }

            default:
            {
                // Clear last namepart when pressing letter
                if (m_strLastPlayerNamePart.size() != 0)
                    m_strLastPlayerNamePart.clear();

                // Clear last name when pressing letter
                if (m_strLastPlayerName.size() != 0)
                    m_strLastPlayerName.clear();

                // If we haven't exceeded the maximum number of characters per chat message, append the char to the message and update the input control
                if (MbUTF8ToUTF16(m_strInputText).size() < CHAT_MAX_CHAT_LENGTH)
                {
                    if (KeyboardArgs.codepoint >= 32)
                    {
                        unsigned int uiCharacter = KeyboardArgs.codepoint;
                        if (uiCharacter < 127)            // we have any char from ASCII
                        {
                            // injecting as is
                            m_strInputText += static_cast<char>(KeyboardArgs.codepoint);
                            SetInputText(m_strInputText.c_str());
                        }
                        else            // we have any char from Extended ASCII, any ANSI code page or UNICODE range
                        {
                            // Generate a null-terminating string for our character
                            wchar_t wUNICODE[2] = {uiCharacter, '\0'};

                            // Convert our UTF character into an ANSI string
                            std::string strANSI = UTF16ToMbUTF8(wUNICODE);

                            // Append the ANSI string, and update
                            m_strInputText.append(strANSI);
                            SetInputText(m_strInputText.c_str());
                        }
                    }
                }
                break;
            }
        }
    }

    return true;
}