Exemplo n.º 1
0
bool RemoveFile(const string& path, bool recurse)
{
    if (!IsDir(path))
	return RemoveFile(path);

    if (!recurse)
	return RemoveDir(path);

    vector<string> filenames;

    if (GetDirEntries(path, filenames))
    {
	string save_cwd;
	GetCwd(save_cwd);

	if (!ChangeDir(path))
	    return false;

	for (size_t i = 0; i < filenames.size(); i++)
	    RemoveFile(filenames[i], true);

	if (!ChangeDir(save_cwd))
	    return false;
    }

    return RemoveDir(path);
}
Exemplo n.º 2
0
UINT __stdcall UninstallBranding(MSIHANDLE hModule)
{
    UINT rc;
    logStringW(hModule, L"UninstallBranding: Handling branding file ...");

    WCHAR wszPathTargetDir[_MAX_PATH];
    WCHAR wszPathDest[_MAX_PATH];

    rc = VBoxGetProperty(hModule, L"CustomActionData", wszPathTargetDir, sizeof(wszPathTargetDir));
    if (rc == ERROR_SUCCESS)
    {
        /** @todo Check trailing slash after %s. */
/** @todo r=bird: using swprintf_s for formatting paths without checking for
 * overflow not good.  You're dodging the buffer overflow issue only to end up
 * with incorrect behavior!  (Truncated file/dir names)
 *
 * This applies almost to all swprintf_s calls in this file!!
 */
        swprintf_s(wszPathDest, RT_ELEMENTS(wszPathDest), L"%scustom", wszPathTargetDir);
        rc = RemoveDir(hModule, wszPathDest);
        if (rc != ERROR_SUCCESS)
        {
            /* Check for hidden .custom directory and remove it. */
            swprintf_s(wszPathDest, RT_ELEMENTS(wszPathDest), L"%s.custom", wszPathTargetDir);
            rc = RemoveDir(hModule, wszPathDest);
        }
    }

    logStringW(hModule, L"UninstallBranding: Handling done. (rc=%u (ignored))", rc);
    return ERROR_SUCCESS; /* Do not fail here. */
}
void TearDown()
{
    RemoveDir(testDataDir);
    RemoveDir(testPrintDataDir);
    
    testDataDir = "";
    testPrintDataDir = "";
}
Exemplo n.º 4
0
 void TearDown()
 {
     SETTINGS.Restore(STAGING_DIR);
     SETTINGS.Restore(DOWNLOAD_DIR);
     SETTINGS.Restore(PRINT_DATA_DIR);
     
     RemoveDir(testStagingDir);
     RemoveDir(testDownloadDir);
     RemoveDir(testPrintDataDir);
     
     testStagingDir = "";
     testDownloadDir = "";
     testPrintDataDir = "";
 }
Exemplo n.º 5
0
/**
 * \brief for function IsFile
 * a file
 */
void testIsFileNormal_SymLink()
{
  system("echo 'hello world' > ./test.file");
  char Fname[] = "./test.file";
  int isFile = IsFile(Fname, 0);
  CU_ASSERT_EQUAL(isFile, 1);
  char NewFname[] = "./link.file";
  symlink(Fname, NewFname);
  isFile = IsFile(NewFname, 1);
  CU_ASSERT_EQUAL(isFile, 1);
#if 0
#endif
  RemoveDir(Fname);
  RemoveDir(NewFname);
}
Exemplo n.º 6
0
bool
MoonInstallerService::Uninstall (Deployment *deployment)
{
	LOG_OOB ("MoonInstallerService::Uninstall ()\n");
	const char *base_dir = GetBaseInstallDir ();
	MoonAppRecord *app;
	char *install_dir;
	
	// get the application record
	if (!(app = GetAppRecord (deployment)))
		return false;
	
	if (!db->RemoveAppRecord (app)) {
		// oops, we failed to remove it from our database of installed apps.
		delete app;
		return false;
	}
	
	// now we can uninstall the application by removing its install directory
	install_dir = g_build_filename (base_dir, app->uid, NULL);
	RemoveDir (install_dir);
	g_free (install_dir);
	delete app;
	
	return true;
}
Exemplo n.º 7
0
int CFileZillaEngine::Execute(const CCommand &command)
{
	if (command.GetId() != Command::cancel && IsBusy())
		return FZ_REPLY_BUSY;

	m_bIsInCommand = true;

	int res = FZ_REPLY_INTERNALERROR;
	switch (command.GetId())
	{
	case Command::connect:
		res = Connect(reinterpret_cast<const CConnectCommand &>(command));
		break;
	case Command::disconnect:
		res = Disconnect(reinterpret_cast<const CDisconnectCommand &>(command));
		break;
	case Command::cancel:
		res = Cancel(reinterpret_cast<const CCancelCommand &>(command));
		break;
	case Command::list:
		res = List(reinterpret_cast<const CListCommand &>(command));
		break;
	case Command::transfer:
		res = FileTransfer(reinterpret_cast<const CFileTransferCommand &>(command));
		break;
	case Command::raw:
		res = RawCommand(reinterpret_cast<const CRawCommand&>(command));
		break;
	case Command::del:
		res = Delete(reinterpret_cast<const CDeleteCommand&>(command));
		break;
	case Command::removedir:
		res = RemoveDir(reinterpret_cast<const CRemoveDirCommand&>(command));
		break;
	case Command::mkdir:
		res = Mkdir(reinterpret_cast<const CMkdirCommand&>(command));
		break;
	case Command::rename:
		res = Rename(reinterpret_cast<const CRenameCommand&>(command));
		break;
	case Command::chmod:
		res = Chmod(reinterpret_cast<const CChmodCommand&>(command));
		break;
	default:
		return FZ_REPLY_SYNTAXERROR;
	}

	if (res != FZ_REPLY_WOULDBLOCK)
		ResetOperation(res);

	m_bIsInCommand = false;

	if (command.GetId() != Command::disconnect)
		res |= m_nControlSocketError;
	else if (res & FZ_REPLY_DISCONNECTED)
		res = FZ_REPLY_OK;
	m_nControlSocketError = 0;

	return res;
}
Exemplo n.º 8
0
void RemoveDir(const char* oldPath)
{
    char *fullOldPath;
    SceIoDirent oneDir;
    int oDir = sceIoDopen(oldPath);
    if (oDir < 0){
        return;
    }
    while (1){
        memset(&oneDir, 0, sizeof(SceIoDirent));
        if (sceIoDread(oDir, &oneDir) <= 0)
            break;
        if (!strcmp(oneDir.d_name, ".") || !strcmp(oneDir.d_name, ".."))
            continue;
        if (oldPath[strlen(oldPath)-1] != '/'){
            fullOldPath = (char *)calloc(strlen(oldPath)+strlen(oneDir.d_name)+2,sizeof(char));
            sprintf(fullOldPath,"%s/%s",oldPath,oneDir.d_name);
        } else {
            fullOldPath = (char *)calloc(strlen(oldPath)+strlen(oneDir.d_name)+1,sizeof(char));
            sprintf(fullOldPath,"%s%s",oldPath,oneDir.d_name);
        }
        if (FIO_S_ISDIR(oneDir.d_stat.st_mode)){
            RemoveDir(fullOldPath);
        } else if(FIO_S_ISREG(oneDir.d_stat.st_mode)){
            sceIoRemove(fullOldPath);
        }
        free(fullOldPath);
    }
    sceIoDclose(oDir);
    sceIoRmdir(oldPath);
}
Exemplo n.º 9
0
acoral_32 acoral_rmdir(const acoral_char *pathname)
{
	acoral_u32 ret;
	acoral_u8 fs_ret,len;
	acoral_char *path;
	len=acoral_str_len(pathname);
	if(path=(acoral_char *)acoral_malloc2(len+1))
	{
		acoral_str_cpy(path,pathname);
		path[len]=0;
	}
	else
		return -1;
	ret=acoral_mutex_pend(fs_mutex,0);
	if(ret!=MUTEX_SUCCED)
	{
		acoral_free2(path);
		return -1;
	}
	fs_ret=RemoveDir(path);
	acoral_mutex_post(fs_mutex);
	acoral_free2(path);
	if(fs_ret!=RETURN_OK)
		return -1;
	return 0;
}
Exemplo n.º 10
0
/**
 * \brief for function IsFile 
 * a file
 */
