Esempio n. 1
0
//
// Modifies the Filename's extension. The period is considered part
// of the extension.
//
// "/foo/bar/baz.txt", ".dat" --> "/foo/bar/baz.dat"
// "/foo/bar/baz.txt", "" --> "/foo/bar/baz"
// "/foo/bar/baz", ".txt" --> "/foo/bar/baz.txt"
//
UnicodeString ChangeFileExtension(const UnicodeString & Path, const UnicodeString & Ext, wchar_t Delimiter)
{
  UnicodeString FileName = ExtractFilename(Path, Delimiter);
  return ExtractDirectory(Path, Delimiter)
         + FileName.SubString(1, FileName.RPos(L'.'))
         + Ext;
}
Esempio n. 2
0
SString SharedUtil::MakeUniquePath ( const SString& strInPathFilename )
{
    const SString strPathFilename = PathConform ( strInPathFilename );

    SString strBeforeUniqueChar, strAfterUniqueChar;

    SString strPath, strFilename;
    ExtractFilename ( strPathFilename, &strPath, &strFilename );

    SString strMain, strExt;
    if ( ExtractExtension ( strFilename, &strMain, &strExt ) )
    {
        strBeforeUniqueChar = PathJoin ( strPath, strMain );
        strAfterUniqueChar = "." + strExt;
    }
    else
    {
        strBeforeUniqueChar = strPathFilename;
        strAfterUniqueChar = "";
    }

    SString strTest = strPathFilename;
    int iCount = 1;
#ifdef WIN32
    while ( GetFileAttributes ( strTest ) != INVALID_FILE_ATTRIBUTES )
#else
    while ( DirectoryExists ( strTest ) || FileExists ( strTest ) )
#endif
    {
        strTest = SString ( "%s_%d%s", strBeforeUniqueChar.c_str (), iCount++, strAfterUniqueChar.c_str () );
    }
    return strTest;
}
Esempio n. 3
0
void FindSimilaritiesForOne(FILE* fp, char* szTable, char* szFilePath)
{
	char szFilename[MAX_PATH];
	char szDirname[MAX_PATH];
	ExtractFilename(szFilePath, szFilename);
	ExtractDirname(szFilePath, szDirname);

	// Retrieve all rows
	mysqlpp::Query query = g_pdbcon1->query();
	query << "SELECT * FROM " << szTable;
	query << " WHERE filename= '" << szFilename << "' AND";
	query << " directoryname= '" << szDirname << "'";
	mysqlpp::ResUse res = query.use();
	if (!res)
	{
		printf("FindSimilaritiesForOne: Failed to query row");
		return; //error with query
	}

	mysqlpp::Row row;
	try
	{
		while (row = res.fetch_row())
			FindSimilarities(fp, szTable, row, false);
	}
	catch (const mysqlpp::EndOfResults& ){} // thrown when no more rows
}	// FindSimilaritiesForOne
Esempio n. 4
0
//////////////////////////////////////////////////////////
//
// HandleNotUsedMainMenu
//
// Called when a problem occured before the main menu was used by user
// If fullscreen, then maybe change fullscreen mode
//
//////////////////////////////////////////////////////////
void HandleNotUsedMainMenu ( void )
{
    AddReportLog( 9310, "Loader - HandleNotUsedMainMenu" );
    {
        // Slighty hacky way of checking in-game settings
        SString strCoreConfigFilename = CalcMTASAPath( PathJoin( "mta", "config", "coreconfig.xml" ) );
        SString strCoreConfig;
        FileLoad( strCoreConfigFilename, strCoreConfig );
        SString strWindowed        = strCoreConfig.SplitRight( "<display_windowed>" ).Left( 1 );
        SString strFullscreenStyle = strCoreConfig.SplitRight( "<display_fullscreen_style>" ).Left( 1 );
        if ( strFullscreenStyle == "1" )
        {
            AddReportLog( 9315, "Loader - HandleNotUsedMainMenu - Already Borderless window" );
        }
        else
        if ( !strWindowed.empty() && !strFullscreenStyle.empty())
        {
            if ( strWindowed == "0" && strFullscreenStyle == "0" )   // 0=FULLSCREEN_STANDARD
            {
                // Inform user
                SString strMessage = _("Are you having problems running MTA:SA?.\n\nDo you want to change the following setting?");
                strMessage += "\n" + _("Fullscreen mode:") + " -> " + _("Borderless window");
                HideSplash();
                int iResponse = MessageBoxUTF8 ( NULL, strMessage, "MTA: San Andreas", MB_YESNO | MB_ICONQUESTION | MB_TOPMOST );
                if ( iResponse == IDYES )
                {
                    // Very hacky way of changing in-game settings
                    strCoreConfig = strCoreConfig.Replace( "<display_fullscreen_style>0", "<display_fullscreen_style>1" );
                    FileSave( strCoreConfigFilename, strCoreConfig );
                    AddReportLog( 9311, "Loader - HandleNotUsedMainMenu - User change to Borderless window" );
                }
                else
                    AddReportLog( 9313, "Loader - HandleNotUsedMainMenu - User said no" );
            }
            else
                AddReportLog( 9314, "Loader - HandleNotUsedMainMenu - Mode not fullscreen standard" );
        }
        else
        {
            // If no valid settings file yet, do the change without asking
            strCoreConfig = "<mainconfig><settings><display_fullscreen_style>1</display_fullscreen_style></settings></mainconfig>";
            FileSave( strCoreConfigFilename, strCoreConfig );
            AddReportLog( 9312, "Loader - HandleNotUsedMainMenu - Set Borderless window" );
        }
    }

    // Check if Evolve is active
    for ( auto processId : MyEnumProcesses( true ) )
    {
        SString strFilename = ExtractFilename( GetProcessPathFilename( processId ) );
        if ( strFilename.BeginsWithI( "Evolve" ) )
        {
            SString strMessage = _("Are you having problems running MTA:SA?.\n\nTry disabling the following products for GTA and MTA:");
            strMessage += "\n\nEvolve";
            DisplayErrorMessageBox ( strMessage, _E("CL43"), "not-used-menu-evolve" );
            break;
        }
    }
}
HRESULT AgentConfigurationEx::CResetThread::Execute (DWORD_PTR dwParam, HANDLE hObject)
{
	static char name[] = "CResetThread::Execute";

	AgentConfigurationEx *agent = (AgentConfigurationEx *) dwParam;

	CancelWaitableTimer(hObject);

	// DebugBreak();

	try
	{
		PROCESS_INFORMATION pi;
		ZeroMemory(&pi, sizeof( pi ) );

		STARTUPINFO si;
		ZeroMemory(&si, sizeof( si ) );
		si.cb          = sizeof( si );
		si.dwFlags     = STARTF_USESHOWWINDOW;
		si.wShowWindow = SW_HIDE;        // set the window display to HIDE

		// SCM reset command of this service
#ifndef RESETTEST
		std::string cmd = StdStringFormat("cmd /c net stop \"%s\" & net start \"%s\"", Globals.ServerName.c_str( ), Globals.ServerName.c_str( ) ); // Command line
#else
		// This works when you run in from a command console as NikonAgent.exe debug, it will restart in the current DOS console.
		TCHAR buf[1000];
		GetModuleFileName(NULL, buf, 1000);
		std::string exepath = File.ExeDirectory();
		std::string exe = ExtractFilename(std::string(buf));
		//GLogger.Fatal(StdStringFormat("start Agent /d  \"%s\" /b \"%s\" debug\n", exepath.c_str(), buf  ) );
		std::string cmd = StdStringFormat("cmd /c taskkill /IM \"%s\" & \"%s\" debug", exe.c_str(),  buf ); // Command line
#endif

		if ( !::CreateProcess(NULL,                                                                                                                // No module name (use command line)
			const_cast<char *>( cmd.c_str( ) ),
			NULL,                                                                                                                               // Process handle not inheritable
			NULL,                                                                                                                               // Thread handle not inheritable
			FALSE,                                                                                                                              // Set handle inheritance to FALSE
			0,                                                                                                                                  // No creation flags
			NULL,                                                                                                                               // Use parent's environment block
			NULL,                                                                                                                               // Use parent's starting directory
			&si,                                                                                                                                // Pointer to STARTUPINFO structure
			&pi) )                                                                                                                              // Pointer to PROCESS_INFORMATION structure
		{
			AtlTrace("CreateProcess FAIL ");
		}

		::Sleep(5000);     // make sure process has spawned before killing thread
	}
	catch ( ... )
	{
		agent->AbortMsg("Exception  - ResetAtMidnightThread(void *oObject");
	}
	return S_OK;
}
Esempio n. 6
0
//
// Returns the file's extension, if any. The period is considered part
// of the extension.
//
// "/foo/bar/baz.txt" --> ".txt"
// "/foo/bar/baz" --> ""
UnicodeString ExtractFileExtension(const UnicodeString & Path, wchar_t Delimiter)
{
  UnicodeString FileName = ExtractFilename(Path, Delimiter);
  intptr_t N = FileName.RPos(L'.');
  if (N > 0)
  {
    return FileName.SubString(N);
  }
  return UnicodeString();
}
Esempio n. 7
0
void VorbitalDlg::LoadFile( QString& filename )
{
    int count = _lstPlaylist->count();
    if( _lstPlaylist != NULL )
    {
        QListWidgetItem* item = new QListWidgetItem(ExtractFilename(filename));
        item->setData(Qt::UserRole, QVariant(filename));
        _lstPlaylist->addItem(item);
        _lstPlaylist->setCurrentRow( count );
    }
    OnButtonPlayClick();
}
Esempio n. 8
0
void CAgentCfg::OnSaveCfg()
{
	CFileDialog dlg(FALSE,
		_T("*"),
		(::ExeDirectory() + "Agent.cfg").c_str(),
		OFN_HIDEREADONLY,
		strFilter);
	if( dlg.DoModal() != IDOK )
		return ;

	WriteCfgFile(ExtractFilename(dlg.m_szFileName), "", ExtractDirectory(dlg.m_szFileName) );
}
Esempio n. 9
0
static int isowavInit()
{
	wav_exit();

	isowavTOC = (isowavCDROM_TOC*)malloc(sizeof(isowavCDROM_TOC));
	if (isowavTOC == NULL) {
		return 1;
	}
	memset(isowavTOC, 0, sizeof(isowavCDROM_TOC));

	TCHAR* filename = ExtractFilename(CDEmuImage);

	if (_tcslen(filename) < 4) {
		return 1;
	}

	if (_tcscmp(_T(".cue"), filename + _tcslen(filename) - 4) == 0) {
		if (isowavParseCueFile()) {
			dprintf(_T("*** Couldn't parse .cue file\n"));
			isowavExit();

			return 1;
		}
	} else {
		if (isowavTestISO()) {
			dprintf(_T("*** Couldn't find .iso / .bin file\n"));
			isowavExit();

			return 1;
		}
	}

	dprintf(_T("    CD image TOC read\n"));
	
	for (int i = isowavTOC->FirstTrack - 1; i < isowavTOC->LastTrack; i++) {
		dprintf(_T("    track %2i start %02i:%02i:%02i control 0x%02X %s\n"), isowavTOC->TrackData[i].TrackNumber, isowavTOC->TrackData[i].Address[1], isowavTOC->TrackData[i].Address[2], isowavTOC->TrackData[i].Address[3], isowavTOC->TrackData[i].Control, isowavTOC->TrackData[i].Filename);
	}
	dprintf(_T("    total running time %02i:%02i:%02i\n"), isowavTOC->TrackData[(int)isowavTOC->LastTrack].Address[1], isowavTOC->TrackData[(int)isowavTOC->LastTrack].Address[2], isowavTOC->TrackData[(int)isowavTOC->LastTrack].Address[3]);

	CDEmuStatus = idle;
	
	return 0;
}
Esempio n. 10
0
/*!
* For a given directory name, extract all the files from that directory as well as
* from all its sub-directories and store the filenames in the fileList vector.
*
* \param folder folder to list
* \param fileExtList list of file extensions to search
* \param fileList list of files in folder
* \param symLinks follow Unix links?
*
* \return path exists and is a directory
*/
bool CUtil::ListAllFiles(string &folder, StringVector &fileExtList, StringVector &fileList, bool symLinks)
{
    StringVector tmpList;
    string file;
    size_t i, n;

    folder = CUtil::TrimString(folder);

#ifdef UNIX
    // skip links if user specified
    struct stat inodeData;
    if (!symLinks && (lstat(folder.c_str(), &inodeData) < 0 || S_ISLNK(inodeData.st_mode)))
        return(false);
#endif

    // process folder
    if (!GetFileList(tmpList, folder, symLinks))
        return(false);

    // read through tmpList and get the names of all the files in the directory mentioned
    for (n = 0; n < tmpList.size(); n++)
    {
        file = tmpList.at(n);

        // if no-extension filtering, each file is pushed into the fileList
        if (fileExtList.at(0) == "*.*" || fileExtList.at(0) == "*")
            fileList.push_back(file);
        else
        {
            // for each extension, if file extension matches with the extension, the file is pushed into the fileList
            for (i = 0; i < fileExtList.size(); i++)
            {
                if (MatchFilename(ExtractFilename(file), fileExtList.at(i)))
                    fileList.push_back(file);
            }
        }
    }
    tmpList.clear();
    return(true);
}
Esempio n. 11
0
std::string ExtractExt(const std::string& path) {
    std::string filename = ExtractFilename(path);
    return filename.substr(filename.find_last_of('.') + 1);
}
Esempio n. 12
0
static int isowavParseCueFile()
{
	TCHAR  szLine[1024];
	TCHAR  szFile[1024];
	TCHAR* s;
	TCHAR* t;
	FILE*  h;
	int    track = 0;
	int    length;

	isowavTOC->FirstTrack = 1;
	isowavTOC->LastTrack  = 1;

	isowavTOC->TrackData[0].Address[1] = 0;
	isowavTOC->TrackData[0].Address[2] = 2;
	isowavTOC->TrackData[0].Address[3] = 0;

	h = _tfopen(CDEmuImage, _T("rt"));
	if (h == NULL) {
		return 1;
	}

	while (1) {
		if (_fgetts(szLine, sizeof(szLine), h) == NULL) {
			break;
		}

		length = _tcslen(szLine);
		// get rid of the linefeed at the end
		while (length && (szLine[length - 1] == _T('\r') || szLine[length - 1] == _T('\n'))) {
			szLine[length - 1] = 0;
			length--;
		}

		s = szLine;

		// file info
		if ((t = LabelCheck(s, _T("FILE"))) != 0) {
			s = t;

			TCHAR* szQuote;

			// read filename
			QuoteRead(&szQuote, NULL, s);

			_sntprintf(szFile, ExtractFilename(CDEmuImage) - CDEmuImage, _T("%s"), CDEmuImage);
			_sntprintf(szFile + (ExtractFilename(CDEmuImage) - CDEmuImage), 1024 - (ExtractFilename(CDEmuImage) - CDEmuImage), _T("/%s"), szQuote);

			continue;
		}

		// track info
		if ((t = LabelCheck(s, _T("TRACK"))) != 0) {
			s = t;

			// track number
			track = _tcstol(s, &t, 10);

			if (track < 1 || track > MAXIMUM_NUMBER_TRACKS) {
				fclose(h);
				return 1;
			}

			if (track < isowavTOC->FirstTrack) {
				isowavTOC->FirstTrack = track;
			}
			if (track > isowavTOC->LastTrack) {
				isowavTOC->LastTrack = track;
			}
			isowavTOC->TrackData[track - 1].TrackNumber = track;

			isowavTOC->TrackData[track - 1].Filename = (TCHAR*)malloc((_tcslen(szFile) + 1) * sizeof(TCHAR));
			if (isowavTOC->TrackData[track - 1].Filename == NULL) {
				fclose(h);
				return 1;
			}
			_tcscpy(isowavTOC->TrackData[track - 1].Filename, szFile);

			s = t;

			// type of track

			if ((t = LabelCheck(s, _T("MODE1/2048"))) != 0) {
				isowavTOC->TrackData[track - 1].Control = 4;

				continue;
			}
			if ((t = LabelCheck(s, _T("AUDIO"))) != 0) {
				isowavTOC->TrackData[track - 1].Control = 0;

				continue;
			}

			fclose(h);
			return 1;
		}

		// pregap
		if ((t = LabelCheck(s, _T("PREGAP"))) != 0) {
			s = t;

			int M, S, F;

			// pregap M
			M = _tcstol(s, &t, 10);
			s = t + 1;
			// pregap S
			S = _tcstol(s, &t, 10);
			s = t + 1;
			// pregap F
			F = _tcstol(s, &t, 10);

			if (M < 0 || M > 100 || S < 0 || S > 59 || F < 0 || F > 74) {
				fclose(h);
				return 1;
			}

			isowavTOC->TrackData[track - 1].Address[1] = M;
			isowavTOC->TrackData[track - 1].Address[2] = S;
			isowavTOC->TrackData[track - 1].Address[3] = F;

			continue;
		}
	}

	fclose(h);

	return isowavGetTrackSizes();
}
Esempio n. 13
0
static int isowavTestISO()
{
	TCHAR fullname[MAX_PATH];
	TCHAR* filename;
	int   length = 0;
	int   offset = 0;
	int   track  = 2;
	FILE* h;

	_tcscpy(fullname, CDEmuImage);
	length = _tcslen(fullname);

	// assume CD-ROM mode1/2048 format

	if (length <= 4 && (_tcscmp(_T(".iso"), fullname + length - 4) || _tcscmp(_T(".bin"), fullname + length - 4))) {
		return 1;
	}

	// create a TOC with only the data track first

	isowavTOC->FirstTrack = 1;
	isowavTOC->LastTrack  = 1;

	isowavTOC->TrackData[0].TrackNumber = 1;

	isowavTOC->TrackData[0].Address[1] = 0;
	isowavTOC->TrackData[0].Address[2] = 2;
	isowavTOC->TrackData[0].Address[3] = 0;

	isowavTOC->TrackData[0].Filename = (TCHAR*)malloc((length + 1) * sizeof(TCHAR));
	if (isowavTOC->TrackData[0].Filename == NULL) {
		return 1;
	}
	_tcscpy(isowavTOC->TrackData[0].Filename, fullname);

	isowavTOC->TrackData[0].Control = 4;

	// if the filename has a number in it, try to find .mp3 tracks

	filename = ExtractFilename(fullname);
	offset = (filename - fullname) + length - 6;
	while (offset >= 0 && fullname[offset] != _T('0') && fullname[offset + 1] != _T('1')) {
		offset--;
	}
	if (offset < 0) {
		return isowavGetTrackSizes();
	}

	_stprintf(fullname + length - 4, _T(".wav"));

	while (1) {
		fullname[offset] = _T('0') + track / 10; fullname[offset + 1] = _T('0') + track % 10;
		
		if ((h = _tfopen(fullname, _T("rb"))) == NULL) {
			break;
		}
		fclose(h);

		isowavTOC->TrackData[track - 1].TrackNumber = track;

		isowavTOC->TrackData[track - 1].Filename = (TCHAR*)malloc((length + 1) * sizeof(TCHAR));
		if (isowavTOC->TrackData[track - 1].Filename == NULL) {
			return 1;
		}
		_tcscpy(isowavTOC->TrackData[track - 1].Filename, fullname);

		isowavTOC->LastTrack = track;

		track++;
	}

	return isowavGetTrackSizes();
}
Esempio n. 14
0
bool CRegistry::IntegrityCheck ( void )
{
    // Check database integrity
    {
        CRegistryResult result;
        bool bOk = Query( &result, "PRAGMA integrity_check" );

        // Get result as a string
        SString strResult;
        if ( result->nRows && result->nColumns )
        {
            CRegistryResultCell& cell = result->Data.front()[0];
            if ( cell.nType == SQLITE_TEXT )
                strResult = std::string ( (const char *)cell.pVal, cell.nLength - 1 );
        }

        // Process result
        if ( !bOk || !strResult.BeginsWithI ( "ok" ) )
        {
            CLogger::ErrorPrintf ( "%s", *strResult );
            CLogger::ErrorPrintf ( "%s\n", GetLastError ().c_str() );
            CLogger::ErrorPrintf ( "Errors were encountered loading '%s' database\n", *ExtractFilename ( PathConform ( m_strFileName ) ) );
            CLogger::ErrorPrintf ( "Maybe now is the perfect time to panic.\n" );
            CLogger::ErrorPrintf ( "See - http://wiki.multitheftauto.com/wiki/fixdb\n" );
            CLogger::ErrorPrintf ( "************************\n" );
            return false;
        }
    }

    // Do compact if required
    if ( g_pGame->GetConfig()->ShouldCompactInternalDatabases() )
    {
        CLogger::LogPrintf ( "Compacting database '%s' ...\n", *ExtractFilename ( PathConform ( m_strFileName ) ) );

        CRegistryResult result;
        bool bOk = Query( &result, "VACUUM" );

        // Get result as a string
        SString strResult;
        if ( result->nRows && result->nColumns )
        {
            CRegistryResultCell& cell = result->Data.front()[0];
            if ( cell.nType == SQLITE_TEXT )
                strResult = std::string ( (const char *)cell.pVal, cell.nLength - 1 );
        }

        // Process result
        if ( !bOk )
        {
            CLogger::ErrorPrintf ( "%s", *strResult );
            CLogger::ErrorPrintf ( "%s\n", GetLastError ().c_str() );
            CLogger::ErrorPrintf ( "Errors were encountered compacting '%s' database\n", *ExtractFilename ( PathConform ( m_strFileName ) ) );
            CLogger::ErrorPrintf ( "Maybe now is the perfect time to panic.\n" );
            CLogger::ErrorPrintf ( "See - http://wiki.multitheftauto.com/wiki/fixdb\n" );
            CLogger::ErrorPrintf ( "************************\n" );
            // Allow server to continue
        }
    }

    return true;
}
Esempio n. 15
0
std::string ChangeExtension( const std::string& path, const std::string& ext )
{
    std::string filename = ExtractFilename( path );
    return ExtractDirectory( path ) +filename.substr( 0, filename.find_last_of( '.' ) ) +ext;
}
Esempio n. 16
0
// gta_sa.exe
SString SharedUtil::GetLaunchFilename( void )
{
    return ExtractFilename( GetLaunchPathFilename() );
}
bool CAccessControlListManager::Load ( void )
{
    m_bAllowSave = true;

    // 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 () )
    {
        SString strParseErrorDesc;
        m_pXML->GetLastError( strParseErrorDesc );
        CLogger::ErrorPrintf ( "Error parsing %s - %s\n", *ExtractFilename( GetFileName() ), *strParseErrorDesc );
        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 ();
    ClearReadCache ();

    // 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;
}
Esempio n. 18
0
bool CAccountManager::IntegrityCheck ()
{
    // Check database integrity
    {
        CRegistryResult result;
        bool bOk = m_pDatabaseManager->QueryWithResultf ( m_hDbConnection, &result, "PRAGMA integrity_check" );

        // Get result as a string
        SString strResult;
        if ( result->nRows && result->nColumns )
        {
            CRegistryResultCell& cell = result->Data.front()[0];
            if ( cell.nType == SQLITE_TEXT )
                strResult = std::string ( (const char *)cell.pVal, cell.nLength - 1 );
        }

        // Process result
        if ( !bOk || !strResult.BeginsWithI ( "ok" ) )
        {
            CLogger::ErrorPrintf ( "%s", *strResult );
            CLogger::ErrorPrintf ( "%s\n", *m_pDatabaseManager->GetLastErrorMessage () );
            CLogger::ErrorPrintf ( "Errors were encountered loading '%s' database\n", *ExtractFilename ( PathConform ( "internal.db" ) ) );
            CLogger::ErrorPrintf ( "Maybe now is the perfect time to panic.\n" );
            CLogger::ErrorPrintf ( "See - http://wiki.multitheftauto.com/wiki/fixdb\n" );
            CLogger::ErrorPrintf ( "************************\n" );
            // Allow server to continue
        }
    }

    // Check can update file
    {
        m_pDatabaseManager->Execf ( m_hDbConnection, "DROP TABLE IF EXISTS write_test" );
        m_pDatabaseManager->Execf ( m_hDbConnection, "CREATE TABLE IF NOT EXISTS write_test (id INTEGER PRIMARY KEY, value INTEGER)" );
        m_pDatabaseManager->Execf ( m_hDbConnection, "INSERT OR IGNORE INTO write_test (id, value) VALUES(1,2)" ) ;
        bool bOk = m_pDatabaseManager->QueryWithResultf ( m_hDbConnection, NULL, "UPDATE write_test SET value=3 WHERE id=1" );
        if ( !bOk )
        {
            CLogger::ErrorPrintf ( "%s\n", *m_pDatabaseManager->GetLastErrorMessage () );
            CLogger::ErrorPrintf ( "Errors were encountered updating '%s' database\n", *ExtractFilename ( PathConform ( "internal.db" ) ) );
            CLogger::ErrorPrintf ( "Database might have incorrect file permissions, or locked by another process, or damaged.\n" );
            CLogger::ErrorPrintf ( "See - http://wiki.multitheftauto.com/wiki/fixdb\n" );
            CLogger::ErrorPrintf ( "************************\n" );
            return false;
        }
        m_pDatabaseManager->Execf ( m_hDbConnection, "DROP TABLE write_test" );
    }

    // Do compact if required
    if ( g_pGame->GetConfig()->ShouldCompactInternalDatabases() )
    {
        CLogger::LogPrintf ( "Compacting accounts database '%s' ...\n", *ExtractFilename ( PathConform ( "internal.db" ) ) );

        CRegistryResult result;
        bool bOk = m_pDatabaseManager->QueryWithResultf ( m_hDbConnection, &result, "VACUUM" );

        // Get result as a string
        SString strResult;
        if ( result->nRows && result->nColumns )
        {
            CRegistryResultCell& cell = result->Data.front()[0];
            if ( cell.nType == SQLITE_TEXT )
                strResult = std::string ( (const char *)cell.pVal, cell.nLength - 1 );
        }

        // Process result
        if ( !bOk )
        {
            CLogger::ErrorPrintf ( "%s", *strResult );
            CLogger::ErrorPrintf ( "%s\n", *m_pDatabaseManager->GetLastErrorMessage () );
            CLogger::ErrorPrintf ( "Errors were encountered compacting '%s' database\n", *ExtractFilename ( PathConform ( "internal.db" ) ) );
            CLogger::ErrorPrintf ( "Maybe now is the perfect time to panic.\n" );
            CLogger::ErrorPrintf ( "See - http://wiki.multitheftauto.com/wiki/fixdb\n" );
            CLogger::ErrorPrintf ( "************************\n" );
            // Allow server to continue
        }
    }
    return true;
}
////////////////////////////////////////////////////////////////
//
// CEffectTemplateImpl::CreateUnderlyingData
//
//
//
////////////////////////////////////////////////////////////////
void CEffectTemplateImpl::CreateUnderlyingData ( const SString& strFilename, const SString& strRootPath, SString& strOutStatus, bool bDebug )
{
    assert ( !m_pD3DEffect );

    // Make defines
    bool bUsesRAWZ = CGraphics::GetSingleton ().GetRenderItemManager ()->GetDepthBufferFormat () == RFORMAT_RAWZ;

    std::vector < D3DXMACRO > macroList;

    macroList.push_back ( D3DXMACRO () );
    macroList.back ().Name = "IS_DEPTHBUFFER_RAWZ";
    macroList.back ().Definition = bUsesRAWZ ? "1" : "0";

    macroList.push_back ( D3DXMACRO () );
    macroList.back ().Name = NULL;
    macroList.back ().Definition = NULL;

    // Compile effect
    DWORD dwFlags = 0;      // D3DXSHADER_PARTIALPRECISION, D3DXSHADER_DEBUG, D3DXFX_NOT_CLONEABLE;
    if ( bDebug )
        dwFlags |= D3DXSHADER_DEBUG;

    SString strMetaPath = strFilename.Right ( strFilename.length () - strRootPath.length () );
    CIncludeManager IncludeManager ( strRootPath, ExtractPath ( strMetaPath ) );
    LPD3DXBUFFER pBufferErrors = NULL;
    HRESULT hr = D3DXCreateEffectFromFile( m_pDevice, ExtractFilename ( strMetaPath ), &macroList[0], &IncludeManager, dwFlags, NULL, &m_pD3DEffect, &pBufferErrors );            

    // Handle compile errors
    strOutStatus = "";
    if( pBufferErrors != NULL )
    {
        strOutStatus = SStringX ( (CHAR*)pBufferErrors->GetBufferPointer() ).TrimEnd ( "\n" );

        // Error messages sometimes contain the current directory. Remove that here.
        SString strCurrentDirectory = GetSystemCurrentDirectory();
        strOutStatus = strOutStatus.ReplaceI ( strCurrentDirectory + "\\", "" );
        strOutStatus = strOutStatus.ReplaceI ( strCurrentDirectory, "" );
    }
    SAFE_RELEASE( pBufferErrors );

    if( !m_pD3DEffect )
    {
        if ( strOutStatus.empty () )
            strOutStatus = SString ( "[D3DXCreateEffectFromFile failed (%08x)%s]", hr, *IncludeManager.m_strReport );
        return;
    }

    // Find first valid technique
    D3DXHANDLE hTechnique = NULL;
    D3DXEFFECT_DESC EffectDesc;
    m_pD3DEffect->GetDesc ( &EffectDesc );

    for ( uint uiAttempt = 0 ; true ; uiAttempt++ )
    {
        SString strProblemInfo = "";
        for ( uint i = 0 ; i < EffectDesc.Techniques ; i++ )
        {
            SString strErrorExtra;
            D3DXHANDLE hTemp = m_pD3DEffect->GetTechnique ( i );
            HRESULT hr = m_pD3DEffect->ValidateTechnique ( hTemp );
            if ( SUCCEEDED( hr ) )
            {
                // Check depth buffer rules
                if ( ValidateDepthBufferUsage ( hTemp, strErrorExtra ) )
                {
                    hTechnique = hTemp;
                    break;
                }
            }

            // Update problem string
            D3DXTECHNIQUE_DESC TechniqueDesc;
            m_pD3DEffect->GetTechniqueDesc( hTemp, &TechniqueDesc );
            strProblemInfo += SString ( "['%s' (%d/%d) failed (%08x)%s]", TechniqueDesc.Name, i, EffectDesc.Techniques, hr, *strErrorExtra );
        }

        // Found valid technique
        if ( hTechnique )
            break;

        // Error if can't find a valid technique after 2nd attempt
        if ( uiAttempt > 0 )
        {
            strOutStatus = SString ( "No valid technique; [Techniques:%d %s]%s", EffectDesc.Techniques, *strProblemInfo, *IncludeManager.m_strReport );
            SAFE_RELEASE ( m_pD3DEffect );
            return;
        }

        // Try resetting samplers if 1st attempt failed
        LPDIRECT3DDEVICE9 pDevice;
        m_pD3DEffect->GetDevice ( &pDevice );
        for ( uint i = 0 ; i < 16 ; i++ )
        {
            pDevice->SetSamplerState ( i, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
            pDevice->SetSamplerState ( i, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
            pDevice->SetSamplerState ( i, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR );
        }
    }


    // Set technique
    m_pD3DEffect->SetTechnique( hTechnique );

    // Inform user of technique name
    D3DXTECHNIQUE_DESC TechniqueDesc;
    m_pD3DEffect->GetTechniqueDesc( hTechnique, &TechniqueDesc );
    strOutStatus = TechniqueDesc.Name;

    if ( bDebug )
    {
        // Disassemble effect
        LPD3DXBUFFER pDisassembly = NULL;
        if ( SUCCEEDED( D3DXDisassembleEffect( m_pD3DEffect, false, &pDisassembly ) ) && pDisassembly )
        {
            LPVOID pData = pDisassembly->GetBufferPointer();
            DWORD Size = pDisassembly->GetBufferSize();

            if( pData && Size )
            {
                SString strDisassemblyContents;
                strDisassemblyContents.assign ( (const char*)pData, Size - 1 );
                FileSave ( strFilename + ".dis", strDisassemblyContents );
            }

            SAFE_RELEASE( pDisassembly );
        }
    }

    // Copy MD5s of all loaded files
    m_FileMD5Map = IncludeManager.m_FileMD5Map;
    dassert ( !HaveFilesChanged() );
}
Esempio n. 20
0
SString SharedUtil::ExtractPath ( const SString& strPathFilename )
{
    SString strPath;
    ExtractFilename ( strPathFilename, &strPath, NULL );
    return strPath;
}
Esempio n. 21
0
SString SharedUtil::ExtractFilename ( const SString& strPathFilename )
{
    SString strFilename;
    ExtractFilename ( strPathFilename, NULL, &strFilename );
    return strFilename;
}