bool LogManager::Start(int maxIdle, LOG_LEVEL nLevel, const string& dir) { /* create log buffers */ for(int i = 0; i < maxIdle; i++) { Message *m = new Message(); mIdleMessageList.PushBack(m); } mIsRunning = true; // Just 4 log g_iLogLevel = nLevel; MkDir(dir.c_str()); mLogDir = dir; // MkDir(g_SysConf.strTempPath.c_str()); // InitMsgList(maxIdle); // KLog::SetLogDirectory(g_SysConf.strLogPath.c_str()); /* start log thread */ mpLogThread = new KThread(new LogRunnable(this)); if( mpLogThread->start() != 0 ) { // printf("# Create log thread ok \n"); } printf("# LogManager start OK. \n"); return true; }
void Log::logToErrFile(const char* log) { if(m_log_line==0 || m_err_log_file==NULL) { if(m_err_log_file) fclose(m_err_log_file); m_err_log_file=NULL; //日期变了,重设文件名 char new_log_file_name[50] = {0}; if(!IsDirExist("log")) MkDir("log"); std::string log_time=StringReplace(StrTimeStamp(), ":", "_"); sprintf_s(new_log_file_name, sizeof(new_log_file_name), "log\\error_%s.log", log_time.c_str()); fopen_s(&m_err_log_file, new_log_file_name, "a"); if(NULL==m_err_log_file) THROWNEXCEPT("create file:%s error.", new_log_file_name); } size_t count=strlen(log); size_t write_count=fwrite(log, sizeof(char), count, m_err_log_file); if(write_count!=count) THROWNEXCEPT("log to file error."); }
void Log::Redirect(string filename) { Put(INFO, "Log: Redirecting log (new log: " + filename + ")"); if (logfile.is_open()) logfile.close(); struct stat s; if (filename.find("/") != string::npos) MkDir(filename.substr(0, filename.find("/")), &s); if (filename != "") logfile.open(filename.c_str(), ios_base::out | ios_base::app); Put(INFO, "Log: Opened log"); }
////////////////////////////////////////////////////////// // // CheckOnRestartCommand // // Changes current directory if required // ////////////////////////////////////////////////////////// SString CheckOnRestartCommand ( void ) { const SString strMTASAPath = GetMTASAPath (); SetCurrentDirectory ( strMTASAPath ); SetDllDirectory( strMTASAPath ); SString strOperation, strFile, strParameters, strDirectory, strShowCmd; if ( GetOnRestartCommand ( strOperation, strFile, strParameters, strDirectory, strShowCmd ) ) { if ( strOperation == "files" || strOperation == "silent" ) { // // Update // // Make temp path name and go there SString strArchivePath, strArchiveName; strFile.Split ( "\\", &strArchivePath, &strArchiveName, -1 ); SString strTempPath = MakeUniquePath ( strArchivePath + "\\_" + strArchiveName + "_tmp_" ); if ( !MkDir ( strTempPath ) ) return "FileError1"; if ( !SetCurrentDirectory ( strTempPath ) ) return "FileError2"; // Start progress bar if ( !strParameters.Contains( "hideprogress" ) ) StartPseudoProgress( g_hInstance, "MTA: San Andreas", _("Extracting files...") ); // Try to extract the files if ( !ExtractFiles ( strFile ) ) { // If extract failed and update file is an exe, try to run it if ( ExtractExtension ( strFile ).CompareI ( "exe" ) ) ShellExecuteBlocking ( "open", strFile, "-s" ); } // Stop progress bar StopPseudoProgress(); // If a new "Multi Theft Auto.exe" exists, let that complete the install if ( FileExists ( MTA_EXE_NAME_RELEASE ) ) return "install from far " + strOperation + " " + strParameters; // Otherwise use the current exe to install return "install from near " + strOperation + " " + strParameters; } else { AddReportLog ( 5052, SString ( "CheckOnRestartCommand: Unknown restart command %s", strOperation.c_str () ) ); } } return "no update"; }
bool sprawl::filesystem::MakeDirs(sprawl::String const& path, sprawl::filesystem::PermissionType::Type mode) { char const* const start = path.c_str(); char const* ptr = start; char const* const end = start + path.length(); char const sep = path::Separator(); char const altSep = path::AltSeparator(); while(ptr < end) { if(*ptr == sep || *ptr == altSep) { sprawl::String str(start, ptr - start); if(!path::Exists(str)) { if(!MkDir(str, mode)) { return false; } } else if(!path::IsDirectory(str)) { return false; } } ++ptr; } sprawl::String str(start, ptr - start); if(!path::Exists(str)) { if(!MkDir(str, mode)) { return false; } } else if(!path::IsDirectory(str)) { return false; } return true; }
static int32_t backup_log(log_t *log) { int32_t ret = 0; char bakName[LOG_NAME_LEN]; char name[LOG_NAME_LEN]; time_t t = 0; struct tm *ts = NULL; if (0 == (log->mode & LOG_TO_FILE)) { return 0; } MkDir(log->dir); OS_RWLOCK_WRLOCK(&log->rwlock); t = time(NULL); ts = localtime(&t); if (NULL == ts) { OS_SNPRINTF(bakName, LOG_NAME_LEN, "%s/%s.log.bak", log->dir, log->name); } else { OS_SNPRINTF(bakName, LOG_NAME_LEN, "%s/%s_%04d%02d%02d_%02d%02d%02d.log", log->dir, log->name, ts->tm_year+1900, ts->tm_mon+1, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec); } OS_SNPRINTF(name, LOG_NAME_LEN, "%s/%s.log", log->dir, log->name); if (NULL != log->disk_hnd) { os_file_close(log->disk_hnd); log->disk_hnd = NULL; } unlink(bakName); rename(name, bakName); if (NULL == open_log(log)) { ret = -1; } log->total_lines = 0; OS_RWLOCK_WRUNLOCK(&log->rwlock); return ret; }
CuSuite* DLL_CALLCONV CuGetFreeImageAlgorithmsColourSuite(void) { CuSuite* suite = CuSuiteNew(); MkDir(TEST_DATA_OUTPUT_DIR "/Colour"); //SUITE_ADD_TEST(suite, TestFIA_ColourFunctions); SUITE_ADD_TEST(suite, TestFIA_ColourExtract); return suite; }
static int UpgradeNSIS(void) { std::string installPath = GetNSISInstallPath(); if (installPath.empty()) return 0; std::string uninstallerPath = installPath + "\\uninstall.exe"; if (!PathExists(uninstallerPath)) return 0; std::string dataPath = GetIcingaDataPath(); if (dataPath.empty()) return 1; bool moveUserData = !PathExists(dataPath); /* perform open heart surgery on the user's data dirs - yay */ if (moveUserData) { MkDir(dataPath.c_str()); std::string oldNameEtc = installPath + "\\etc"; std::string newNameEtc = dataPath + "\\etc"; if (!CopyDirectory(oldNameEtc, newNameEtc)) return 1; std::string oldNameVar = installPath + "\\var"; std::string newNameVar = dataPath + "\\var"; if (!CopyDirectory(oldNameVar, newNameVar)) return 1; } ExecuteCommand(uninstallerPath, "/S _?=" + installPath); _unlink(uninstallerPath.c_str()); if (moveUserData) { std::string oldNameEtc = installPath + "\\etc"; if (!DeleteDirectory(oldNameEtc)) return 1; std::string oldNameVar = installPath + "\\var"; if (!DeleteDirectory(oldNameVar)) return 1; _rmdir(installPath.c_str()); } return 0; }
static void MkDirP(const std::string& path) { size_t pos = 0; while (pos != std::string::npos) { pos = path.find_first_of("/\\", pos + 1); std::string spath = path.substr(0, pos + 1); struct _stat statbuf; if (_stat(spath.c_str(), &statbuf) < 0 && errno == ENOENT) MkDir(path.substr(0, pos)); } }
void ApiMkDir(DWORD *argv) { const char *path; if ((argv[MSG_ATTR_ID] & MSG_MAP_MASK) != MSG_ATTR_ROMAP) return; path = (const char*)argv[MSG_ADDR_ID]; if (CheckPathSize(path, argv[MSG_SIZE_ID]) == NULL) argv[MSG_RES_ID] = FS_ERR_ARGS_TOOLONG; else argv[MSG_RES_ID] = MkDir(pret[((THREAD_ID*)&argv[PTID_ID])->ProcID], path); KUnmapProcAddr((void*)path, argv); }
///////////////////////////////////////////////////////////////////////////////////////// // //创建/打开文件 // //特性:文件不存在--创建,文件存在--打开文件并把属性设为NORMAL,即可以写只读文件。关闭 // 文件时恢复文件原属性。根据参数dwCreate: // = RF_NEW -- 清除文件,截断为0 // = RF_APPEND -- 文件指针移到文件尾 // = RF_EDIT -- 打开文件 // //返回:文件不存在--FALSE,成功--TRUE // BOOL ringFile::Create(DWORD dwCreate,DWORD dwAttr/*=FILE_ATTRIBUTE_NORMAL*/) { DWORD dwMode = RF_EDIT; if(m_hFile) { if(dwCreate == RF_APPEND) Seek(0,FILE_END); else if(dwCreate == RF_NEW) Seek(0); return TRUE; } switch(m_aAttrib) { case RFA_FILE: //临时文件无须设置属性 if((m_dwFileAttr & FILE_ATTRIBUTE_TEMPORARY) != FILE_ATTRIBUTE_TEMPORARY) SetFileAttributes(m_szFilename,FILE_ATTRIBUTE_NORMAL); if(dwCreate == RF_NEW) dwMode = TRUNCATE_EXISTING; break; case RFA_NOTEXIST: MkDir(Pathname()); m_dwFileAttr = dwAttr; break; default: return FALSE; } m_hFile = CreateFile(m_szFilename,GENERIC_READ | GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,NULL,dwMode,FILE_ATTRIBUTE_NORMAL,NULL); if(m_hFile==INVALID_HANDLE_VALUE) { m_hFile = NULL; m_dwFileAttr = 0xffffffff; m_aAttrib = RFA_NOTEXIST; return FALSE; } else { if(dwCreate == RF_APPEND) SeekToEnd(); m_dwFileSize = ::GetFileSize(m_hFile,NULL); return TRUE; } }
CuSuite* DLL_CALLCONV CuGetFreeImageAlgorithmsMorphologySuite(void) { CuSuite* suite = CuSuiteNew(); MkDir(TEST_DATA_OUTPUT_DIR "/Morphology"); SUITE_ADD_TEST(suite, TestFIA_DilationTest); SUITE_ADD_TEST(suite, TestFIA_ErosionTest); SUITE_ADD_TEST(suite, TestFIA_OpeningTest); SUITE_ADD_TEST(suite, TestFIA_ClosingTest); return suite; }
CuSuite* DLL_CALLCONV CuGetFreeImageAlgorithmsIOSuite(void) { CuSuite* suite = CuSuiteNew(); MkDir(TEST_DATA_OUTPUT_DIR "/IO"); MkDir(TEST_DATA_OUTPUT_DIR "/IO/SimpleSave"); MkDir(TEST_DATA_OUTPUT_DIR "/IO/ForcedSave"); SUITE_ADD_TEST(suite, TestFIA_LoadBinaryTest); //SUITE_ADD_TEST(suite, TestFIA_IOSave8BitJpegTest); /* SUITE_ADD_TEST(suite, TestFIA_IOSave8BitPngTest); SUITE_ADD_TEST(suite, TestFIA_IOSave8BitTifTest); SUITE_ADD_TEST(suite, TestFIA_IOSave16UBitPngTest); SUITE_ADD_TEST(suite, TestFIA_IOSave16UBitTifTest); SUITE_ADD_TEST(suite, TestFIA_IOSave16BitPngTest); SUITE_ADD_TEST(suite, TestFIA_IOSave16BitTifTest); SUITE_ADD_TEST(suite, TestFIA_IOSave32BitFloatPngTest); SUITE_ADD_TEST(suite, TestFIA_IOSave32BitFloatTifTest); SUITE_ADD_TEST(suite, TestFIA_IOSave32BitFloatExrTest); SUITE_ADD_TEST(suite, TestFIA_IOSaveForced8BitPngTest); SUITE_ADD_TEST(suite, TestFIA_IOSaveForced24BitPngTest); SUITE_ADD_TEST(suite, TestFIA_IOSaveForced16BitPngTest); SUITE_ADD_TEST(suite, TestFIA_IOSaveForced32BitPngTest); SUITE_ADD_TEST(suite, TestFIA_Convert48BitsToStandardType); */ //SUITE_ADD_TEST(suite, TestFIA_IO); SUITE_ADD_TEST(suite, TestFIA_IOLoadColourArrayData); //SUITE_ADD_TEST(suite, TestFIA_SaveBPPWithPalette); return suite; }
////////////////////////////////////////////////////////// // // CInstallManager::_InstallNewsItems // // // ////////////////////////////////////////////////////////// SString CInstallManager::_InstallNewsItems ( void ) { // Get install news queue CArgMap queue; queue.SetFromString ( GetApplicationSetting ( "news-install" ) ); SetApplicationSetting ( "news-install", "" ); std::vector < SString > keyList; queue.GetKeys ( keyList ); for ( uint i = 0 ; i < keyList.size () ; i++ ) { // Install each file SString strDate = keyList[i]; SString strFileLocation = queue.Get ( strDate ); // Save cwd SString strSavedDir = GetSystemCurrentDirectory (); // Calc and make target dir SString strTargetDir = PathJoin ( GetMTADataPath (), "news", strDate ); MkDir ( strTargetDir ); // Extract into target dir SetCurrentDirectory ( strTargetDir ); // Try to extract the files if ( !ExtractFiles ( strFileLocation ) ) { // If extract failed and update file is an exe, try to run it if ( ExtractExtension ( strFileLocation ).CompareI ( "exe" ) ) ShellExecuteBlocking ( "open", strFileLocation, "-s" ); } // Restore cwd SetCurrentDirectory ( strSavedDir ); // Check result if ( FileExists ( PathJoin ( strTargetDir, "files.xml" ) ) ) { SetApplicationSettingInt ( "news-updated", 1 ); AddReportLog ( 2051, SString ( "InstallNewsItems ok for '%s'", *strDate ) ); } else { AddReportLog ( 4048, SString ( "InstallNewsItems failed with '%s' '%s' '%s'", *strDate, *strFileLocation, *strTargetDir ) ); } } return "ok"; }
bool CServerSession::OnLogOn( CNcpMessage* pMsg, int nBufSize ) { char path[MAXPATH]; //parse parameters int nFileMode = pMsg->GetRet(); string strUser = (char*)pMsg->GetData(); string strPass = (char*)( pMsg->GetData()+strUser.size()+1 ); //get home path #ifdef _WIN32 GetModuleFileName( NULL, path, ELEMENTS(path) ); char* p = strrchr( path, '\\' ); if( p!=NULL )*p = '\0'; #else getcwd( path, ELEMENTS(path) ); #endif CatDir( path, strUser.c_str(), path, ELEMENTS(path) ); //now path is the current home path. //make home directory if necessary int nRet = S_OK; if( !IsDirExist(path) ) { if( MkDir( path )!=0 ) { nRet = E_ACCES; } } m_strHomeDir = path; m_strCurDir = m_strHomeDir; m_nFileMode = nFileMode; if( SUCCEEDED(nRet) && !IsDirExist(m_strHomeDir.c_str()) ) { nRet = E_NOUSER; } pMsg->Init( CM_ACK, nRet ); pMsg->Send( m_sock ); //switch established if( SUCCEEDED(nRet) ) { m_state = NCPS_ESTABLISHED; if( strcmp( strUser.c_str(), "root" )==0 )m_bRootUsr = true; ASSERT( m_pServApp ); //lock the same user logon from other hosts. m_pLocker = m_pServApp->GetSessionLocker( strUser.c_str() ); m_pLocker->Lock(); } return SUCCEEDED(nRet); }
void RecursiveCopy(const std::string& srcDir, const std::string& destDir) { #ifdef FILECOPY_DEBUG std::cout << "Recursively copying " << srcDir << " to " << destDir << "\n"; std::cout << "Making dir " << destDir << "\n"; #endif MkDir(destDir); // List contents of src dir DirEnts des; Dir(srcDir, &des, false); for (unsigned int i = 0; i < des.size(); i++) { DirEnt& de = des[i]; #ifdef FILECOPY_DEBUG std::cout << "In " << srcDir << ": " << " found: " << de.m_name << (de.m_isDir ? " (DIR)" : "") << "\n"; #endif if (de.m_name[0] == '.') // name starts with a dot ? { #ifdef FILECOPY_DEBUG std::cout << "...skipping this dir.\n"; #endif continue; } if (de.m_isDir) { #ifdef FILECOPY_DEBUG std::cout << "So should recusively copy...\n"; #endif std::string dir = "/" + de.m_name + "/"; RecursiveCopy(srcDir + dir, destDir + dir); } else { CopyFileIfMissing(de.m_name, srcDir, destDir); } } }
CuSuite* DLL_CALLCONV CuGetFreeImageAlgorithmsGradientBlendSuite(void) { CuSuite* suite = CuSuiteNew(); MkDir(TEST_DATA_OUTPUT_DIR "/GradientBlending"); SUITE_ADD_TEST(suite, TestFIA_GradientBlendPasteTest1); SUITE_ADD_TEST(suite, TestFIA_GradientBlendPasteTest2); SUITE_ADD_TEST(suite, TestFIA_GradientBlendPasteTest3); SUITE_ADD_TEST(suite, TestFIA_GradientBlendPasteTest4); SUITE_ADD_TEST(suite, TestFIA_GradientBlendPasteTest5); SUITE_ADD_TEST(suite, TestFIA_GradientBlendPasteTest6); SUITE_ADD_TEST(suite, TestFIA_GradientBlendPasteTest7); SUITE_ADD_TEST(suite, TestFIA_GradientBlendPasteTest8); return suite; }
bool nwxFileUtil::MkDir(const wxString &sDir) { bool bRtn = false; if(wxDir::Exists(sDir)) { bRtn = true; } else { wxString s(sDir); UpDir(&s,1); if(MkDir(s)) // check parent directory { // parent directory now exists // make directory bRtn = ::wxMkdir(sDir); } } return bRtn; }
/** Call all tests */ GLDEF_C void CallTestsL() { TInt r = client.CreateLocal(0); FailIfError(r); gFileSize = 8; CSelectionBox* TheSelector = CSelectionBox::NewL(test.Console()); // Each test case of the suite has an identifyer for parsing purposes of the results gTestHarness = 6; gTestCase = 1; PrintHeaders(1, _L("t_fsrmkdir. Mkdir")); if(gMode == 0) { // Manual gSessionPath=_L("?:\\"); TCallBack createFiles(TestFileCreate, TheSelector); TCallBack MkDir(TestMake, TheSelector); TCallBack makeMultSame(TestMakeMultSame, TheSelector); TCallBack makeMultDif(TestMakeMultDif, TheSelector); TCallBack makeAll(TestAll, TheSelector); TheSelector->AddDriveSelectorL(TheFs); TheSelector->AddLineL(_L("Create all files"), createFiles); TheSelector->AddLineL(_L("Mkdir "), MkDir); TheSelector->AddLineL(_L("Mkdir mult clients same dir "), makeMultSame); TheSelector->AddLineL(_L("Mkdir mult clients dif dir"), makeMultDif); TheSelector->AddLineL(_L("Execute all options"), makeAll); TheSelector->Run(); } else { // Automatic TestAll(TheSelector); } client.Close(); test.Printf(_L("#~TestEnd_%d\n"), gTestHarness); delete TheSelector; }
// ------------------------------------------------------------------------------------------------- static void switch_file(LOG_HANDLE *hHandle, int isretry) { char filename[512] = {0}; time_t log_time = 0; struct tm *newtime = NULL; if (!hHandle) return; if (hHandle->g_cur_file) { fclose(hHandle->g_cur_file); hHandle->g_cur_file = NULL; } time(&log_time); newtime = localtime(&log_time); if (!isretry) { snprintf(filename, sizeof(filename), ".\\log\\%s_%d-%d-%d.log", hHandle->g_fname_prefix, newtime->tm_year + 1900, newtime->tm_mon + 1, newtime->tm_mday); } else { snprintf(filename, sizeof(filename), ".\\log\\%s_%d-%d-%d_%d-%d-%d.log", hHandle->g_fname_prefix, newtime->tm_year + 1900, newtime->tm_mon + 1, newtime->tm_mday, newtime->tm_hour, newtime->tm_min, newtime->tm_sec); } MkDir("log"); hHandle->g_cur_file = fopen(filename, "ab"); if (!hHandle->g_cur_file) { #ifdef _MSC_VER Sleep(1000); #else usleep(1000 * 1000); #endif switch_file(hHandle, 1); } hHandle->g_bytes = 0; }
bool CServerSession::OnMkDir( CNcpMessage* pMsg, int nSize ) { char path[MAXPATH]; //parse the parameters char* pName = (char*)pMsg->GetData(); if( IsAbsDir( pName ) ) { strcpy( path, pName ); } else { CatDir( m_strCurDir.c_str(), pName, path, ELEMENTS(path) ); } int nRetCode = S_OK; //make the directory if( MkDir( path )!=0 ) { nRetCode = S_EXIST; } pMsg->Init( CM_ACK, nRetCode ); pMsg->Send( m_sock ); return SUCCEEDED(nRetCode); }
/** * \brief Given an ISO image and a directory, * extract the image to the directory. * * ISO images have magic type "application/x-iso". * This can unpack any known ISO9660 format including: * ISO9660, Rock Ridge, Joliet, and El Torrito. * * Uses the following external commands: `isoinfo grep` * \note This spawns multiple processes. * \param Source * \param Destination * \return 0 on success, non-zero on failure. **/ int ExtractISO (char *Source, char *Destination) { char Cmd[FILENAME_MAX*4]; /* command to run */ char Line[FILENAME_MAX]; int Len; char *s; /* generic string pointer */ FILE *Fin; int rc; char TempSource[FILENAME_MAX], TempDestination[FILENAME_MAX]; /* judge if the parameters are empty */ if ((NULL == Source) || (!strcmp(Source, "")) || (NULL == Destination) || (!strcmp(Destination, ""))) return 1; if (!Quiet && Verbose) fprintf(stderr,"Extracting ISO: %s\n",Source); /* get list of directories in the ISO and make the directories */ if (TaintString(TempSource,FILENAME_MAX,Source,1,NULL) || TaintString(TempDestination,FILENAME_MAX,Destination,1,NULL)) return(-1); memset(Cmd,'\0',sizeof(Cmd)); snprintf(Cmd,sizeof(Cmd)," (isoinfo -l -R -J -i '%s' || isoinfo -l -R -i '%s' " "|| isoinfo -l -i '%s') 2>/dev/null | grep '^Directory'", TempSource, TempSource, TempSource); Fin = popen(Cmd,"r"); if (!Fin) { fprintf(stderr,"ERROR: ISO failed: %s\n",Cmd); return(-1); } while(ReadLine(Fin,Line,sizeof(Line)-1) >= 0) { s=strchr(Line,'/'); /* find first slash */ if (s==NULL) continue; snprintf(Cmd,sizeof(Cmd),"%s%s",Destination,s); if (Verbose > 1) printf("ISO directory: %s\n",Cmd); if (MkDir(Cmd)) { fprintf(stderr,"ERROR: Unable to mkdir(%s) in ExtractISO\n",Cmd); if (!ForceContinue) SafeExit(40); } } pclose(Fin); /* Now let's extract each file */ snprintf(Cmd,sizeof(Cmd),"(isoinfo -f -R -J -i '%s' || isoinfo -f -R -i '%s' || isoinfo -f -i '%s') 2>/dev/null", TempSource, TempSource, TempSource); Fin = popen(Cmd,"r"); if (!Fin) { fprintf(stderr,"ERROR: ISO failed: %s\n",Cmd); return(-1); } memset(Line,'\0',sizeof(Line)); strcpy(Line,Destination); Len=strlen(Destination); while(ReadLine(Fin,Line+Len,sizeof(Line)-1-Len) >= 0) { if (Line[Len] != '/') continue; /* should not happen, but... */ if (IsDir(Line)) continue; /* don't do directories */ if (Verbose > 1) printf("ISO file: %s\n",Line); /* create extraction command */ snprintf(Cmd,sizeof(Cmd),"(isoinfo -R -J -i '%s' -x '%s' || isoinfo -R -i '%s' -x '%s' || isoinfo -i '%s' -x '%s') > '%s' 2>/dev/null",TempSource,Line+Len,TempSource,Line+Len,TempSource, Line+Len,Line); rc = system(Cmd); if (WIFSIGNALED(rc)) { printf("ERROR: Process killed by signal (%d): %s\n",WTERMSIG(rc),Cmd); SafeExit(-1); } rc = WEXITSTATUS(rc); if (rc) { fprintf(stderr,"ERROR: Command failed (rc=%d): %s\n",rc,Cmd); pclose(Fin); return(rc); } } pclose(Fin); #if 0 /* save the ISO information */ snprintf(Cmd,sizeof(Cmd),"(isoinfo -d -R -i '%s' || isoinfo -d -R -J -i '%s' || isoinfo -d -i '%s') > '%s/ISO_INFO' 2>/dev/null", TempSource, TempSource, TempSource, TempDestination); rc = system(Cmd); if (WIFSIGNALED(rc)) { printf("ERROR: Process killed by signal (%d): %s\n",WTERMSIG(rc),Cmd); SafeExit(-1); } rc = WEXITSTATUS(rc); if (rc) { fprintf(stderr,"ERROR: Command failed (rc=%d): %s\n",rc,Cmd); return(rc); } #endif /* Set the permissions on every file and directory */ /* Only RockRidge saves permission information! */ snprintf(Cmd,sizeof(Cmd),"(isoinfo -l -R -J -i '%s' || isoinfo -l -R -i '%s' || isoinfo -l -i '%s') 2>/dev/null", TempSource, TempSource, TempSource); Fin = popen(Cmd,"r"); if (Fin) { mode_t Mode; char Dir[FILENAME_MAX]; memset(Dir,'\0',sizeof(Dir)); while((Len = ReadLine(Fin,Line,sizeof(Line)-1)) >= 0) { if (Len == 0) continue; if (!strchr("Dd-",Line[0])) continue; /* Every line is either a "Directory" or desirable chmod */ if (!strncmp(Line,"Directory listing of ",21)) { strcpy(Dir,Line+22); continue; } snprintf(Cmd,sizeof(Cmd)-1,"%s/%s%s",Destination,Dir,Line+67); Mode = GetISOMode(Line); chmod(Cmd,Mode); } pclose(Fin); } /* All done */ return(0); } /* ExtractISO() */
int CollectDataFlow(const std::string &DFTBinary, const std::string &DirPath, const Vector<SizedFile> &CorporaFiles) { Printf("INFO: collecting data flow: bin: %s dir: %s files: %zd\n", DFTBinary.c_str(), DirPath.c_str(), CorporaFiles.size()); MkDir(DirPath); auto Temp = TempPath(".dft"); for (auto &F : CorporaFiles) { // For every input F we need to collect the data flow and the coverage. // Data flow collection may fail if we request too many DFSan tags at once. // So, we start from requesting all tags in range [0,Size) and if that fails // we then request tags in [0,Size/2) and [Size/2, Size), and so on. // Function number => DFT. std::unordered_map<size_t, Vector<uint8_t>> DFTMap; std::unordered_set<std::string> Cov; std::queue<std::pair<size_t, size_t>> Q; Q.push({0, F.Size}); while (!Q.empty()) { auto R = Q.front(); Printf("\n\n\n********* Trying: [%zd, %zd)\n", R.first, R.second); Q.pop(); Command Cmd; Cmd.addArgument(DFTBinary); Cmd.addArgument(std::to_string(R.first)); Cmd.addArgument(std::to_string(R.second)); Cmd.addArgument(F.File); Cmd.addArgument(Temp); Printf("CMD: %s\n", Cmd.toString().c_str()); if (ExecuteCommand(Cmd)) { // DFSan has failed, collect tags for two subsets. if (R.second - R.first >= 2) { size_t Mid = (R.second + R.first) / 2; Q.push({R.first, Mid}); Q.push({Mid, R.second}); } } else { Printf("********* Success: [%zd, %zd)\n", R.first, R.second); std::ifstream IF(Temp); std::string L; while (std::getline(IF, L, '\n')) { // Data flow collection has succeeded. // Merge the results with the other runs. if (L.empty()) continue; if (L[0] == 'C') { // Take coverage lines as is, they will be the same in all attempts. Cov.insert(L); } else if (L[0] == 'F') { size_t FunctionNum = 0; std::string DFTString; if (ParseDFTLine(L, &FunctionNum, &DFTString)) { auto &DFT = DFTMap[FunctionNum]; if (DFT.empty()) { // Haven't seen this function before, take DFT as is. DFT = DFTStringToVector(DFTString); } else if (DFT.size() == DFTString.size()) { // Have seen this function already, merge DFTs. DFTStringAppendToVector(&DFT, DFTString); } } } } } } auto OutPath = DirPlusFile(DirPath, Hash(FileToVector(F.File))); // Dump combined DFT to disk. Printf("Producing DFT for %s\n", OutPath.c_str()); std::ofstream OF(OutPath); for (auto &DFT: DFTMap) OF << "F" << DFT.first << " " << DFT.second << std::endl; for (auto &C : Cov) OF << C << std::endl; } RemoveFile(Temp); // Write functions.txt. Command Cmd; Cmd.addArgument(DFTBinary); Cmd.setOutputFile(DirPlusFile(DirPath, "functions.txt")); ExecuteCommand(Cmd); return 0; }
Platform::Platform() { // Init directories. string path; CHECK(GetBinaryDir(path), ("Can't retrieve path to executable")); char const * homePath = ::getenv("HOME"); string const home(homePath ? homePath : ""); m_settingsDir = my::JoinFoldersToPath({home, ".config"}, "MapsWithMe"); if (!IsFileExistsByFullPath(my::JoinFoldersToPath(m_settingsDir, SETTINGS_FILE_NAME))) { MkDir(my::JoinFoldersToPath(home, ".config")); MkDir(m_settingsDir.c_str()); } m_writableDir = my::JoinFoldersToPath({home, ".local", "share"}, "MapsWithMe"); MkDir(my::JoinFoldersToPath(home, ".local")); MkDir(my::JoinFoldersToPath({home, ".local"}, "share")); MkDir(m_writableDir); char const * resDir = ::getenv("MWM_RESOURCES_DIR"); if (resDir) { m_resourcesDir = resDir; } else { string const devBuildWithSymlink = my::JoinFoldersToPath({path, "..", ".."}, "data"); string const devBuildWithoutSymlink = my::JoinFoldersToPath({path, "..", "..", "..", "omim"}, "data"); string const installedVersionWithPackages = my::JoinFoldersToPath({path, ".."}, "share"); string const installedVersionWithoutPackages = my::JoinFoldersToPath({path, ".."}, "MapsWithMe"); string const customInstall = path; if (IsEulaExist(devBuildWithSymlink)) { m_resourcesDir = devBuildWithSymlink; m_writableDir = m_resourcesDir; } else if (IsEulaExist(devBuildWithoutSymlink)) { m_resourcesDir = devBuildWithoutSymlink; m_writableDir = m_resourcesDir; } else if (IsEulaExist(installedVersionWithPackages)) { m_resourcesDir = installedVersionWithPackages; } else if (IsEulaExist(installedVersionWithoutPackages)) { m_resourcesDir = installedVersionWithoutPackages; } else if (IsEulaExist(customInstall)) { m_resourcesDir = path; } } m_resourcesDir += '/'; m_settingsDir += '/'; m_writableDir += '/'; char const * tmpDir = ::getenv("TMPDIR"); if (tmpDir) m_tmpDir = tmpDir; else m_tmpDir = "/tmp"; m_tmpDir += '/'; LOG(LDEBUG, ("Resources directory:", m_resourcesDir)); LOG(LDEBUG, ("Writable directory:", m_writableDir)); LOG(LDEBUG, ("Tmp directory:", m_tmpDir)); LOG(LDEBUG, ("Settings directory:", m_settingsDir)); LOG(LDEBUG, ("Client ID:", UniqueClientId())); }
CuSuite* DLL_CALLCONV CuGetFreeImageAlgorithmsDrawingSuite(void) { CuSuite* suite = CuSuiteNew(); MkDir(TEST_DATA_OUTPUT_DIR "/Drawing"); SUITE_ADD_TEST(suite, TestFIA_Index1PixelLineTest); //SUITE_ADD_TEST(suite, TestFIA_ColourTextTest); //SUITE_ADD_TEST(suite, TestFIA_GreyscaleTextTest); //SUITE_ADD_TEST(suite, TestFIA_ColourElipseTest); //SUITE_ADD_TEST(suite, TestFIA_Rect24bitTest); // SUITE_ADD_TEST(suite, TestFIA_Rect32bitTest); //SUITE_ADD_TEST(suite, TestFIA_GsRectTest); //SUITE_ADD_TEST(suite, TestFIA_SolidGSRectTest); //SUITE_ADD_TEST(suite, TestFIA_SolidRectTest); //SUITE_ADD_TEST(suite, TestFIA_ConvexHullTest); SUITE_ADD_TEST(suite, TestFIA_GreyscaleElipseTest); //SUITE_ADD_TEST(suite, TestFIA_GSLineTest); /* SUITE_ADD_TEST(suite, TestFIA_Colour24bitLineTest); SUITE_ADD_TEST(suite, TestFIA_Colour32bitLineTest); SUITE_ADD_TEST(suite, TestFIA_GSLineTest); SUITE_ADD_TEST(suite, TestFIA_GreyscaleU16bitElipseTest); SUITE_ADD_TEST(suite, TestFIA_GreyscaleElipseTest); SUITE_ADD_TEST(suite, TestFIA_ColourElipseTest); SUITE_ADD_TEST(suite, TestFIA_ConvexHullTest); SUITE_ADD_TEST(suite, TestFIA_GreyscalePolygonTest); SUITE_ADD_TEST(suite, TestFIA_ColourPolygonTest); SUITE_ADD_TEST(suite, TestFIA_ColourTextTest); SUITE_ADD_TEST(suite, TestFIA_GreyscaleTextTest); SUITE_ADD_TEST(suite, TestFIA_FloodFillTest); SUITE_ADD_TEST(suite, TestFIA_AffineTransorm32bitTest); SUITE_ADD_TEST(suite, TestFIA_AffineTransorm8bitTest); SUITE_ADD_TEST(suite, TestFIA_AffineTransorm32bitScaleTest); */ /* SUITE_ADD_TEST(suite, TestFIA_DrawImageTest1); SUITE_ADD_TEST(suite, TestFIA_DrawImageTest2); SUITE_ADD_TEST(suite, TestFIA_DrawImageTest3); SUITE_ADD_TEST(suite, TestFIA_DrawImageTest4); SUITE_ADD_TEST(suite, TestFIA_DrawImageTest5); SUITE_ADD_TEST(suite, TestFIA_DrawImageTest6); SUITE_ADD_TEST(suite, TestFIA_DrawImageTest7); SUITE_ADD_TEST(suite, TestFIA_DrawImageTest8); SUITE_ADD_TEST(suite, TestFIA_DrawImageTest9); SUITE_ADD_TEST(suite, TestFIA_DrawImageTest10); SUITE_ADD_TEST(suite, TestFIA_DrawImageTest11); SUITE_ADD_TEST(suite, TestFIA_DrawImageTest12); SUITE_ADD_TEST(suite, TestFIA_DrawImageTest13); SUITE_ADD_TEST(suite, TestFIA_DrawImageTest14); SUITE_ADD_TEST(suite, TestFIA_DrawImageDstRectTest1); SUITE_ADD_TEST(suite, TestFIA_DrawImageDstRectTest2); SUITE_ADD_TEST(suite, TestFIA_DrawImageDstRectTest3); SUITE_ADD_TEST(suite, TestFIA_DrawImageDstRectTest4); */ return suite; }
int main(int argc, char *argv[]) { int Pid; int c; int rvExist1=0, rvExist2=0; PGresult *result; char *NewDir="."; char *AgentName = "ununpack"; char *AgentARSName = "ununpack_ars"; char *agent_desc = "Unpacks archives (iso, tar, etc)"; int Recurse=0; int ars_pk = 0; int user_pk = 0; long Pfile_size = 0; char *ListOutName=NULL; char *Fname = NULL; char *FnameCheck = NULL; char *COMMIT_HASH; char *VERSION; char agent_rev[PATH_MAX]; struct stat Stat; /* connect to the scheduler */ fo_scheduler_connect(&argc, argv, &pgConn); while((c = getopt(argc,argv,"ACc:d:FfHhL:m:PQiqRr:T:t:U:VvXx")) != -1) { switch(c) { case 'A': SetContainerArtifact=0; break; case 'C': ForceContinue=1; break; case 'c': break; /* handled by fo_scheduler_connect() */ case 'd': /* if there is a %U in the path, substitute a unique ID */ NewDir=PathCheck(optarg); break; case 'F': UseRepository=1; break; case 'f': ForceDuplicate=1; break; case 'L': ListOutName=optarg; break; case 'm': MaxThread = atoi(optarg); if (MaxThread < 1) MaxThread=1; break; case 'P': PruneFiles=1; break; case 'R': Recurse=-1; break; case 'r': Recurse=atoi(optarg); break; case 'i': if (!IsExe("dpkg-source",Quiet)) LOG_WARNING("dpkg-source is not available on this system. This means that debian source packages will NOT be unpacked."); SafeExit(0); break; /* never reached */ case 'Q': UseRepository=1; user_pk = fo_scheduler_userID(); /* get user_pk for user who queued the agent */ /* Get the upload_pk from the scheduler */ if((Upload_Pk = fo_scheduler_next()) == NULL) SafeExit(0); break; case 'q': Quiet=1; break; case 'T': memset(REP_GOLD,0,sizeof(REP_GOLD)); strncpy(REP_GOLD,optarg,sizeof(REP_GOLD)-1); break; case 't': memset(REP_FILES,0,sizeof(REP_FILES)); strncpy(REP_FILES,optarg,sizeof(REP_FILES)-1); break; case 'U': UseRepository = 1; Recurse = -1; Upload_Pk = optarg; break; case 'V': printf("%s", BuildVersion);SafeExit(0); case 'v': Verbose++; break; case 'X': UnlinkSource=1; break; case 'x': UnlinkAll=1; break; default: Usage(argv[0], BuildVersion); SafeExit(25); } } /* Open DB and Initialize CMD table */ if (UseRepository) { /* Check Permissions */ if (GetUploadPerm(pgConn, atoi(Upload_Pk), user_pk) < PERM_WRITE) { LOG_ERROR("You have no update permissions on upload %s", Upload_Pk); SafeExit(100); } COMMIT_HASH = fo_sysconfig(AgentName, "COMMIT_HASH"); VERSION = fo_sysconfig(AgentName, "VERSION"); sprintf(agent_rev, "%s.%s", VERSION, COMMIT_HASH); /* Get the unpack agent key */ agent_pk = fo_GetAgentKey(pgConn, AgentName, atoi(Upload_Pk), agent_rev,agent_desc); InitCmd(); /* Make sure ars table exists */ if (!fo_CreateARSTable(pgConn, AgentARSName)) SafeExit(0); /* Has this user previously unpacked this upload_pk successfully? * In this case we are done. No new ars record is needed since no * processing is initiated. * The unpack version is ignored. */ snprintf(SQL,MAXSQL, "SELECT ars_pk from %s where upload_fk='%s' and ars_success=TRUE", AgentARSName, Upload_Pk); result = PQexec(pgConn, SQL); if (fo_checkPQresult(pgConn, result, SQL, __FILE__, __LINE__)) SafeExit(101); if (PQntuples(result) > 0) /* if there is a value */ { PQclear(result); LOG_WARNING("Upload_pk %s, has already been unpacked. No further action required", Upload_Pk) SafeExit(0); } PQclear(result); /* write the unpack_ars start record */ ars_pk = fo_WriteARS(pgConn, ars_pk, atoi(Upload_Pk), agent_pk, AgentARSName, 0, 0); /* Get Pfile path and Pfile_Pk, from Upload_Pk */ snprintf(SQL,MAXSQL, "SELECT pfile.pfile_sha1 || '.' || pfile.pfile_md5 || '.' || pfile.pfile_size AS pfile, pfile_fk, pfile_size FROM upload INNER JOIN pfile ON upload.pfile_fk = pfile.pfile_pk WHERE upload.upload_pk = '%s'", Upload_Pk); result = PQexec(pgConn, SQL); if (fo_checkPQresult(pgConn, result, SQL, __FILE__, __LINE__)) SafeExit(102); if (PQntuples(result) > 0) /* if there is a value */ { Pfile = strdup(PQgetvalue(result,0,0)); Pfile_Pk = strdup(PQgetvalue(result,0,1)); Pfile_size = atol(PQgetvalue(result, 0, 2)); if (Pfile_size == 0) { PQclear(result); LOG_WARNING("Uploaded file (Upload_pk %s), is zero length. There is nothing to unpack.", Upload_Pk) SafeExit(0); } PQclear(result); } // Determine if uploadtree records should go into a separate table. // If the input file size is > 500MB, then create a separate uploadtree_{upload_pk} table // that inherits from the master uploadtree table. // Save uploadtree_tablename, it will get written to upload.uploadtree_tablename later. if (Pfile_size > 500000000) { sprintf(uploadtree_tablename, "uploadtree_%s", Upload_Pk); if (!fo_tableExists(pgConn, uploadtree_tablename)) { snprintf(SQL,MAXSQL,"CREATE TABLE %s (LIKE uploadtree INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING INDEXES); ALTER TABLE %s ADD CONSTRAINT %s CHECK (upload_fk=%s); ALTER TABLE %s INHERIT uploadtree", uploadtree_tablename, uploadtree_tablename, uploadtree_tablename, Upload_Pk, uploadtree_tablename); PQsetNoticeProcessor(pgConn, SQLNoticeProcessor, SQL); // ignore notice about implicit primary key index creation result = PQexec(pgConn, SQL); // Ignore postgres notice about creating an implicit index if (PQresultStatus(result) != PGRES_NONFATAL_ERROR) if (fo_checkPQcommand(pgConn, result, SQL, __FILE__, __LINE__)) SafeExit(103); PQclear(result); } } else strcpy(uploadtree_tablename, "uploadtree_a"); } CheckCommands(Quiet); if (NewDir) MkDir(NewDir); if (Verbose) { fclose(stderr) ; stderr=stdout; } /* don't interlace! */ if (ListOutName != NULL) { if ((ListOutName[0]=='-') && (ListOutName[1]=='\0')) ListOutFile=stdout; else ListOutFile = fopen(ListOutName,"w"); if (!ListOutFile) { LOG_ERROR("pfile %s Unable to write to %s\n",Pfile_Pk,ListOutName) SafeExit(104); } else { /* Start the file */ fputs("<xml tool=\"ununpack\" ",ListOutFile); fputs("version=\"",ListOutFile); fputs(Version,ListOutFile); fputs("\" ",ListOutFile); fputs("compiled_date=\"",ListOutFile); fputs(__DATE__,ListOutFile); fputs(" ",ListOutFile); fputs(__TIME__,ListOutFile); fputs("\"",ListOutFile); fputs(">\n",ListOutFile); } /* Problem: When parallel processing, the XML may be generated out of order. Solution? When using XML, only use 1 thread. */ MaxThread=1; } // Set ReunpackSwitch if the uploadtree records are missing from the database. if (!ReunpackSwitch && UseRepository) { snprintf(SQL,MAXSQL,"SELECT uploadtree_pk FROM uploadtree WHERE upload_fk=%s limit 1;",Upload_Pk); result = PQexec(pgConn, SQL); if (fo_checkPQresult(pgConn, result, SQL, __FILE__, __LINE__)) SafeExit(105); if (PQntuples(result) == 0) ReunpackSwitch=1; PQclear(result); } /*** process files from command line ***/ for( ; optind<argc; optind++) { CksumFile *CF=NULL; Cksum *Sum; int i; if (Fname) { free(Fname); Fname=NULL; } if (ListOutName != NULL) { fprintf(ListOutFile,"<source source=\"%s\" ",argv[optind]); if (UseRepository && !fo_RepExist(REP_FILES,argv[optind])) { /* make sure the source exists in the src repository */ if (fo_RepImport(argv[optind],REP_FILES,argv[optind],1) != 0) { LOG_ERROR("Failed to import '%s' as '%s' into the repository",argv[optind],argv[optind]) SafeExit(106); } } } if (UseRepository) { if (fo_RepExist(REP_FILES,argv[optind])) { Fname=fo_RepMkPath(REP_FILES,argv[optind]); } else if (fo_RepExist(REP_GOLD,argv[optind])) { Fname=fo_RepMkPath(REP_GOLD,argv[optind]); if (fo_RepImport(Fname,REP_FILES,argv[optind],1) != 0) { LOG_ERROR("Failed to import '%s' as '%s' into the repository",Fname,argv[optind]) SafeExit(107); } } if (Fname) { FnameCheck = Fname; CF = SumOpenFile(Fname); } else { LOG_ERROR("NO file unpacked. File %s does not exist either in GOLD or FILES", Pfile); SafeExit(108); } /* else: Fname is NULL and CF is NULL */ } else { FnameCheck = argv[optind]; CF = SumOpenFile(argv[optind]); } /* Check file to unpack. Does it exist? Is it zero length? */ if (stat(FnameCheck,&Stat)) { LOG_ERROR("File to unpack is unavailable: %s, error: %s", Fname, strerror(errno)); SafeExit(109); } else if (Stat.st_size < 1) { LOG_WARNING("File to unpack is empty: %s", Fname); SafeExit(110); } if (ListOutFile) { if (CF) { Sum = SumComputeBuff(CF); SumCloseFile(CF); if (Sum) { fputs("fuid=\"",ListOutFile); for(i=0; i<20; i++) { fprintf(ListOutFile,"%02X",Sum->SHA1digest[i]); } fputs(".",ListOutFile); for(i=0; i<16; i++) { fprintf(ListOutFile,"%02X",Sum->MD5digest[i]); } fputs(".",ListOutFile); fprintf(ListOutFile,"%Lu",(long long unsigned int)Sum->DataLen); fputs("\" ",ListOutFile); free(Sum); } /* if Sum */ } /* if CF */ else /* file too large to mmap (probably) */ { FILE *Fin; Fin = fopen(argv[optind],"rb"); if (Fin) { Sum = SumComputeFile(Fin); if (Sum) { fputs("fuid=\"",ListOutFile); for(i=0; i<20; i++) { fprintf(ListOutFile,"%02X",Sum->SHA1digest[i]); } fputs(".",ListOutFile); for(i=0; i<16; i++) { fprintf(ListOutFile,"%02X",Sum->MD5digest[i]); } fputs(".",ListOutFile); fprintf(ListOutFile,"%Lu",(long long unsigned int)Sum->DataLen); fputs("\" ",ListOutFile); free(Sum); } fclose(Fin); } } /* else no CF */ fprintf(ListOutFile,">\n"); /* end source XML */ } if (Fname) TraverseStart(Fname,"called by main via args",NewDir,Recurse); else TraverseStart(argv[optind],"called by main",NewDir,Recurse); if (ListOutName != NULL) fprintf(ListOutFile,"</source>\n"); } /* end for */ /* free memory */ if (Fname) { free(Fname); Fname=NULL; } /* process pfile from scheduler */ if (Pfile) { if (0 == (rvExist1 = fo_RepExist2(REP_FILES,Pfile))) { Fname=fo_RepMkPath(REP_FILES,Pfile); } else if (0 == (rvExist2 = fo_RepExist2(REP_GOLD,Pfile))) { Fname=fo_RepMkPath(REP_GOLD,Pfile); if (fo_RepImport(Fname,REP_FILES,Pfile,1) != 0) { LOG_ERROR("Failed to import '%s' as '%s' into the repository",Fname,Pfile) SafeExit(111); } } if (Fname) { TraverseStart(Fname,"called by main via env",NewDir,Recurse); free(Fname); Fname=NULL; } else { LOG_ERROR("NO file unpacked!"); if (rvExist1 > 0) { Fname=fo_RepMkPath(REP_FILES, Pfile); LOG_ERROR("Error is %s for %s", strerror(rvExist1), Fname); } if (rvExist2 > 0) { Fname=fo_RepMkPath(REP_GOLD, Pfile); LOG_ERROR("Error is %s for %s", strerror(rvExist2), Fname); } SafeExit(112); } } /* recurse on all the children */ if (Thread > 0) do { Pid = ParentWait(); Thread--; if (Pid >= 0) { if (!Queue[Pid].ChildEnd) { /* copy over data */ if (Recurse > 0) Traverse(Queue[Pid].ChildRecurse,NULL,"called by wait",NULL,Recurse-1,&Queue[Pid].PI); else if (Recurse < 0) Traverse(Queue[Pid].ChildRecurse,NULL,"called by wait",NULL,Recurse,&Queue[Pid].PI); } } } while(Pid >= 0); if (MagicCookie) magic_close(MagicCookie); if (ListOutFile) { fprintf(ListOutFile,"<summary files_regular=\"%d\" files_compressed=\"%d\" artifacts=\"%d\" directories=\"%d\" containers=\"%d\" />\n", TotalFiles,TotalCompressedFiles,TotalArtifacts, TotalDirectories,TotalContainers); fputs("</xml>\n",ListOutFile); } if (pgConn) { /* If it completes, mark it! */ if (Upload_Pk) { snprintf(SQL,MAXSQL,"UPDATE upload SET upload_mode = (upload_mode | (1<<5)), uploadtree_tablename='%s' WHERE upload_pk = '%s';",uploadtree_tablename, Upload_Pk); result = PQexec(pgConn, SQL); /* UPDATE upload */ if (fo_checkPQcommand(pgConn, result, SQL, __FILE__ ,__LINE__)) SafeExit(113); PQclear(result); snprintf(SQL,MAXSQL,"UPDATE %s SET realparent = getItemParent(uploadtree_pk) WHERE upload_fk = '%s'",uploadtree_tablename, Upload_Pk); result = PQexec(pgConn, SQL); /* UPDATE uploadtree */ if (fo_checkPQcommand(pgConn, result, SQL, __FILE__ ,__LINE__)) SafeExit(114); PQclear(result); } if (ars_pk) fo_WriteARS(pgConn, ars_pk, atoi(Upload_Pk), agent_pk, AgentARSName, 0, 1); } if (ListOutFile && (ListOutFile != stdout)) { fclose(ListOutFile); } if (UnlinkAll && MaxThread > 1) { /* Delete temporary files */ if (strcmp(NewDir, ".")) RemoveDir(NewDir); } SafeExit(0); return(0); // never executed but makes the compiler happy }
/*************************************************** ExtractAR(): Given an AR file, extract the contents to the directory. Returns: 0 on success, non-zero on failure. NOTE: This spawns multiple processes. Uses the following external commands: ar NOTE: Things that are known to cause failures: - Absolute paths in ar files - Same file name listed twice in the archive ***************************************************/ int ExtractAR (char *Source, char *Destination) { char Cmd[FILENAME_MAX*4]; /* command to run */ char Line[FILENAME_MAX]; char *s; /* generic string pointer */ FILE *Fin; int rc; char TempSource[FILENAME_MAX]; char CWD[FILENAME_MAX]; /* judge if the parameters are empty */ if ((NULL == Source) || (!strcmp(Source, "")) || (NULL == Destination) || (!strcmp(Destination, ""))) return 1; if (getcwd(CWD,sizeof(CWD)) == NULL) { fprintf(stderr,"ERROR: directory name longer than %d characters\n",(int)sizeof(CWD)); return(-1); } if (Verbose > 1) printf("CWD: %s\n",CWD); if (!Quiet && (Verbose > 1)) fprintf(stderr,"Extracting ar: %s\n",Source); chdir(Destination); if (TaintString(TempSource,FILENAME_MAX,Source,1,NULL)) return(-1); memset(Cmd,'\0',sizeof(Cmd)); /* get list of directories and make the directories */ /* Cmd: ar t %s 2>/dev/null | grep '^Directory' */ if (TempSource[0] != '/') snprintf(Cmd,sizeof(Cmd)," (ar t '%s/%s') 2>/dev/null",CWD,TempSource); else snprintf(Cmd,sizeof(Cmd)," (ar t '%s') 2>/dev/null",TempSource); Fin = popen(Cmd,"r"); if (!Fin) { fprintf(stderr,"ERROR: ar failed: %s\n",Cmd); chdir(CWD); return(-1); } while(ReadLine(Fin,Line,sizeof(Line)-1) >= 0) { /* each line is a file. Check for directories. */ if (Line[0]=='/') { pclose(Fin); return(1); } /* NO ABSOLUTE PATHS! */ s=strrchr(Line,'/'); /* find the last slash */ if (s == NULL) continue; s[0]='\0'; if (MkDir(Line)) { fprintf(stderr,"ERROR: Unable to mkdir(%s) in ExtractAR\n",Line); if (!ForceContinue) exit(-1); } } pclose(Fin); /* Now let's extract each file */ if (TempSource[0] != '/') snprintf(Cmd,sizeof(Cmd)," (ar x '%s/%s') 2>/dev/null",CWD,TempSource); else snprintf(Cmd,sizeof(Cmd)," (ar x '%s') 2>/dev/null",TempSource); rc = WEXITSTATUS(system(Cmd)); if (rc) { fprintf(stderr,"ERROR: Command failed (rc=%d): %s\n",rc,Cmd); } /* All done */ chdir(CWD); return(rc); } /* ExtractAR() */
Bool Cd(U8 *dirname,Bool make_dirs=FALSE) {//Optionally, will create the directories if they don't exist. I64 maxlen,cur_dir_cluster=0; U8 *chg_to_buf,*new_cur_dir,*buf; CPrt *p; Bool result=TRUE; if (!*dirname) return TRUE; if (dirname[1]==':') { if (*dirname==':') { if (Fs->cur_prt->drv_let!=*sys_acct) if (!Drv(*dirname)) return FALSE; } else { if (Fs->cur_prt!= Drv2Prt(*dirname)) if (!Drv(*dirname)) return FALSE; } dirname+=2; } if (*dirname=='/' || !*dirname || !Fs->cur_dir) { Free(Fs->cur_dir); Fs->cur_dir=StrNew("/"); if (*dirname=='/') dirname++; } chg_to_buf=MStrUtil(dirname, SUF_REM_LEADING|SUF_REM_TRAILING|SUF_REM_CTRL_CHARS); maxlen=StrLen(Fs->cur_dir)+1+StrLen(chg_to_buf)+1; new_cur_dir=MAlloc(maxlen); buf=MAlloc(maxlen); StrCpy(new_cur_dir,Fs->cur_dir); while (*chg_to_buf && result) { StrFirstRem(chg_to_buf,"/",buf); if (!*buf) StrCpy(new_cur_dir,"/"); else if (!StrCmp(buf,"..")) { StrLastRem(new_cur_dir,"/"); if (!*new_cur_dir) StrCpy(new_cur_dir,"/"); } else if (!StrCmp(buf,".")) { ; } else if (*buf) { if (!StrCmp(buf,"HOME")) { result=Cd(sys_acct); Free(new_cur_dir); new_cur_dir=MAlloc(maxlen+StrLen(sys_acct)); StrCpy(new_cur_dir,sys_acct+2); } else { p=Fs->cur_prt; cur_dir_cluster=Name2DirCluster(p,new_cur_dir); switch (p->type) { case PT_REDSEA: result=RedSeaFSCd(buf,cur_dir_cluster); break; case PT_FAT32: result=FAT32Cd(buf,cur_dir_cluster); break; case PT_ISO9660: result=ISO1Cd(buf,cur_dir_cluster); break; default: PutDefineErr("ST_UNSUPPORTED_FILE_SYSTEM"); result=FALSE; } if (!result && make_dirs) { Free(Fs->cur_dir); Fs->cur_dir=StrNew(new_cur_dir); result=MkDir(buf); } if (result) { if (StrCmp(new_cur_dir,"/")) StrCat(new_cur_dir,"/"); StrCat(new_cur_dir,buf); } } } } Free(Fs->cur_dir); Fs->cur_dir=StrNew(new_cur_dir); Free(buf); Free(chg_to_buf); Free(new_cur_dir); return result; }
int main() { // Set up for the tests fprintf(stderr, "Set up for the read tests\n"); int fd, ret, i, j; char buf[SIZE + 1], ref[SIZE], zero[SIZE], fff[SIZE]; struct Stat mystat; // Fill buf with 'A' and ref with 'B' for(i = 0 ; i < SIZE ; i++) { buf[i] = 'A'; ref[i] = 'B'; // used later zero[i] = '\0'; //used later fff[i] = 'F'; //used later } fd = Create("a"); for(i = 0 ; i < 5 ; i++) { // Indirect block write for(j = 0 ; j < SIZE ; j++) buf[j]++; ret = Write(fd, buf, SIZE); assert("Write position not advancing correctly in indirect block writes\n", ret == SIZE); } // Seeking to the end of those 5 blocks, skipping a block, and then writing another block ret = Seek(fd, 0, SEEK_END); assert("Seek end not working correctly\n", ret == SIZE * 5); ret = Seek(fd, SIZE, SEEK_CUR); assert("Seek not allowed to seek past end of file?\n", ret == SIZE * 6); ret = Write(fd, buf, SIZE); assert("Write position not advancing correctly after seeking past end of file\n", ret == SIZE); ret = Seek(fd, 0, SEEK_END); assert("Seek set not working correctly after skipping\n", ret == SIZE * 7); ret = Seek(fd, 0, SEEK_SET); assert("Seek set not working correctly\n", ret == 0); ret = Seek(fd, -1, SEEK_SET); assert("Seek set allowed to seek before beginning of file\n", ret == ERROR); ret = Seek(fd, -1, SEEK_CUR); assert("Seek cur allowed to seek before beginning of file\n", ret == ERROR); Close(fd); // Test stat of a fprintf(stderr, "Test stat of a\n"); fd = Stat("a", &mystat); fprintf(stderr, "Stat a: [%d], inode=%d, type=%d, size=%d, nlink=%d\n", fd, mystat.inum, mystat.type, mystat.size, mystat.nlink); assert("Stats failed on a", fd == 0 && mystat.inum == 2 && mystat.type == 2 && mystat.size == SIZE * 7 && mystat.nlink == 1); // Begin read tests on a file fprintf(stderr, "Begin read tests on a file\n"); fd = Open("a"); ret = Read(fd, buf, 16); assert("Read wrong number of bytes: BBB\n", ret == 16); buf[16] = 0; assert("Failed read on file: BBB\n", strncmp(buf, "BBBBBBBBBBBBBBBB", 16) == 0); ret = Seek(fd, SIZE, SEEK_SET); ret = Read(fd, buf, 16); assert("Read wrong number of bytes: CCC\n", ret == 16); buf[16] = 0; assert("Failed read on file: CCC\n", strncmp(buf, "CCCCCCCCCCCCCCCC", 16) == 0); ret = Seek(fd, SIZE * 2, SEEK_SET); ret = Read(fd, buf, 16); assert("Read wrong number of bytes: DDD\n", ret == 16); buf[16] = 0; assert("Failed read on file: DDD\n", strncmp(buf, "DDDDDDDDDDDDDDDD", 16) == 0); ret = Seek(fd, 0, SEEK_SET); ret = Read(fd, buf, SIZE); assert("Read wrong number of bytes: BBB\n", ret == SIZE); assert("Failed read on file: ref\n", strncmp(buf, ref, SIZE) == 0); // Here we're attempting to read the '\0' gap block in the 6th block ret = Seek(fd, SIZE * -2, SEEK_END); assert("Seeking to wrong place in file: 000\n", ret == SIZE * 5); ret = Read(fd, buf, SIZE); assert("Read wrong number of bytes: 000\n", ret == SIZE); assert("Failed read on file: 000\n", strncmp(buf, zero, SIZE) == 0); // And then we attempt to read the FFF which should be in the 7th block, right past the gap block ret = Read(fd, buf, SIZE); assert("Read wrong number of bytes: FFF\n", ret == SIZE); assert("Failed read on file: FFF\n", strncmp(buf, fff, SIZE) == 0); ret = Seek(fd, 0, SEEK_END); ret = Read(fd, buf, SIZE); assert("Read wrong number of bytes: seek end\n", ret == 0); Close(fd); // Test Reading and writing on directories fprintf(stderr, "Test Reading and writing on directories\n"); fd = Open("."); ret = Read(fd, buf, 16); assert("Read wrong number of bytes: . dir\n", ret == 16); //TODO: idk what this should actually return ret = Write(fd, buf, 16); assert("Wrote to directory\n", ret == ERROR); Close(fd); fd = Open("/"); ret = Read(fd, buf, 16); assert("Read wrong number of bytes: / dir\n", ret == 16); //TODO: idk what this should actually return ret = Write(fd, buf, 16); assert("Wrote to directory\n", ret == ERROR); Close(fd); // Null tests fprintf(stderr, "null tests\n"); fd = Open(NULL); assert("Opened null file\n", fd == ERROR); ret = Read(fd, buf, 16); assert("Read null file\n", ret == ERROR); ret = Write(fd, buf, 16); assert("Wrote null file\n", ret == ERROR); fd = Stat(NULL, &mystat); assert("Stats on null", fd == ERROR); fd = Stat("a", NULL); assert("Stats with null stat struct", fd == ERROR); // Test more stat things fprintf(stderr, "Test more stat things\n"); fd = Create("b"); for(j = 0 ; j < SIZE ; j++) buf[j]++; ret = Write(fd, buf, 16); Close(fd); fd = Stat("b", &mystat); assert("Stats failed on b", fd == 0 && mystat.inum == 3 && mystat.type == 2 && mystat.size == 16 && mystat.nlink == 1); fd = MkDir("c"); fd = Stat("c", &mystat); assert("Stats failed on c", fd == 0 && mystat.inum == 4 && mystat.type == 1 && mystat.size == 64 && mystat.nlink == 2); fd = MkDir("c/d"); fd = Stat("c/d", &mystat); assert("Stats failed on c/d", fd == 0 && mystat.inum == 5 && mystat.type == 1 && mystat.size == 64 && mystat.nlink == 2); fd = Stat("f", &mystat); assert("Stats failed on f", fd == ERROR); fd = Sync(); assert("Sync failed", fd == 0); Delay(3); // TODO test stat on links? printf("All tests passed\n"); return Shutdown(); }
/////////////////////////////////////////////////////////////// // // DoInstallFiles // // Copy directory tree at current dirctory to GetMTASAPath () // /////////////////////////////////////////////////////////////// bool DoInstallFiles ( void ) { SString strCurrentDir = PathConform ( GetSystemCurrentDirectory () ); const SString strMTASAPath = PathConform ( GetMTASAPath () ); SString path1, path2; strCurrentDir.Split ( "\\", &path1, &path2, -1 ); SString strDestRoot = strMTASAPath; SString strSrcRoot = strCurrentDir; SString strBakRoot = MakeUniquePath ( strCurrentDir + "_bak_" ); // Clean backup dir if ( !MkDir ( strBakRoot ) ) { AddReportLog ( 5020, SString ( "InstallFiles: Couldn't make dir '%s'", strBakRoot.c_str () ) ); return false; } // Get list of files to install std::vector < SFileItem > itemList; { std::vector < SString > fileList; FindFilesRecursive ( PathJoin ( strCurrentDir, "*" ), fileList ); for ( unsigned int i = 0 ; i < fileList.size () ; i++ ) { SFileItem item; item.strSrcPathFilename = PathConform ( fileList[i] ); item.strDestPathFilename = PathConform ( fileList[i].Replace ( strSrcRoot, strDestRoot ) ); item.strBackupPathFilename = PathConform ( fileList[i].Replace ( strSrcRoot, strBakRoot ) ); itemList.push_back ( item ); } } // See if any files to be updated are running. // If so, terminate them for ( unsigned int i = 0 ; i < itemList.size () ; i++ ) { SString strFile = itemList[i].strDestPathFilename; if ( strFile.EndsWithI( ".exe" ) ) TerminateProcessFromPathFilename ( strFile ); } // Copy current(old) files into backup location for ( unsigned int i = 0 ; i < itemList.size () ; i++ ) { const SFileItem& item = itemList[i]; if ( !FileCopy ( item.strDestPathFilename, item.strBackupPathFilename ) ) { if ( FileExists ( item.strDestPathFilename ) ) { AddReportLog ( 5021, SString ( "InstallFiles: Couldn't backup '%s' to '%s'", *item.strDestPathFilename, *item.strBackupPathFilename ) ); return false; } AddReportLog ( 4023, SString ( "InstallFiles: Couldn't backup '%s' as it does not exist", *item.strDestPathFilename ) ); } } // Try copy new files bool bOk = true; std::vector < SFileItem > fileListSuccess; for ( unsigned int i = 0 ; i < itemList.size () ; i++ ) { const SFileItem& item = itemList[i]; if ( !FileCopy ( item.strSrcPathFilename, item.strDestPathFilename ) ) { // If copy failed, check if we really need to copy the file if ( GenerateSha256HexStringFromFile( item.strSrcPathFilename ) != GenerateSha256HexStringFromFile( item.strDestPathFilename ) ) { AddReportLog ( 5022, SString ( "InstallFiles: Couldn't copy '%s' to '%s'", *item.strSrcPathFilename, *item.strDestPathFilename ) ); bOk = false; break; } } fileListSuccess.push_back ( item ); } // If fail, copy back old files if ( !bOk ) { bool bPossibleDisaster = false; for ( unsigned int i = 0 ; i < fileListSuccess.size () ; i++ ) { const SFileItem& item = fileListSuccess[i]; int iRetryCount = 3; while ( true ) { if ( FileCopy ( item.strBackupPathFilename, item.strDestPathFilename ) ) break; // If copy failed, check if we really need to copy the file if ( GenerateSha256HexStringFromFile( item.strBackupPathFilename ) != GenerateSha256HexStringFromFile( item.strDestPathFilename ) ) break; if ( !--iRetryCount ) { AddReportLog ( 5023, SString ( "InstallFiles: Possible disaster restoring '%s' to '%s'", *item.strBackupPathFilename, *item.strDestPathFilename ) ); bPossibleDisaster = true; break; } } } //if ( bPossibleDisaster ) // MessageBox ( NULL, _("Installation may be corrupt. Please redownload from www.mtasa.com"), _("Error"), MB_OK | MB_ICONERROR ); //else // MessageBox ( NULL, _("Could not update due to file conflicts."), _("Error"), MB_OK | MB_ICONERROR ); } // Launch MTA_EXE_NAME return bOk; }