void testIsFileNormal_RegulerFile()
{
  system("echo 'hello world' > ./test.file");
  char Fname[] = "./test.file";
  int isFile = IsFile(Fname, 1);
  CU_ASSERT_EQUAL(isFile, 1);
  RemoveDir(Fname);
}
Exemplo n.º 11
0
static int lua_removeDir(lua_State *L)
{
    const char *path = luaL_checkstring(L, 1);
    if(!path) return luaL_error(L, "System.removeDirectory(directory) takes a directory name as a string argument.");

    RemoveDir(path);

    return 0;
}
Exemplo n.º 12
0
BOOL CFileUtil::RecurseRemoveDir(char* szPathName)
{
    DIR*                pDIR;
    struct dirent*      pDirEnt;
	char				szTemp[MAX_PATH];
	BOOL				bValid;
	char				szDirectory[MAX_PATH];
    struct stat         sBuffer;
    int                 iStatus;
    BOOL                bDir;

	strcpy(szDirectory, szPathName);
	RemoveFileSeparator(szDirectory);

    pDIR = opendir(szPathName);

    if (pDIR == NULL)
    {
        return FALSE;
    }

    pDirEnt = readdir(pDIR);
    while (pDirEnt != NULL)
    {
		bValid = TRUE;

        if (!((strcmp(pDirEnt->d_name, ".") == 0) || (strcmp(pDirEnt->d_name, "..") == 0)))
        {
            strcpy(szTemp, szDirectory);
            strcat(szTemp, FILE_SEPARATOR);
            strcat(szTemp, pDirEnt->d_name);

            iStatus = stat(szTemp, &sBuffer);
            if (iStatus == -1)
            {
                printf("%s: %s\n", strerror(errno), szTemp);
                return FALSE;
            }
            bDir = S_ISDIR(sBuffer.st_mode);
            if (bDir) //Directory
            {
				RemoveDir(szTemp);
			}
            else
            {
                unlink(szTemp);
            }
		}
		pDirEnt = readdir(pDIR);
	}

    closedir(pDIR);
	rmdir(szDirectory);
	return TRUE;
}
Exemplo n.º 13
0
int 
InitTransport(void)
{

    if( DirExists(COMM_DIR) ) {
	RemoveDir(COMM_DIR);
    }

    return !mkdir(COMM_DIR,0700)?OK:ERROR;

}
Exemplo n.º 14
0
void
Downloader::CleanupUnzipDir ()
{
	if (!unzipdir)
		return;
	
	RemoveDir (unzipdir);
	g_free (unzipdir);
	unzipped = false;
	unzipdir = NULL;
}
Exemplo n.º 15
0
    int _stdcall REMOVEDIRC( char* pStrPath, int nChar )
    {
        char strPath[MAXPATH];
        if( nChar>=MAXPATH ) {
            return -1;
        }

        memcpy( strPath, pStrPath, nChar*sizeof(char) );
        strPath[nChar] = '\0';
        return RemoveDir( strPath );
    }
Exemplo n.º 16
0
MoonAppRecord *
MoonAppDatabase::CreateAppRecord (const Uri *origin)
{
	char *install_dir, *uid;
	MoonAppRecord *app;
	const char *domain;
	
	if (origin == NULL || !(domain = origin->GetHost ()))
		domain = "localhost";
	
	int seed = (int)(get_now () >> 32);
#if !HAVE_RAND_R
	srand (seed);
#endif
	do {
#if HAVE_RAND_R
		int r = rand_r (&seed);
#else
		int r = rand ();
#endif

		uid = g_strdup_printf ("%u.%s", r, domain);
		install_dir = g_build_filename (base_dir, uid, NULL);
		if (g_mkdir_with_parents (install_dir, 0777) == 0)
			break;
		
		g_free (install_dir);
		g_free (uid);
		
		if (errno != EEXIST) {
			// EEXIST is the only error we can recover from...
			return NULL;
		}
	} while (true);
	
	app = new MoonAppRecord ();
	app->origin = g_strdup (origin->GetOriginalString ());
	app->mtime = time (NULL);
	app->uid = uid;
	
	if (!AddAppRecord (app)) {
		RemoveDir (install_dir);
		delete app;
		return NULL;
	}
	
	g_free (install_dir);
	
	return app;
}
Exemplo n.º 17
0
/*----------------------------------------------------------------------
|   NPT_File::Remove
+---------------------------------------------------------------------*/
NPT_Result 
NPT_File::Remove(const char* path, bool recurse /* = false */)
{
    NPT_FileInfo info;

    // make sure the path exists
    NPT_CHECK_WARNING(GetInfo(path, &info));

    if (info.m_Type == NPT_FileInfo::FILE_TYPE_DIRECTORY) {
        return RemoveDir(path, recurse);
    } else {
        return RemoveFile(path);
    }
}
BOOL CFileUtil::RemoveDir(const char*szPathName)
{
	WIN32_FIND_DATA		sFindData;
	CChars				szFindName;
	CChars				szTemp;
	HANDLE				hFindHandle;
	BOOL				bContinue;
	BOOL				bValid;
	CChars				szDirectory;
	BOOL				bDeleted;

	szDirectory.Init(szPathName);
	RemoveFileSeparator(&szDirectory);

	szFindName.Init(szPathName);
	AppendToPath(&szFindName, "*.*");

	hFindHandle = FindFirstFile(szFindName.Text(), &sFindData);
	bContinue = (hFindHandle != INVALID_HANDLE_VALUE);
	bDeleted = TRUE;
	while (bContinue)
	{
		bValid = TRUE;
		if (sFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			if (!((strcmp(sFindData.cFileName, ".") == 0) || (strcmp(sFindData.cFileName, "..") == 0)))
			{
				szTemp.Init(szDirectory);
				AppendToPath(&szTemp, sFindData.cFileName);
				RemoveDir(szTemp.Text());
				szTemp.Kill();
			}
		}
		else
		{
			szTemp.Init(szPathName);
			AppendToPath(&szTemp, sFindData.cFileName);
			bDeleted &= DeleteFile(szTemp.Text());
			szTemp.Kill();
		}
		bContinue = FindNextFile(hFindHandle, &sFindData);
	}
	FindClose(hFindHandle);
	RemoveDirectory(szDirectory.Text());

	szDirectory.Kill();
	szFindName.Kill();
	return bDeleted;
}
Exemplo n.º 19
0
bool plFileUtils::RemoveDirTree(const char * path)
{
    hsFolderIterator it(path);
    while (it.NextFile())
    {
        const char * fname = it.GetFileName();
        if ( fname[0]=='.' )
            continue;
        char pathAndName[128];
        it.GetPathAndName(pathAndName);
        if ( it.IsDirectory() )
        {
            RemoveDirTree( pathAndName );
            RemoveDir( pathAndName );
        }
        else
        {
            RemoveFile( pathAndName );
        }
    }
    RemoveDir( path );

    return 1;
}
Exemplo n.º 20
0
int CFileZillaApi::Command(t_command *pCommand)
{
	//Check if call allowed
	if (!m_bInitialized)
		return FZ_REPLY_NOTINITIALIZED;

	//Dispatch command to command specific functions
	switch(pCommand->id)
	{
	case FZ_COMMAND_LIST:
		if (pCommand->param1!=_MPT(""))
			return List(pCommand->path,pCommand->param1,pCommand->param4);
		else if (!pCommand->path.IsEmpty())
			return List(pCommand->path,pCommand->param4);
		else
			return List(pCommand->param4);
		break;
	case FZ_COMMAND_CONNECT:
		return Connect(pCommand->server);
		break;
	case FZ_COMMAND_DISCONNECT:
		return Disconnect();
		break;
	case FZ_COMMAND_FILETRANSFER:
		return FileTransfer(pCommand->transferfile);
		break;
	case FZ_COMMAND_DELETE:
		return Delete(pCommand->param1, pCommand->path);
		break;
	case FZ_COMMAND_REMOVEDIR:
		return RemoveDir(pCommand->param1, pCommand->path);
		break;
	case FZ_COMMAND_MAKEDIR:
		return MakeDir(pCommand->path);
		break;
	case FZ_COMMAND_RENAME:
		return Rename(pCommand->param1, pCommand->param2, pCommand->path, pCommand->newPath);
		break;
	case FZ_COMMAND_CUSTOMCOMMAND:
		return CustomCommand(pCommand->param1);
		break;
	case FZ_COMMAND_CHMOD:
		return Chmod(pCommand->param4, pCommand->param1, pCommand->path);
		break;
	}
	return FZ_REPLY_INVALIDPARAM;
}
Exemplo n.º 21
0
int RemoveDir(char * dirName)
{
    WIN32_FIND_DATA fileData;
    HANDLE hSearch;
    char filePattern[MAX_PATH_SIZE] = {0};
    sprintf(filePattern, "%s\\%s", dirName, "*");

    BOOL fFinished = false;

    hSearch = FindFirstFile(filePattern, &fileData);
    
    while (!fFinished) 
    {
        if (fileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY) 
        {
            if ((strcmp(fileData.cFileName, ".") != 0) && (strcmp(fileData.cFileName, "..") != 0))
            {
                //For none "." & ".." directory, take resursive handling mechanism
                char nextDirName[MAX_PATH_SIZE] = {0};
                sprintf(nextDirName, "%s\\%s", dirName, fileData.cFileName);
                RemoveDir(nextDirName);
            }
        }
        else 
        {
            //For general file, just delete
            char fullFileName[MAX_PATH_SIZE] = {0};
            sprintf(fullFileName, "%s\\%s", dirName, fileData.cFileName);
            DeleteFile(fullFileName);
            
        }
        if (!FindNextFile(hSearch, &fileData) && (GetLastError() == ERROR_NO_MORE_FILES))
                fFinished = true;
    }
    //Close the search handle
    FindClose(hSearch);
    //Then delete the directory
    RemoveDirectory(dirName);
    return 1;
}
Exemplo n.º 22
0
Arquivo: VFS.cpp Projeto: ss23/rpcs3
void VFS::DeleteAll(const std::string& ps3_path) const
{
	// Delete directory and all its contents recursively
	for (const auto entry : vfsDir(ps3_path))
	{
		if (entry->name == "." || entry->name == "..")
		{
			continue;
		}

		if (entry->flags & DirEntry_TypeFile)
		{
			RemoveFile(ps3_path + "/" + entry->name);
		}

		if (entry->flags & DirEntry_TypeDir)
		{
			DeleteAll(ps3_path + "/" + entry->name);
		}
	}

	RemoveDir(ps3_path);
}
Exemplo n.º 23
0
//---------------------------------------------------------------------------
void __fastcall TCopyProgress::TimerTimer(TObject *Sender)
{
//Надо переделать постановку в очередь файлов загруженных в память и выгрузку их
//переменные i,j,k 
  static __int64 memsize,rwconst;
  static int i, j, k;
  static bool firstwrite;
  static int exitcode = EX_EOF, len;
  try
    {
  switch(FMode)
    {
    case cmInit:
      memsize = FMemoryBuffer;
      rwconst = FRWConst;
      i = 0;
      j = 0;
      k = 0;
      FMode = cmLoad;
      ReadingProgressBar->Position = ReadingProgressBar->Min;
      ReadingLabel->Show();
      ReadingProgressBar->Show();
      firstwrite = true;
      break;

    case cmLoad:
      if(i != FFileList->Files)
        {
//        if(FFileList->Selected[i])
//          {
          AnsiString temp;
          if(!(FFile && FFileList->File[i]->Root))
            temp = FFileList->File[i]->FullName;
          else
            temp = GetNewName(FDestinationName,FFileList->File[i]->FullName);//get name from mask
          if(!VerifyStatements(FTarget + temp,i))
            {
            i++;
            break;
            }
          FMem[k] = new TFileCmd(FSource,FTarget,temp,FFileList->File[i],FBuffer,FAddFile);
          if(FMem[k]->SourceHandle == -1)
            throw EFOpenError("Couldn't open file " + FMem[k]->SourceName);
          if(FMem[k]->Type == fstFile)
            {
            AnsiString path = ExtractFilePath(FSource + FMem[k]->SourceName), temp = ExtractFileName(FMem[k]->SourceName);
            len = ReadingLabel->Canvas->TextWidth(temp);
            ReadingLabel->Caption = MinimizeName(path,ReadingLabel->Canvas,
              ReadingLabel->ClientWidth - len) + temp;
            ReadingProgressBar->Position = ReadingProgressBar->Min;
            }
          FMode = cmLoading;
          i++;
//          }
//        else
//          i++;
        }
      else
        {
        memsize = FMemoryBuffer;
        FMode = cmSave;
        }
      break;
      
    case cmLoading:
      exitcode = FMem[k]->LoadFileToMemory(memsize,rwconst);
      if(FMem[k]->Type == fstFile)
        ReadingProgressBar->Position = (int) ((FMem[k]->FileSourcePos + 1) * (ReadingProgressBar->Max -
          ReadingProgressBar->Min) / (FMem[k]->FileSize + 1));
      switch(exitcode)
        {
        case EX_NEXT:
          rwconst = FRWConst;
          memsize = FMemoryBuffer;
          FMode = cmSave;
          break;
        case EX_EOF:
          k++;
          rwconst = FRWConst;
          FMode = cmLoad;
        }
      break;
      
    case cmSave:
      if(firstwrite)
        {
        WritingProgressBar->Position = WritingProgressBar->Min;
        WritingLabel->Show(); 
        WritingProgressBar->Show(); 
        firstwrite = false;
        }
      if(j == k && i == FFileList->Files && exitcode == EX_EOF)
        {
        for (i = k - 1; i >= 0; i--)
          {
          if(FMove && FMem[i]->Type == fstDirectory)
            {
            if(!RemoveDir(FMem[j]->SourcePath + FMem[j]->SourceName))
              throw EInOutError("The directory " + FMem[j]->SourceName + " can't be deleted");
            }
          delete FMem[i];
          }
        FCopied = true;
        Close();
        return;
        }
      if(!FMem[j]->SaveContinue)
        {
        FMem[j]->CreateFile();
        if(FMem[j]->Type == fstFile)
          {
          AnsiString path = ExtractFilePath(FTarget + FMem[j]->DestinationName), temp = ExtractFileName(FMem[j]->DestinationName);
          len = WritingLabel->Canvas->TextWidth(temp);  
          WritingLabel->Caption = MinimizeName(path,WritingLabel->Canvas,
            WritingLabel->ClientWidth - len) + temp;
          WritingProgressBar->Position = WritingProgressBar->Min;
          }
        }
      FMode = cmSaving;//verify if directory then next save (not saving)
      break;
      
    case cmSaving:
      exitcode = FMem[j]->SaveMemoryToFile(memsize,rwconst);
      if(FMem[j]->Type == fstFile)
        WritingProgressBar->Position = (int) ((FMem[j]->FileDestinationPos + 1) * (WritingProgressBar->Max - 
          WritingProgressBar->Min) / (FMem[j]->FileSize + 1));
      switch(exitcode)
        {
        case EX_EOF:
          if(FMove && FMem[j]->Type == fstFile)
            {
            if(!DeleteFile(FMem[j]->SourcePath + FMem[j]->SourceName))
              throw EInOutError("Error occurs during deleting file " + FMem[j]->SourceName);
            }
          rwconst = FRWConst;
          j++;
          FMode = cmSave;
          break;
        case EX_NEXT:
          rwconst = FRWConst;
          memsize = FMemoryBuffer;
          FMode = cmLoading;
          break;
        case EX_TOBECONTINUED:
          break;
        }
    }
    }
  catch(...)
    {
/*      if(FMode == cmLoad)
        k --;*/
      for(j = 0; j <= k; j++)
        delete FMem[j];
      FCopied = true;
      Close();
      return;
    }
}
Exemplo n.º 24
0
unsigned int __stdcall InstallAction ( MSIHANDLE hModule )
{
    // store the original path
    char ORIG_PATH[MAX_PATH_SIZE] = {0};  // c:\somewhere
    GetCurrentDirectory(MAX_PATH_SIZE, ORIG_PATH);

    if (InitGlobal() == false)
    {
        return 0;
    }
    
    ExtractBinaryFile(hModule, "JarPack", g_TEMP_INSTALLER_JAR);

    do_extract(g_TEMP_INSTALLER_JAR);

	// get JnlpFileName Property from msi Property table
    char jnlpFileName[256] = {0};
    GetMsiProperty(hModule, jnlpFileName, "JnlpFileName");
    char TEMP_JNLP_FILE[MAX_PATH_SIZE] = {0};  // C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\[javaws4c1.tmp]\draw.jnlp
    sprintf(TEMP_JNLP_FILE, "%s\\%s", g_TEMP_JAVAWS_PATH, jnlpFileName);

	// get Shortcut Property from msi Property table
    char shortcut[256] = {0};
    GetMsiProperty(hModule, shortcut, "Shortcut");
    if(shortcut[0] != '0')
    {
        strncpy(g_SHORTCUT, "-shortcut", strlen("-shortcut"));
    }

	// get CacheType Property from msi Property table
    char cachetype[256] = {0};
    GetMsiProperty(hModule, cachetype, "CacheType");
    if(0 == stricmp(cachetype, "system"))
    {
        strncpy(g_CACHE_TYPE, "-system", strlen("-system"));
    }

	// get Association Property from msi Property table
    char association[256] = {0};
    GetMsiProperty(hModule, association, "Association");
    if(association[0] != '0')
    {
        strncpy(g_ASSOCIATION, "-association", strlen("-association"));
    }

    // install the jnlp software
    STARTUPINFO stinfo = {0}; //info of the window
    stinfo.cb = sizeof(STARTUPINFO);
    PROCESS_INFORMATION procinfo; //info of the process
    char CREATEPROCESS[MAX_PATH_SIZE] = {0};  // javaws -silent -import -system -codebase %s
    sprintf(CREATEPROCESS, "%s\\javaws %s -silent -import %s %s -codebase \"%s\" %s", 
        g_JAVAWS_HOME, g_CACHE_TYPE, g_SHORTCUT, g_ASSOCIATION, g_TEMP_JAVAWS_URL, TEMP_JNLP_FILE);

    if(!CreateProcess(NULL, CREATEPROCESS, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &stinfo, &procinfo))
    {
        return 0;
    }
    
    // wait for the end of the process
    WaitForSingleObject(procinfo.hProcess, INFINITE);
    CloseHandle(procinfo.hProcess);
    CloseHandle(procinfo.hThread);

    // restore to original path & Remove the generated temporary directory
    SetCurrentDirectory(ORIG_PATH);
    RemoveDir(g_TEMP_JAVAWS_PATH);

    return ERROR_SUCCESS;
}
Exemplo n.º 25
0
main()
{
    static char text[MAXSEARCH];  /* Pointer to buffer for search text  */
    static char date_time[19];    /* Receive file date and time         */
    int err, mode, handle, len;   /* Codes, file handle, bytes read     */
    int row, col, ch;             /* Cursor coordinates, kb character   */
    int i, j, attr;               /* Index variables, file attribute    */
    int disp_attr;                /* Display attribute                  */
    char *spec, *ptr, *buffer;    /* File spec, char match, read buffer */
    long dsize, disk_use;         /* Disk size and usage                */
    struct DISKSTAT disk;         /* Structure for disk size params     */

    static char copy_msg[] =
    {
        "Files can be copied or moved in 2 different modes:\n" \
        "      0  -  overwrite target file if it exists\n" \
        "      1  -  abort if target file exists\n\n" \
        "Mode 1 is supported only with DOS versions 3.0 or higher.\n"
    };
    static char move_msg[] =
    {
        "Quick Move uses DOS function 56h (Rename File) to effectively " \
        "move a file from\none directory to another directory on the " \
        "same drive.  It copies the entry\nfrom the source directory to " \
        "the target directory, but does not physically\ncopy the file.\n\n" \
        "Source and target specifications must be given in full, " \
        "including filenames,\neven if the names are the same."
    };
    static char grep_msg[] =
    {
        "The Find Text option uses the StrFindChar and StrCompare procedures " \
        "to locate\na text string within specified files, like Unix's " \
        "\"grep\" command.  Find Text\nis limited to case-sensitive searches " \
        "within the current directory.\n\nEnter the desired search string " \
        "without quotation marks.  When specifying the\nfilename, use " \
        "wildcard characters to expand the search to a group of files --\n" \
        "for example, \"*.*\" searches all files within the current " \
        "directory, \"*.bat\"\nlimits the search to batch files, and so forth."
    };
    static char attr_msg[] =
    {
        "\t\t\t1    normal      \n" \
        "\t\t\t2    read-only   \n" \
        "\t\t\t3    hidden      \n" \
        "\t\t\t4    system      \n" \
        "\t\t\t     volume      \n" \
        "\t\t\t     subdirectory\n" \
        "\t\t\t5    archive     \n"
    };

    GetVidConfig();
    ReadCharAttr( &disp_attr );
    clear_scrn( disp_attr, 0, 24 );
    SetCurPos( 8, 0 );
    puts( "Welcome to the FILEDEMO program.\n\n\nThis program is meant " \
          "to encourage experimentation while demonstrating how to\naccess " \
          "DOS from assembly-language procedures.  As a safety precaution, " \
          "however,\nwe suggest you DO NOT experiment with files that " \
          "cannot easily be replaced." );
    press();

    do
    {
        /* Display current drive and directory */
        clear_scrn( disp_attr, 0, 24 );
        SetCurPos( 0, 0 );
        printf( "Current Directory:  %c:\\", (char)(GetCurDrive() + 'A') );
        GetCurDir( source );
        puts( source );

        /* Display DOS version */
        SetCurPos( 1, 0 );
        printf( "DOS Version:        %2.1f", ( (float) GetVer() ) / 100 );

        /* Display disk statistics for current drive */
        SetCurPos( 0, 58 );
        GetDiskSize( 0, &disk );
        dsize = (long)disk.bytes * disk.sects * disk.total;
        disk_use = (long)(disk.total - disk.avail) * disk.bytes * disk.sects;
        printf( "Disk Size: %6lu K", dsize / 1024 );
        SetCurPos( 1, 58 );
        printf( "Disk Use:  %6lu K", disk_use / 1024 );

        /* Display menu and poll for keystroke */
        clear_scrn( disp_attr, 2, 23 );
        SetCurPos( 5, 0 );
        puts( " \t               ***      FILE " \
              "Demonstration Program      ***" );
        SetCurPos( 7, 0 );
        puts( " \tA  List Directory       \t\tH  Get/Set File Attribute" );
        puts( " \tB  Copy File            \t\tI  Get File Date and Time" );
        puts( " \tC  Move File            \t\tJ  Rename File" );
        puts( " \tD  Make Subdirectory    \t\tK  Delete File" );
        puts( " \tE  Remove Subdirectory  \t\tL  Create Unique File" );
        puts( " \tF  Change Default Drive \t\tM  Quick Move" );
        puts( " \tG  Change Directory     \t\tN  Find Text" );
        printf( "\n\n\tSelect an option, or press ESC to quit: " );
        ch = getch();
        switch( (ch = toupper( ch )) )
        {
            /* List first 60 files in specified directory */
            case 'A':
                err  = list_dir( get_spec( 1 ), disp_attr );
                if( !err )
                    press();
                break;

            /* Copy or Move File according to requested mode:
             *          0 = overwrite target
             *          1 = abort if target exists
             * If Move requested, delete source file after copy.
             */
            case 'B':
            case 'C':
                clear_scrn( disp_attr, 2, 17 );
                SetCurPos( 9, 0 );
                puts( copy_msg );
                mode = -1;
                while( (mode < 0)  ||  (mode > 1) )
                {
                    SetCurPos( 16, 0 );
                    printf( "Enter copy mode:  " );
                    mode = (int)(getche() - '0');
                }
                spec = get_spec( 2 );                   /* Get source     */
                strcpy( source, spec );                 /* Save in buffer */
                spec = get_spec( 3 );                   /* Get target     */
                err  = CopyFile( mode, source, spec );
                if( (ch == 'C')  &&  !err )
                    err = DelFile( source );
                break;

            /* Make Directory */
            case 'D':
                err = MakeDir( get_spec( 1 ) );
                break;

            /* Remove Directory */
            case 'E':
                err = RemoveDir( get_spec( 1 ) );
                break;

            /* Change Default Drive */
            case 'F':
                SetCurPos( 18, 0 );
                printf( "Enter new drive letter:  " );
                ch = getch();
                ch = toupper( ch );
                ChangeDrive( ch );
                err = 0;
                break;

            /* Change Directory */
            case 'G':
                err = ChangeDir( get_spec( 1 ) );
                break;

            /* Get and Set File Attributes */
            case 'H':
                strcpy( source, get_spec( 3 ) );
                if( (err = GetAttribute( source )) != -1 )
                {
                    attr = err;
                    if( !attr )
                        attr_msg[6] = '*';
                    else
                        attr_msg[6] = ' ';
                    for( j = 1, i = 27; j <= 32; j <<= 1, i+= 21 )
                    {
                        attr_msg[i] = ' ';
                        if( attr & j )
                            attr_msg[i] = '*';
                    }
                    err = 0;
                    clear_scrn( disp_attr, 2, 17 );
                    SetCurPos( 7, 0 );
                    puts( attr_msg );
                    printf( "\n\nToggle attribute bits by selecting 1-5, " \
                            "or any other key to exit:  " );
                    mode = (int)( getch() - '0' );
                    if( (mode > 0)  &&  (mode < 6) )
                    {
                        switch( --mode )
                        {
                            case 0:
                                attr = 0;
                                break;

                            case 1:
                            case 2:
                            case 3:
                                attr = attr ^ (1 << (--mode) );
                                break;

                            case 4:
                                attr = attr ^ 32;
                        }
                        err = SetAttribute( attr, source );
                    }
                }
                break;

            /* Get File Date and Time */
            case 'I':
                if( (handle = OpenFile( 0, get_spec( 3 ) )) == -1 )
                    err = 1;
                else
                    err = 0;
                if( !err )
                {
                    if( !(err = GetFileTime( handle, date_time )) )
                    {
                        clear_scrn( disp_attr, 2, 17 );
                        SetCurPos( 12, 10 );
                        printf( "File's date and time stamp:  %s", date_time );
                        CloseFile( handle );
                        press();
                    }
                }
                break;

            /* Rename File */
            case 'J':
                strcpy( source, get_spec( 2 ) );
                err = RenameFile( source, get_spec( 3 ) );
                break;

            /* Delete File */
            case 'K':
                err = DelFile( get_spec( 3 ) );
                break;

            /* Create File with Unique Name */
            case 'L':
                strcpy( source, get_spec( 1 ) );
                handle = UniqueFile( 0, source );   /* Normal file attr = 0 */
                if( handle >= 0 )
                {
                    printf( "\n\nDOS creates file %s", source );
                    press();
                    err = 0;
                }
                else err = 1;
                break;

            /* Quick Move from one directory to another */
            case 'M':
                clear_scrn( disp_attr, 2, 17 );
                SetCurPos( 8, 0 );
                puts( move_msg );
                strcpy( source, get_spec( 2 ) );
                err = RenameFile( source, get_spec( 3 ) );
                break;

            /* Search files for specified text */
            case 'N':
                clear_scrn( disp_attr, 2, 17 );
                buffer = (char *) malloc( BUFFSIZE + 1 );
                if( buffer == NULL )
                {
                    SetCurPos( 12, 26 );
                    puts( "Insufficient memory for option" );
                    err = 1;
                    break;
                }
                SetCurPos( 7, 0 );
                puts( grep_msg );
                SetCurPos( 18, 0 );
                printf( "Enter search text:  " );
                GetStr( text, MAXSEARCH );

                /* Find first data file. */
                if( err = FindFirst( 0, get_spec( 3 ), &file ) )
                {
                    clear_scrn( disp_attr, 2, 17 );
                    SetCurPos( 12, 24 );
                    puts( "No files found matching specification" );
                }

                /* If file found, initialize screen coordinates and
                 * open file for reading.
                 */
                else
                {
                    clear_scrn( disp_attr, 2, 17 );
                    row = 6;
                    col = 0;
                    do
                    {
                        if( (handle = OpenFile( 0, file.filename )) != -1 )
                        {

                            /* If file opened successfully, read a block
                             * of BUFFSIZE bytes. If end-of-file encountered
                             * (number of bytes read not equal to BUFFSIZE)
                             * or read error, set error flag to break loop.
                             * Terminate block with a NULL character to 
                             * make it an ASCIIZ string.
                             */
                            err = 0;
                            while( !err )
                            {
                                len = ReadFile( handle, BUFFSIZE, buffer );
                                if( (len == 0)  ||  (len != BUFFSIZE) )
                                    ++err;
                                ptr = buffer;
                                *( ptr + len ) = 0;

                                /* Search block for first character in text */
                                while( spec = StrFindChar( text[0], ptr, 0 ) )
                                {

                                    /* If initial character found, compare
                                     * remaining characters in search text.
                                     * If all characters match, display file
                                     * name and break out of loop.
                                     */
                                    ptr = StrCompare( ++spec, &text[1],
                                          (strlen( text ) - 1) );
                                    if( !ptr )
                                    {
                                        SetCurPos( row++, col );
                                        puts( file.filename );
                                        if( row == 16)
                                        {
                                            row  = 6;
                                            col += 20;
                                        }
                                        err  = 1;
                                        break;
                                    }
                                }
                            }
                            CloseFile( handle );
                        }
                        else
                        {
                            err = 1;
                            break;
                        }
                    } while( !FindNext( &file ) );

                    if( (row == 6)  &&  (col == 0) )
                    {
                        SetCurPos( 12, 22 );
                        puts( "Text not found in specified file(s)" );
                    }
                    press();
                    err = 0;
                }
                free( buffer );             /* Free allocated block */
                break;

            default:
                continue;
        }

        if( err )
        {
            clear_scrn( disp_attr, 24, 24 );
            SetCurPos( 24, 0 );
            printf( "***  Error  ***\a" );
            press();
        }

    } while( ch != ESCAPE );            /* Exit if ESC key pressed    */

    clear_scrn( disp_attr, 0, 24 );     /* Clear screen before exit   */
    SetCurPos( 23, 0 );                 /*   and set cursor to bottom */
    return( 0 );
}
Exemplo n.º 26
0
static int wrap_cgpt(int argc,
                     const char *const argv[],
                     const char *mtd_device) {
    uint8_t *original_hash = NULL;
    uint8_t *modified_hash = NULL;
    int ret = 0;

    // Create a temp dir to work in.
    ret++;
    char temp_dir[] = "/tmp/cgpt_wrapper.XXXXXX";
    if (ReadNorFlash(temp_dir) != 0) {
        return ret;
    }
    char rw_gpt_path[PATH_MAX];
    if (snprintf(rw_gpt_path, sizeof(rw_gpt_path), "%s/rw_gpt", temp_dir) < 0) {
        goto cleanup;
    }
    original_hash = DigestFile(rw_gpt_path, SHA1_DIGEST_ALGORITHM);

    // Obtain the MTD size.
    ret++;
    uint64_t drive_size = 0;
    if (GetMtdSize(mtd_device, &drive_size) != 0) {
        Error("Cannot get the size of %s.\n", mtd_device);
        goto cleanup;
    }

    // Launch cgpt on "rw_gpt" with -D size.
    ret++;
    const char** my_argv = calloc(argc + 2 + 1, sizeof(char *));
    if (my_argv == NULL) {
        errno = ENOMEM;
        goto cleanup;
    }
    memcpy(my_argv, argv, sizeof(char *) * argc);
    char *real_cgpt;
    if (asprintf(&real_cgpt, "%s.bin", argv[0]) == -1) {
        free(my_argv);
        goto cleanup;
    }
    my_argv[0] = real_cgpt;

    int i;
    for (i = 2; i < argc; ++i) {
        if (strcmp(my_argv[i], mtd_device) == 0) {
            my_argv[i] = rw_gpt_path;
        }
    }
    my_argv[argc] = "-D";
    char size[32];
    snprintf(size, sizeof(size), "%" PRIu64, drive_size);
    my_argv[argc + 1] = size;
    i = ForkExecV(NULL, my_argv);
    free(real_cgpt);
    free(my_argv);
    if (i != 0) {
        Error("Cannot exec cgpt to modify rw_gpt.\n");
        goto cleanup;
    }

    // Write back "rw_gpt" to NOR flash in two chunks.
    ret++;
    modified_hash = DigestFile(rw_gpt_path, SHA1_DIGEST_ALGORITHM);
    if (original_hash != NULL && modified_hash != NULL) {
        if (memcmp(original_hash, modified_hash, SHA1_DIGEST_SIZE) != 0) {
            ret = WriteNorFlash(temp_dir);
        } else {
            ret = 0;
        }
    }

cleanup:
    free(original_hash);
    free(modified_hash);
    RemoveDir(temp_dir);
    return ret;
}
Exemplo n.º 27
0
static void Rmdir(const char *dirname) {
//    printf("%s\n", dirname.c_str());
    if (RemoveDir(dirname) < 0) {
//            printf("Failed to remove the directory\n");
    }
}
Exemplo n.º 28
0
//FIXME: nuke this!
char *
Application::GetResourceAsPath (const Uri *resourceBase, const Uri *uri)
{
	const char *filename;
	char *dirname, *path;
	char *canonicalized_filename;
	ManagedStreamCallbacks stream;
	unzFile zipfile;
	struct stat st;
	char buf[4096];
	int nread;
	int fd;
	
	if (!get_resource_cb || !uri || uri->IsAbsolute ())
		return NULL;
	
	// construct the path name for this resource
	filename = uri->ToString ();
	canonicalized_filename = Deployment::GetCurrent ()->CanonicalizeFileName (filename, false);
	
	path = g_build_filename (GetResourceRoot(), canonicalized_filename, NULL);
	g_free (canonicalized_filename);
	
	if (g_stat (path, &st) != -1) {
		// path exists, we're done
		return path;
	}
	
	// create the directory for our resource (keeping the relative path intact)
	dirname = g_path_get_dirname (path);
	if (g_mkdir_with_parents (dirname, 0700) == -1 && errno != EEXIST) {
		g_free (dirname);
		g_free (path);
		return NULL;
	}
	
	g_free (dirname);
	
	stream = get_resource_cb (resourceBase, uri);
	
	if (!stream.handle) {
		g_free (path);
		return NULL;
	}
	
	// reset the stream to 0
	if (stream.CanSeek (stream.handle))
		stream.Seek (stream.handle, 0, SEEK_SET);
	
	// create and save the buffer to disk
	if ((fd = g_open (path, O_WRONLY | O_CREAT | O_EXCL, 0600)) == -1) {
		stream.Close (stream.handle);
		g_free (path);
		return NULL;
	}
	
	// write the stream to disk
	do {
		if ((nread = stream.Read (stream.handle, buf, 0, sizeof (buf))) <= 0)
			break;
		
		if (write_all (fd, buf, (size_t) nread) == -1) {
			stream.Close (stream.handle);
			g_unlink (path);
			g_free (path);
			close (fd);
			
			return NULL;
		}
	} while (true);
	
	stream.Close (stream.handle);
	close (fd);
	
	// check to see if the resource is zipped
	if (!(zipfile = unzOpen (path))) {
		// nope, not zipped...
		return path;
	}
	
	// create a directory to contain our unzipped content
	if (!(dirname = CreateTempDir (path))) {
		unzClose (zipfile);
		g_free (dirname);
		g_unlink (path);
		g_free (path);
		return NULL;
	}
	
	// unzip the contents
	if (!ExtractAll (zipfile, dirname, CanonModeResource)) {
		RemoveDir (dirname);
		unzClose (zipfile);
		g_free (dirname);
		g_unlink (path);
		g_free (path);
		return NULL;
	}
	
	unzClose (zipfile);
	g_unlink (path);
	
	if (g_rename (dirname, path) == -1) {
		RemoveDir (dirname);
		g_free (dirname);
		g_free (path);
		return NULL;
	}
	
	g_free (dirname);
	
	return path;
}
Exemplo n.º 29
0
int
main(int argc, char **argv)
{
    char **av = argv;
    struct sockaddr_in host;
    afs_int32 code;
    struct hostent *hp;
    char hnamebuf[200];
    struct timeval tv;
    int noAuth = 1;		/* Default is authenticated connections */

    argc--, av++;
    if (argc < 1) {
	printf("usage: pxclient <serverHost>\n");
	exit(1);
    }
    memset(&host, 0, sizeof(struct sockaddr_in));
    host.sin_family = AF_INET;
    host.sin_addr.s_addr = inet_addr(av[0]);
#ifdef STRUCT_SOCKADDR_HAS_SA_LEN
    host.sin_len = sizeof(struct sockaddr_in);
#endif
    if (host.sin_addr.s_addr != -1) {
	strcpy(hnamebuf, av[0]);
    } else {
	hp = gethostbyname(av[0]);
	if (hp) {
	    host.sin_family = hp->h_addrtype;
	    memcpy((caddr_t) & host.sin_addr, hp->h_addr, hp->h_length);
	} else {
	    printf("unknown server host %s\n", av[0]);
	    exit(1);
	}
    }
    if ((code = pxclient_Initialize(noAuth, host.sin_addr.s_addr)) != 0) {
	printf("Couldn't initialize fs library (code=%d).\n", code);
	exit(1);
    }

    code = ubik_Call(RXAFS_GetTime, cstruct, 0, &tv.tv_sec, &tv.tv_usec);
    if (!code)
	printf("AFS_GetTime on %s sec=%ld, usec=%ld\n", av[0], tv.tv_sec,
	       (long int)tv.tv_usec);
    else
	printf("return code is %d\n", code);

#ifdef notdef
    while (1) {
	char line[500];
	int nargs;

	printf("fs> ");
	if (fgets(line, 499, stdin) != NULL) {
	    char *oper;
	    char **argp = args;
	    GetArgs(line, argp, &nargs);
	    oper = &argp[0][0];
	    ++argp, --nargs;
	    if (!strcmp(oper, "probe")) {
		code =
		    ubik_Call(RXAFS_GetTime, cstruct, 0, &tv.tv_sec,
			      &tv.tv_usec);
		printf("return code is %d\n", code);
		if (!code)
		    printf("sec=%d\n", tv.tv_sec);
	    } else if (!strcmp(oper, "fsstats")) {
		struct afsStatistics stats;

		code = ubik_AFS_GetStatistics(cstruct, 0, &stats);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "fd")) {
		code = FetchData(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "fs")) {
		code = FetchStatus(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "fa")) {
		code = FetchACL(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "sd")) {
		code = StoreData(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "ss")) {
		code = StoreStatus(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "sa")) {
		code = StoreACL(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "cf")) {
		code = CreateFile(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "rf")) {
		code = RemoveFile(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "rn")) {
		code = Rename(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "sl")) {
		code = Symlink(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "hl")) {
		code = HardLink(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "md")) {
		code = MakeDir(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "rd")) {
		code = RemoveDir(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "rdd")) {
		code = Readdir(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "mm")) {
		code = MakeMountPoint(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "rt")) {
		code = ReleaseTokens(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "bs")) {
		code = BulkStatus(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "lk")) {
		code = Lookup(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "gt")) {
		code = GetToken(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "ka")) {
		code = KeepAlive(argp);
		printf("return code is %d\n", code);
	    } else if ((!strcmp(oper, "q")) || !strcmp(oper, "quit"))
		exit(0);
	    else {
		printf("Unknown oper! Available operations: \n\n");
		printf("fd <vnode> <unique> <pos> <len>\n");
		printf("fs <vnode> <unique>\n");
		printf("fa <vnode> <unique>\n");
		printf
		    ("sd <vnode> <unique> <pos> <len> <flen> [<mode>|-1] [<owner>|-1] [<length>|-1] <string>\n");
		printf
		    ("ss <vnode> <unique> [<mode>|-1] [<owner>|-1] [<length>|-1]\n");
		printf("sa <vnode> <unique> <string>\n");
		printf("rf <vnode> <unique> <name>\n");
		printf
		    ("cf <vnode> <unique> <name> [<mode>|-1] [<owner>|-1] [<length>|-1]\n");
		printf
		    ("rn <ovnode> <ounique> <oname> <nvnode> <nunique> <nname>\n");
		printf
		    ("sl <vnode> <unique> <name> <contents> [<mode>|-1] [<owner>|-1] [<length>|-1]\n");
		printf("hl <dvnode> <dunique> <name> <evnode> <eunique>\n");
		printf
		    ("md <vnode> <unique> <name> [<mode>|-1] [<owner>|-1] [<length>|-1]\n");
		printf("rd <vnode> <unique> <name>\n");
		printf("rdd <vnode> <unique> <pos> <len>\n");
		printf("lk <vnode> <unique> <name>\n");
		printf("gt <vnode> <unique> <tokenID>\n");
		printf("ka <vol.l> <vnode> <unique> <isExec> <kaTime>\n");
	    }
	}
    }
#endif
    return 0;
}
Exemplo n.º 30
0
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
}