Esempio n. 1
0
/////////////////////////////////////////////////////////////////////////////////////
// adds a document
void TPdfFrontend::AddDocument(String const &name, String const &Title)
{
	if(FileExists(name))
	{
		// create the dest path, if needed
		RealizeDirectory(GetPdfDataPath());
		
		// opens sequence file, if any end read sequence number
		int Seq;
		String SeqPath = GetPdfDataPath() + "seqf";
		if(FileExists(SeqPath))
		{
			FileIn SeqFile(SeqPath);
			Seq = atoi(SeqFile.GetLine());
		}
		else
			Seq = 1;
		
		// creates destination file name
		String DestName = GetPdfDataPath() + FormatIntDec(Seq, 4, '0') + "-" + Title;
		
		// copies the file to data folder
		FileCopy(name, DestName);
		
		// adds to document lists
		DocumentList.Add(Title);
		Documents.Add(DestName);
		
		// stores the next sequence number
		Seq++;
		FileOut SeqFile(SeqPath);
		SeqFile.PutLine(FormatInt(Seq));
	}
	
} // END TPdfFrontend::AddDocument()
Esempio n. 2
0
const char* FileManager::GetTmpFile(const std::string &filename) {
  std::map<std::string, std::string>::const_iterator file_iter =
    tmp_file_map_.find(filename);
  // If the filename already exists in the map, return the
  // tmp file that we have already created.
  if (file_iter != tmp_file_map_.end()) {
    return file_iter->second.c_str();
  }

  // Add the tmp file to the map and return the reference to the same.
  std::string tmp_file = filename;
  for(int l = 0; l < tmp_file.length(); ++l) {
    if(tmp_file[l] == '/') tmp_file[l] = '_';
  }
  
  tmp_file = "/tmp/" + tmp_file + ".tmp";

  tmp_file_map_[filename] = tmp_file;
  std::cerr << "Inserting: " << filename << " into " << tmp_file << std::endl;

  // Check if the filename exists and if it exists, copy the file to the
  // tmp file.
	if (!syscall(SYS_access, filename.c_str(), F_OK)) {
    FileCopy(filename.c_str(), tmp_file.c_str());
	}

  const char *ret = tmp_file_map_[filename].c_str();

  return ret;
}
Esempio n. 3
0
//////////////////////////////////////////////////////////
//
// CopyExe
//
// Return false if needs admin access
//
//////////////////////////////////////////////////////////
bool CopyExe( void )
{
    SString strGTAEXEPathFrom = GetExePathFilename( false );
    SString strGTAEXEPathTo = GetExePathFilename( true );
    if ( !FileCopy( strGTAEXEPathFrom, strGTAEXEPathTo ) )
        return false;
    return true;
}
Esempio n. 4
0
bool plFileUtils::FileCopy(const char* existingFile, const char* newFile)
{
    wchar_t* wExisting = hsStringToWString(existingFile);
    wchar_t* wNew = hsStringToWString(newFile);
    bool ret = FileCopy(wExisting, wNew);
    delete [] wExisting;
    delete [] wNew;
    return ret;
}
Esempio n. 5
0
bool UserPackManager::TransferPack( const CString &sPack, const CString &sDestPack, FileCopyFn CopyFn, CString &sError )
{
	bool bSuccess = FileCopy( sPack, USER_PACK_SAVE_PATH + "/" + sDestPack, sError, CopyFn );
	if (!bSuccess)
	{
		FILEMAN->FlushDirCache( USER_PACK_SAVE_PATH );
		FILEMAN->Remove( USER_PACK_SAVE_PATH + "/" + sDestPack );
	}

	return bSuccess;
}
Esempio n. 6
0
bool UserPackManager::TransferPack( const CString &sPack, const CString &sDestPack, void(*OnUpdate)(unsigned long, unsigned long), CString &sError )
{
	bool bSuccess = FileCopy( sPack, USER_PACK_SAVE_PATH + "/" + sDestPack, sError, OnUpdate );
	if (!bSuccess)
	{
		FILEMAN->FlushDirCache( USER_PACK_SAVE_PATH );
		FILEMAN->Remove( USER_PACK_SAVE_PATH + "/" + sDestPack );
	}

	return bSuccess;
}
Esempio n. 7
0
// fetch the new app version from server
// and replaces older one
// if ver is not specified, fetches the maximum available
// one but which is less than or equal maxVersion
bool Updater::FetchApp(ProductVersion ver, bool devel)
{
	int err = 0;

	if(!ver)
		ver = FetchMaxValidVersion(acceptDevelVersions);
	if(!ver)
		return false;

	String appServerPath, destPath;
	#ifdef PLATFORM_POSIX
		appServerPath = GetPlatformRoot() + ver.ToString() + "/" + appName;
		destPath = AppendFileName(GetProgramsFolder(), appName);
	#else
		appServerPath = GetPlatformRoot() + ver.ToString() + "/" + appName + ".exe";
		destPath = AppendFileName(GetProgramsFolder(), appName + "\\" + appName + ".exe");
		RealizePath(destPath);
	#endif

	if(isWebServer)
	{
		http.Url(appServerPath);
		http.Timeout(1000*60*30);
		http.MaxContentSize(100000000);
		http.WhenDo = THISBACK(doProgress);

		// fetch version file from server
		appBuffer = http.Execute();
		err = http.GetStatusCode();
		if(err != 200 || http.IsAbort() || http.IsError())
		{
			appBuffer = "";
			return false;
		}
	
		// replaces/installs app
		if(!SaveFile(destPath, appBuffer))
			return false;
	}
	else
		FileCopy(appServerPath, destPath);
#ifdef PLATFORM_POSIX
	if(chmod(~destPath, 0755) != 0)
		return false;
#endif

	// stores current version inside system config path
	if(!SaveFile(AppendFileName(systemConfigPath, "version"), ver.ToString()))
		return false;

	installedVersion = ver;

	return true;
}
Esempio n. 8
0
bool plFileUtils::FileMove(const wchar_t* existingFile, const wchar_t* newFile)
{
#if HS_BUILD_FOR_WIN32
    return (::MoveFileW(existingFile, newFile) != 0);
#elif HS_BUILD_FOR_UNIX
    FileCopy(existingFile,newFile);
    return( RemoveFile( existingFile )==0);
#else
    hsAssert(0, "Not implemented");
    return false;
#endif
}
BOOL CModuleType::save()
{
	char	sysDirScripts	[FILE_MAX_PATHLEN];
	char	sysDirModules	[FILE_MAX_PATHLEN];
	char	sysDirIcons		[FILE_MAX_PATHLEN];

	if (RegKeyGetValue(REGKEY_SECTION_PATHNAME, REGKEY_KEY_SCRIPTS_PATHNAME,	sysDirScripts) == FALSE)
		strcpy(sysDirScripts, "scripts\\");
	if (RegKeyGetValue(REGKEY_SECTION_PATHNAME, REGKEY_KEY_MODULES_PATHNAME,	sysDirModules) == FALSE)
		strcpy(sysDirModules, "modules\\");
	if (RegKeyGetValue(REGKEY_SECTION_PATHNAME, REGKEY_KEY_ICONS_PATHNAME,		sysDirIcons) == FALSE)
		strcpy(sysDirIcons, "icons\\");

	char	outFnameScripts	[FILE_MAX_FILENAME];
	char	outFnameModules	[FILE_MAX_FILENAME];
	char	outFnameIcons	[FILE_MAX_FILENAME];

	sprintf(outFnameModules, "%s%s%s.%s", sysDirModules, getClassName(), getName(), MODULE_FILE_EXTENTION);
	strcpy(outFnameScripts, getScriptName());	FileChangePathName(outFnameScripts, sysDirScripts);
	sprintf(outFnameIcons, "%s%s%s.%s", sysDirIcons, getClassName(), getName(), ICON_FILE_EXTENTION);

	// Copy a icon and script files into system directry.
	BOOL bCopiedScriptFile = FileCopy(getScriptName(), outFnameScripts);
	BOOL bCopiedIconFile = FileCopy(getIconName(), outFnameIcons);
	
	if (!bCopiedScriptFile || !bCopiedIconFile)
		return FALSE;

	// Strip the directory name in a icon and scrpit file name.
	char	scriptFilename	[FILE_MAX_FILENAME];
	char	iconFilename	[FILE_MAX_FILENAME];
	strcpy(scriptFilename, getScriptName());	FileStripPathName(scriptFilename);	setScriptName(scriptFilename);
	sprintf(iconFilename, "%s%s.%s", getClassName(), getName(), ICON_FILE_EXTENTION);	setIconName(iconFilename);

	// Save this module infomation into a file
	return save(outFnameModules);
}
Esempio n. 10
0
int DirCopy( const char *pDirIn, const char *pDirOut,
			 int (*pfnCallback)( const char *p1, const char *p2, unsigned int nCopied,
			 unsigned int nTotal ) )
{
	int numFiles, i;
	fileInfo_t *pFileInfo;
	char szPathIn[MAX_PATH + 1];
	char szPathOut[MAX_PATH + 1];

	// attempt to create target directory
	if( FileMkdir( pDirOut ) == -1 )
		return 0;

	pFileInfo = malloc( sizeof(fileInfo_t) * MAX_DIR_FILES );
	if( !pFileInfo )
		return 0;

	numFiles = DirGetContents( pDirIn, NULL, pFileInfo, MAX_DIR_FILES );
	
	for( i = 0; i < numFiles; i++ )
	{
		if( pFileInfo[i].flags & FLAG_DIRECTORY )
		{
			// build new in path
			snprintf(	szPathIn, sizeof(szPathIn), "%s%s/",
						pDirIn, pFileInfo[i].name );

			// build new out path
			snprintf(	szPathOut, sizeof(szPathOut), "%s%s/",
						pDirOut, pFileInfo[i].name );

			DirCopy( szPathIn, szPathOut, pfnCallback );
		}
		else
		{
			// copy a single file
			snprintf(	szPathIn, sizeof(szPathIn), "%s%s",
						pDirIn, pFileInfo[i].name );

			snprintf(	szPathOut, sizeof(szPathOut), "%s%s",
						pDirOut, pFileInfo[i].name );

			FileCopy( szPathIn, szPathOut, pfnCallback );
		}
	}

	free(pFileInfo);
	return 1;
}
Esempio n. 11
0
// main updater proc inside normal mode
// prepares environment, copy app in temporary folder
// and restarts it in superuser mode
// returns true if app must continue execution, false otherwise
bool Updater::START_Updater(String const &operation)
{
	// prepare environment for updating
	environment.Add("UPDATER_USER", user);
	environment.Add("UPDATER_OP", operation);
	environment.Add("UPDATER_STATE", "INSIDEUPDATER");
	environment.Add("UPDATER_APPNAME", appName);
	environment.Add("UPDATER_EXEPATH", GetExeFilePath());
	
	if(CommandLine().GetCount() && CommandLine()[0] != "--UNINSTALL")
	{
		String s;
		for(int i = 0; i < CommandLine().GetCount(); i++)
			s += CommandLine()[i] + " ";
		s = s.Left(s.GetCount() - 1);
		environment.Add("UPDATER_CMDLINE", s);
	}

	// gets current executable path
	String exePath = GetExeFilePath();
	
	// creates a temporary filename and copies itself
	// in temporary folder
	String tempName = GetTempFileName();
#ifdef PLATFORM_WIN32
	tempName += ".exe";
#endif
	if(!FileCopy(exePath, tempName))
		return true;
	
#ifdef PLATFORM_POSIX
	// for posix, change temp file permission
	// allowing its execution and executes it as a superuser
	if(chmod(~tempName, 0755) != 0)
		return true;
#endif
	
	// executes the file asking for password
	bool res = !SysStartAdmin(tempName, "", environment);
	return res;

}
Esempio n. 12
0
static bool FileMove(const QFileInfo &src, const QFileInfo &dst)
{
    // attempt to rename the file,
    // this will fail if files are on different partitions
    QByteArray source = src.absoluteFilePath().toLocal8Bit();
    QByteArray dest   = dst.absoluteFilePath().toLocal8Bit();
    if (rename(source.constData(), dest.constData()) == 0)
    {
        return true;
    }

    // src and dst are on different mount points, move manually.
    if (errno == EXDEV)
    {
        if (FileCopy(src, dst))
            return FileDelete(src);
    }

    return false;
}
Esempio n. 13
0
void WorkspaceWork::DoImportTree(const String& dir, const String& mask, bool sep, Progress& pi, int from)
{
	String active = GetActivePackage();
	if(active.IsEmpty()) return;
	FindFile ff(AppendFileName(dir, "*.*"));
	Vector<String> dirs, files;
	while(ff) {
		String p = AppendFileName(dir, ff.GetName());
		if(ff.IsFile() && PatternMatchMulti(mask, ff.GetName()))
			files.Add(p);
		if(ff.IsFolder())
			dirs.Add(p);
		ff.Next();
	}
	String relPath(dir.Mid(from)),
		absPath = SourcePath(active, relPath);
	if(sep && files.GetCount()) {
		if(!DirectoryExists(absPath))
			if(!RealizeDirectory(absPath))
				throw Format("An error occurred while creating the directory:&\1%s", absPath);
		Package::File& f = actual.file.Add();
		f = relPath;
		f.separator = f.readonly = true;
	}
	Sort(files, &FileOrder_);
	Sort(dirs, &FileOrder_);
	for(int i = 0; i < files.GetCount(); i++) {
		if(pi.StepCanceled())
			throw String();
		String name = GetFileName(files[i]);
		if(FileCopy(files[i], AppendFileName(absPath, name))) {
			Package::File& f = actual.file.Add();
			f = AppendFileName(relPath, name);
			f.separator = f.readonly = false;
		}
		else
			throw Format("An error occurred while copying the file:&\1%s", files[i]);
	}
	for(int i = 0; i < dirs.GetCount(); i++)
		DoImportTree(dirs[i], mask, true, pi, from);
}
Esempio n. 14
0
void
DeadServerExit(GMC_ARG_VOID)
{
   tps_FileName FileName;
   tp_FilDsc FilDsc;
   size_t sz;

   sz = snprintf(FileName, MAX_FileName, "%s/ERR", OdinDirName);
   if (sz >= MAX_FileName) {
      (void)fprintf(stderr, "File name too long (MAX_FileName=%d): %s/ERR\n",
		  MAX_FileName, OdinDirName);
      exit(1); }/*if*/;
   FilDsc = FileName_RFilDsc(FileName, FALSE);
   /*select*/{
      if (FilDsc != ERROR) {
	 FileCopy(StdErrFD, FilDsc);
	 Close(FilDsc);
      }else{
	 SystemError("Odin server shut down.\n"); };}/*select*/;
   Exit(1);
   }/*DeadServerExit*/
Esempio n. 15
0
void InitBigFile(const char *path)
{
	int arr[ITEM_SIZE];
	char *tmpPath = "D:\\tmp.txt";
	FILE *fr = fopen(path,"rb");
	FILE *fw = fopen(tmpPath,"wb");
	assert(fr!=NULL && fw!=NULL);
	int len;
	while((len=fread(arr,sizeof(int),ITEM_SIZE,fr))==ITEM_SIZE)
	{
		BubbleSort(arr,sizeof(arr)/sizeof(arr[0]));
		assert(fwrite(arr,sizeof(int),len,fw)==len);
	}

	BubbleSort(arr,sizeof(arr)/sizeof(arr[0]));
	assert(fwrite(arr,sizeof(int),len,fw)==len);

	fclose(fr);
	fclose(fw);

	FileCopy(path,tmpPath);
	remove(tmpPath);
}
Esempio n. 16
0
void restoreCoolFiles(){
    int nandtype = NandSwitch();
    if(nandtype == -1){
        return;
    }
    selectedFile = -1;
    MenuInit(&CoolFilesMenu);
    MenuShow();
    while (true) {
        u32 pad_state = InputWait();
		if(pad_state & BUTTON_DOWN) MenuNextSelection();
		if(pad_state & BUTTON_UP)   MenuPrevSelection();
		if(pad_state & BUTTON_A)    { MenuSelect(); break; }
		if(pad_state & BUTTON_B) 	break;
		TryScreenShot();
		MenuShow();
    }
    if(selectedFile == -1) return;
    ConsoleInit();
    ConsoleSetTitle("File Inject : %s", CoolFiles[selectedFile].name);
    char dest[256];
    sprintf(tmpstr, "rxTools/%s", CoolFiles[selectedFile].name);
    sprintf(dest, "%d:%s", nandtype + 1, CoolFiles[selectedFile].path);
    print("Injecting...\n"); ConsoleShow();
    int res = FileCopy(dest, tmpstr);
    char* showres;
    switch(res){
        case 1 : showres = "Success!"; break;
        case -1 : showres = "Cannot write to file!"; break;
        case -2 : showres = "Cannot read from file!"; break;
        default : showres = "Failure!"; break;
    }
    print(showres); print("\n");
    print("\nPress A to exit\n");
	ConsoleShow();
	WaitForButton(BUTTON_A);
}
Esempio n. 17
0
bool GalleryUtil::Copy(const QFileInfo &src, QFileInfo &dst)
{
    if (src.isDir())
        return CopyDirectory(src, dst);

    dst = MakeUnique(dst);

    if (!FileCopy(src, dst))
        return false;

    MSqlQuery query(MSqlQuery::InitCon());
    query.prepare("INSERT INTO gallerymetadata (image, angle) "
                  "SELECT :IMAGENEW , angle "
                  "FROM gallerymetadata "
                  "WHERE image = :IMAGEOLD");
    query.bindValue(":IMAGENEW", dst.absoluteFilePath());
    query.bindValue(":IMAGEOLD", src.absoluteFilePath());
    if (query.exec())
        return true;

    // try to undo copy on DB failure
    FileDelete(dst);
    return false;
}
Esempio n. 18
0
void WorkspaceWork::DoImport(const String& dir, const String& mask, bool sep, Progress& pi)
{
	String active = GetActivePackage();
	if(active.IsEmpty()) return;
	FindFile ff(AppendFileName(dir, "*.*"));
	Vector<String> dirs, files;
	while(ff) {
		String p = AppendFileName(dir, ff.GetName());
		if(ff.IsFile() && PatternMatchMulti(mask, ff.GetName()))
			files.Add(p);
		if(ff.IsFolder())
			dirs.Add(p);
		ff.Next();
	}
	if(sep && files.GetCount()) {
		Package::File& f = actual.file.Add();
		f = GetFileTitle(dir);
		f.separator = f.readonly = true;
	}
	Sort(files, &FileOrder_);
	Sort(dirs, &FileOrder_);
	for(int i = 0; i < files.GetCount(); i++) {
		if(pi.StepCanceled())
			throw String();
		String name = GetFileName(files[i]);
		if(FileCopy(files[i], SourcePath(active, name))) {
			Package::File& f = actual.file.Add();
			f = name;
			f.separator = f.readonly = false;
		}
		else
			throw Format("An error occurred while copying the file:&\1%s", files[i]);
	}
	for(int i = 0; i < dirs.GetCount(); i++)
		DoImport(dirs[i], mask, true, pi);
}
Esempio n. 19
0
int Connect(char* user, char* password, char* host, int port,
        SftpServerAccountInfo* allServers, int currentServerId)
{
  // are we connected ?
  if (PsftpWrapper[currentServerId].hDll != NULL) 
  { 
    // we allready have a connection running
    return SFTP_SUCCESS;        
  }

  int real_port = 22;
  char real_host[MAX_CMD_BUFFER];
  char real_port_string[MAX_CMD_BUFFER];
  SftpServerAccountInfo* current_server = &allServers[currentServerId];
  PsftpWrapperType *currect_psftp = &PsftpWrapper[currentServerId];
  real_host[0] = '\0';

  // ok lets load the DLL and connect to the sftp server 

  InitPsftpWrapperStruct(currentServerId);

  char dll_2_load[MAX_CMD_BUFFER];
  char dll_2_copy[MAX_CMD_BUFFER];
  char dll_with_server_id[100];

  sprintf(dll_with_server_id, "psftp_%i.dll", currentServerId);

  GetTempPath(MAX_CMD_BUFFER, dll_2_load);
  strcat(dll_2_load, dll_with_server_id);

  GetPsftpDllPath(dll_2_copy);
  if (!FileExists(dll_2_copy)) {
    char msg[MAX_CMD_BUFFER];
    sprintf(msg, "%s not exists", dll_2_copy);
    dbg(msg);
    return SFTP_FAILED;
  }

  int fcret = FileCopy(dll_2_copy, dll_2_load);

#ifdef _DEBUG
  currect_psftp->hDll = LoadLibrary(dll_2_copy);
#else
  currect_psftp->hDll = LoadLibrary(dll_2_load);
#endif

  HMODULE dll = currect_psftp->hDll;

  if (dll == NULL) {
    char msg[MAX_CMD_BUFFER];
    sprintf(msg, "Can't load \"%s\" (code %d)", dll_2_load, fcret);
    dbg(msg);
    return SFTP_FAILED;         // DLL couldn't be loaded, write a warn message
  };

  currect_psftp->Connect =
    (PsftpConnectProcType) GetProcAddress(dll, "__map__wcplg_open_sftp_session");
  currect_psftp->Disconnect =
    GetProcAddress(dll, "__map__wcplg_close_sftp_session");
  currect_psftp->DoSftp =
    (PsftpDoSftpProcType) GetProcAddress(dll, "__map__wcplg_do_sftp");
  currect_psftp->GetCurrentDirStruct =
    (PsftpGetCurrentDirStructProcType) GetProcAddress(dll, "__map__wcplg_get_current_dir_struct");
  currect_psftp->GetLastErrorMessage =
    (PsftpGetLastErrorMessageProcType) GetProcAddress(dll, "__map__wcplg_get_last_error_msg");
  currect_psftp->InitProgressProc =
    (PsftpInitProcsProcType) GetProcAddress(dll, "__map__init_Procs");
  currect_psftp->SFTP_DLL_FNCT_psftp_memory_hole__stopfen =
    GetProcAddress(dll, "__map__psftp_memory_hole__stopfen");
  currect_psftp->SetSftpServerAccountInfo =
    (PsftpSetSftpServerAccountInfoProcType) GetProcAddress(dll, "__map__set_Server_config_Struct");
  currect_psftp->SetTransferMode =
    (PsftpSetTransferModeProcType) GetProcAddress(dll, "__map__setTransferMode");
  currect_psftp->Disconnected =
    (PsftpDisconnectedProcType) GetProcAddress(dll, "__map__disconnected");

  if (currect_psftp->Connect == NULL
      || currect_psftp->Disconnect == NULL
      || currect_psftp->DoSftp == NULL
      || currect_psftp->GetCurrentDirStruct == NULL
      || currect_psftp->GetLastErrorMessage == NULL
      || currect_psftp->InitProgressProc == NULL
      || currect_psftp->SFTP_DLL_FNCT_psftp_memory_hole__stopfen == NULL
      || currect_psftp->SetSftpServerAccountInfo == NULL
      || currect_psftp->SetTransferMode == NULL
      || currect_psftp->Disconnected == NULL
	  ) {
    // DLL loaded successfuly, but not all functions could be imported
    dbg("Can't load all of PSFTP.DLL's functions!");
    UnloadPsftpDll(currentServerId);
    return SFTP_FAILED;
  }

  /* 
     DLL-loading and functionsimport successed,
     now try to connect to server
   */

  InitProcs(gRequestProc, gProgressProc, gPluginNumber, currentServerId);

  if ((current_server->keyfilename[0]) & (!current_server->dont_ask4_passphrase)) //get passphrase for private key
  {
    gRequestProc(
        gPluginNumber, 
        RT_Password,
        "Secure FTP: Passphrase for your key", 
        "",
        current_server->passphrase, 
        MAX_CMD_BUFFER);
  }

  currect_psftp->SetSftpServerAccountInfo(*current_server);
  // Logging
  char buf_log[MAX_CMD_BUFFER];

  strcpy(real_host, host);
  strcpy(real_port_string, host);
  trim_host_from_hoststring(real_host);
  trim_port_from_hoststring(real_port_string);

  if (strlen(real_port_string) < 1) {
    real_port = port;
  } else {
    real_port = atoi(real_port_string);
    if (real_port == 0)
      real_port = port;
  }

  if (real_port == 0)
    real_port = 22;              //last check if port set 2 a valid number

  sprintf(buf_log, "CONNECT \\");
  if (gAlreadyConnected)
    LogProc_(MSGTYPE_DETAILS, buf_log);
  else {
    LogProc_(MSGTYPE_CONNECT, buf_log);
    gAlreadyConnected = true;
  }

  sprintf(
      buf_log, 
      "[%s] (connecting to %s@%s:%i using %s)",
      current_server->title, 
      user, 
      real_host, 
      real_port,
      current_server->use_key_auth 
          ? "public key authentication" 
          : "password authentication");
  LogProc_(MSGTYPE_DETAILS, buf_log);

  currect_psftp->SetTransferMode(gDefaultTransferMode);

  if (currect_psftp->Connect(user, password, real_host, real_port) == 1) {
    char sftp_cmd[MAX_CMD_BUFFER];
    
    sprintf(sftp_cmd, "pwd");
    if (ExecuteCommand(sftp_cmd, current_server->base_dir, currentServerId) != SFTP_SUCCESS) {
      strcpy(current_server->base_dir, current_server->home_dir);
    }

    if (current_server->home_dir != NULL) {
      if ((strlen(current_server->home_dir) > 0)
          && (strcmp(current_server->home_dir, ".") != 0)) {
        sprintf(sftp_cmd, "cd \"%s\"", current_server->home_dir);
        convert_slash_windows_to_unix(sftp_cmd);

        if (ExecuteCommand(sftp_cmd, NULL, currentServerId) == SFTP_SUCCESS) {
          strcpy(current_server->base_dir, current_server->home_dir);
        } else {
          sprintf(buf_log, "WARNING: couldn't change to home directory!");
          current_server->home_dir[0] = 0;
          LogProc_(MSGTYPE_DETAILS, buf_log);
        }
      }
    }
    LogProc_(MSGTYPE_CONNECTCOMPLETE, "");
    return SFTP_SUCCESS;
  }

  strcpy(buf_log, currect_psftp->GetLastErrorMessage());
  if (strcmp(buf_log, "") != 0)
    LogProc_(MSGTYPE_IMPORTANTERROR, buf_log);

  //lets look if this is a imported session && use_key_auth=1  - and if this case then change 
  //use_key_auth=0 that the user can give a password
  if (current_server->is_imported_from_any_datasrc == 1
      && current_server->use_key_auth == 1) {
    current_server->use_key_auth = 0;
  }

  UnloadPsftpDll(currentServerId);

  return SFTP_FAILED;
}
Esempio n. 20
0
int CLuaFileDefs::fileCopy ( lua_State* luaVM )
{
//  bool fileCopy ( string filePath, string newFilePath, bool overwrite = false )
    SString filePath; SString newFilePath; bool bOverwrite;

    CScriptArgReader argStream ( luaVM );
    argStream.ReadString ( filePath );
    argStream.ReadString ( newFilePath );
    argStream.ReadBool ( bOverwrite, false );

    if ( !argStream.HasErrors () )
    {
        // Grab our lua VM
        CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine ( luaVM );

        if ( !g_pNet->ValidateBinaryFileName ( newFilePath ) )
        {
            argStream.SetCustomError ( SString ( "Filename not allowed %s", *newFilePath ), "File error" );
        }
        else
        if ( pLuaMain )
        {
            std::string strCurAbsPath;
            std::string strNewAbsPath;

            // We have a resource arguments?
            CResource* pThisResource = pLuaMain->GetResource ();
            CResource* pCurResource = pThisResource;
            CResource* pNewResource = pThisResource;
            if ( CResourceManager::ParseResourcePathInput ( filePath, pCurResource, strCurAbsPath ) &&
                 CResourceManager::ParseResourcePathInput ( newFilePath, pNewResource, strNewAbsPath ) )
            {
                 // Does source file exist?
                if ( FileExists ( strCurAbsPath ) )
                {
                    // Does destination file exist?
                    if ( !bOverwrite && FileExists ( strNewAbsPath ) )
                    {
                        argStream.SetCustomError ( SString ( "Destination file already exists (%s)", *newFilePath ), "File error" );
                    }
                    else
                    {
                        // Inform file verifier
                        g_pClientGame->GetResourceManager()->FileModifedByScript( strNewAbsPath );

                        // Make sure the destination folder exists so we can copy the file
                        MakeSureDirExists ( strNewAbsPath );

                        if ( FileCopy ( strCurAbsPath, strNewAbsPath ) )
                        {
                            // If file copied return success
                            lua_pushboolean ( luaVM, true );
                            return 1;
                        }
                        else
                        {
                            argStream.SetCustomError ( SString ( "Unable to copy %s to %s", *filePath, *newFilePath ), "File error" );
                        }
                    }
                }
                else
                {
                    argStream.SetCustomError ( SString ( "Source file doesn't exist (%s)", *filePath ), "File error" );
                }
            }
        }
    }

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

    // Failed
    lua_pushboolean ( luaVM, false );
    return 1;
}
Esempio n. 21
0
void ScreenArcadePatch::PatchMain()
{
	m_State = PATCH_CHECKING;

        /* NOTE: we used to look for OpenITG prefixed updates also, but the
         * original ITG binary does not, so if we want people to be able to
         * upgrade directly from ITG to OITG, we have to continue to use the
         * "ITG 2 " prefix.  Sad times. */

	/* set up patterns to match */
	CStringArray vsPatterns;
	vsPatterns.push_back( "ITG 2 *.itg" );

	/* check to see if either player has patches */
	PlayerNumber pn = PLAYER_INVALID;

	/* HasPatch() will early abort for us, due to the size() check,
	 * if P1 and P2 both have patches. We just want the first one. */
	FOREACH_PlayerNumber( p )
		if( this->HasPatch(p, vsPatterns) )
			pn = p;

	/* no matches on either card. */
	if( pn == PLAYER_INVALID )
	{
		m_State = PATCH_NONE;
		return;
	}

	/* set the help text to the patch name, blank the patch text */
	m_textHelp->SetText( m_vsPatches[0] );
	PATCH_TEXT( "" );

	/* set up the key paths we want to verify against */
	CStringArray vsRSAPaths;
	vsRSAPaths.push_back( "Data/Patch-OpenITG.rsa" );
	vsRSAPaths.push_back( "Data/Patch.rsa" );

	/* create the path for the patch file */
	CString sPatchFile = m_sProfileDir + m_vsPatches[0];

	// copy the patch file into memory
	// TODO: see if we can FILEMAN->GetFileDriver( "/@mem/" ).
	m_MemDriver = new RageFileDriverMem;

	int iError = 0;
	m_PatchFile = m_MemDriver->Open( ITG_TEMP_FILE, RageFile::WRITE, iError );
	
	if( iError != 0 )
	{
		STATE_TEXT( ssprintf("Failed to open temporary file:\n%s", strerror(iError)) );
		m_State = PATCH_ERROR;
	}

	/* give up to an hour for the data to copy */
	MEMCARDMAN->MountCard( pn, 3600 );

	RageFile patch;
	if( !patch.Open(sPatchFile) )
	{
		STATE_TEXT( ssprintf("Failed to open patch file (%s):\n%s",
			sPatchFile.c_str(), patch.GetError().c_str()) );

		m_State = PATCH_ERROR;
	}

	if( m_State == PATCH_ERROR )
	{
		MEMCARDMAN->UnmountCard(pn);
		return;
	}

	CString sError;
	if( FileCopy( patch, *m_PatchFile, sError, &UpdateProgress) )
	{
		STATE_TEXT( "Patch copied! Checking..." );
		PATCH_TEXT( "" );
	}
	else
	{
		STATE_TEXT( ssprintf("Patch copying failed:\n" "%s", sError.c_str()) );
		m_State = PATCH_ERROR;
	}

	MEMCARDMAN->UnmountCard( pn );

	if( m_State == PATCH_ERROR )
		return;

	/* re-open the patch file read-open. this should not fail. */
	m_PatchFile = m_MemDriver->Open( ITG_TEMP_FILE, RageFile::READ, iError );

	if( !this->VerifyPatch(m_PatchFile, vsRSAPaths) )
	{
		PATCH_TEXT( "" );
		m_State = PATCH_ERROR;
		return;
	}

	/* reset the error checker */
	iError = 0;

	/* check the XML data */
	CString sGame, sSuccessMessage;
	int iPatchRevision;

	/* open our new copy and read from it */
	RageFileDriverZip *fZip = new RageFileDriverZip( m_PatchFile );

	// we'll catch this in a bit, after we've freed our memory
	if( !this->GetXMLData(fZip, sGame, sSuccessMessage, iPatchRevision) )
		m_State = PATCH_ERROR;

	SAFE_DELETE( fZip );

	// if the XML get earlier failed, return now.
	if( m_State == PATCH_ERROR )
		return;

	// accept patches for oITG or ITG2
	if( sGame != "OpenITG" && sGame != "In The Groove 2" )
	{
		sError = ssprintf( "revision is for another game\n" "(\"%s\")", sGame.c_str() );
		STATE_TEXT( ssprintf("Cannot proceed: %s", sError.c_str()) );
		m_State = PATCH_ERROR;
		return;
	}

	int iCurrentRevision = DiagnosticsUtil::GetRevision();

	// HACK: allow any patch at all if it's revision 1.
	if( iCurrentRevision != 1 && iCurrentRevision == iPatchRevision )
	{
		sError = ssprintf( "patch revision (%d) matches the machine revision.", iPatchRevision );
		STATE_TEXT( ssprintf("Cannot proceed: %s", sError.c_str()) );
		m_State = PATCH_ERROR;
		return;
	}

	/* wipe any unsucessful or unused patch data */
	DeleteRecursive( TEMP_PATCH_DIR );
	DeleteRecursive( FINAL_PATCH_DIR );

	FILEMAN->CreateDir( TEMP_PATCH_DIR );

	/* re-open the ZIP file now */
	fZip = new RageFileDriverZip;
	if( !fZip->Load(m_PatchFile) )
	{
		PATCH_TEXT( "Failed to re-open ZIP file!" );
		m_State = PATCH_ERROR;
		return;
	}

	CStringArray vsDirs, vsFiles;
	vsDirs.push_back( "/" );

	/* find all the files we're going to write with a recursive check */
	while( vsDirs.size() )
	{
		CString sDir = vsDirs.back();
		vsDirs.pop_back();

		fZip->GetDirListing( sDir + "/*", vsFiles, false, true );
		fZip->GetDirListing( sDir + "/*", vsDirs, true, true );
	}

	PATCH_TEXT( "Extracting files..." );

	/* write them now */
	for( unsigned i = 0; i < vsFiles.size(); i++ )
	{
		const CString &sPath = vsFiles[i];
		CString sCleanPath = sPath;
		TrimLeft( sCleanPath, "/" );

		if( fZip->GetFileType(sPath) != RageFileManager::TYPE_FILE )
			continue;

		LOG->Trace( "ScreenArcadePatch: copying file \"%s\"", sCleanPath.c_str() );
		PATCH_TEXT( ssprintf("Extracting files...\n" "%s", sCleanPath.c_str()) );

		RageFileBasic *fCopyFrom = fZip->Open( sPath, RageFile::READ, iError );

		RageFile fCopyTo;
		fCopyTo.Open( TEMP_PATCH_DIR + sCleanPath, RageFile::WRITE );

		if( !FileCopy(*fCopyFrom, fCopyTo) )
		{
			PATCH_TEXT( ssprintf("Could not copy \"%s\":\n" "%s", sCleanPath.c_str(),sError.c_str()) );

			m_State = PATCH_ERROR;
			SAFE_DELETE( fCopyFrom );
			SAFE_DELETE( fZip );
			return;
		}

		SAFE_DELETE( fCopyFrom );
		fCopyTo.Close();

/* set CHMOD info */
#ifdef LINUX
		/* get the actual path to the files */
		CString sRealPath = ResolveTempFilePath( sCleanPath );

		const RageFileDriverZip::FileInfo *fi = fZip->GetFileInfo( sPath );
		int ret = chmod( sRealPath.c_str(), fi->m_iFilePermissions );

		LOG->Trace( "chmod( %s, %#o ) returned %i", sRealPath.c_str(), fi->m_iFilePermissions, ret );
#endif // LINUX
	}

	SAFE_DELETE( fZip );

	/* clear the previous copying text */
	STATE_TEXT( "Finalizing patch data..." );
	PATCH_TEXT( "" );

#ifdef LINUX
	sync(); sleep(5);
#endif

	/* we've successfully copied everything. now, move the directory and we're done. */
	if( FILEMAN->Move(TEMP_PATCH_DIR, FINAL_PATCH_DIR) )
	{
		STATE_TEXT( sSuccessMessage );
		m_State = PATCH_INSTALLED;
	}
	else
	{
		STATE_TEXT( "Failed to finalize patch data!\nCheck your system permissions" );
		m_State = PATCH_ERROR;
	}
}
Esempio n. 22
0
File: main.c Progetto: 173210/ppsspp
int main(int argc, char *argv[])
{
	int i;
	pspDebugScreenInit();

	SceUID mod = pspSdkLoadStartModule ("flash0:/kd/chnnlsv.prx",PSP_MEMORY_PARTITION_KERNEL); 
	if (mod < 0) {
		printf("Error 0x%08X loading/starting chnnlsv.prx.\n", mod);
	}

	mod = pspSdkLoadStartModule ("kernelcall.prx",PSP_MEMORY_PARTITION_KERNEL); 
	if (mod < 0) {
		printf("Error 0x%08X loading/starting kernelcall.prx.\n", mod);
	}

	sceCtrlSetSamplingCycle(0);
	sceCtrlSetSamplingMode(PSP_CTRL_MODE_ANALOG);
	for(;;)
	{
		printf("====================================================================");
		printf("PPSSPP Save Tool\n");
		printf("====================================================================\n\n\n");
	   
		switch(currentMenu)
		{
			
		case 0:
			{
				int maxOption = 0;
				for(i = 0; menuList0[i]; i++)
				{
					if(i == selectedOption)
						printf("   > %s\n",menuList0[i]);
					else
						printf("     %s\n",menuList0[i]);
					maxOption++;
				}
				
				int input = ProcessInput(maxOption, &selectedOption);
				if(input == 0)
				{
					currentMenu = 1;
					selectedOption = 0;
				}
				else if(input == 1)
				{
					currentMenu = 4;
					selectedOption = 0;
				}
				else if(input == 2)
				{
					sceKernelExitGame();
				}
			}
			break;
		case 4:
		case 1:
			{
				int maxOption = 0;
				printf("PPSSPP Decrypted Save Directory : \n");
				for(i = 0; menuList1[i]; i++)
				{
					if(i == selectedOption)
						printf("   > %s\n",menuList1[i]);
					else
						printf("     %s\n",menuList1[i]);
					maxOption++;
				}
				
				int input = ProcessInput(maxOption, &selectedOption);
				if(input == maxOption-1)
				{
					if(currentMenu == 1)
						selectedOption = 0;
					else
						selectedOption = 1;
					currentMenu = 0;
				}
				else if(input >= 0)
				{
					basePath = selectedOption;
					if(currentMenu == 1)
					{
						currentMenu = 2;
						UpdateValidDir(1);
					}
					else
					{
						currentMenu = 5;
						UpdateValidDir(0);
					}
					selectedOption = 0;
				}
			}
			break;
		case 5:
		case 2:
			{
				int maxOption = 0;
				if(currentMenu == 2)
					printf("Save to encrypt : \n");
				else
					printf("Save to decrypt : \n");
				
				if(numDirList == 0)
				{
					printf("No compatible data, see README for help on use\n");
				}
				for(i = 0; i < numDirList; i++)
				{
					if(i == selectedOption)
						printf("   > %s\n",dirList[i].name);
					else
						printf("     %s\n",dirList[i].name);
					maxOption++;
				}
				
				for(i = 0; menuList2[i]; i++)
				{
					if((i+numDirList) == selectedOption)
						printf("   > %s\n",menuList2[i]);
					else
						printf("     %s\n",menuList2[i]);
					maxOption++;
				}
				
				printf("\n Invalid path : \n");
				for(i = 0; i < numInvalidDirList && i < (22-numDirList); i++)
				{
					switch(invalidDirList[i].errorId)
					{
						case 1:
							printf("     %s : ENCRYPT_INFO.BIN not found\n",invalidDirList[i].name);
						break;
						case 2:
							printf("     %s : ENCRYPT_INFO.BIN read error\n",invalidDirList[i].name);
						break;
						case 3:
							printf("     %s : ENCRYPT_INFO.BIN wrong version\n",invalidDirList[i].name);
						break;
						case 4:
							printf("     %s : PARAM.SFO not found\n",invalidDirList[i].name);
						break;
						case 5:
							printf("     %s : PARAM.SFO read error\n",invalidDirList[i].name);
						break;
						case 6:
							printf("     %s : SAVEDATA_FILE_LIST not found in PARAM.SFO\n",invalidDirList[i].name);
						break;
						case 7:
							printf("     %s : no save name in SAVEDATA_FILE_LIST\n",invalidDirList[i].name);
						break;
						case 8:
							printf("     %s : no save found\n",invalidDirList[i].name);
						break;
						default:
						break;
					}
				}
				
				int input = ProcessInput(maxOption, &selectedOption);
				if(input == numDirList)
				{
					if(currentMenu == 2)
						currentMenu = 1;
					else
						currentMenu = 4;
					selectedOption = basePath;
				}
				else if(input >= 0)
				{
					if(currentMenu == 2)
						currentMenu = 3;
					else
						currentMenu = 6;
					workDir = input;
					selectedOption = 0;
				}
			}
			break;
		case 6:
		case 3:
		{
			
			EncryptFileInfo encryptInfo;
			if(FileRead(menuList1[basePath], dirList[workDir].name, "ENCRYPT_INFO.BIN",(u8*)&encryptInfo,sizeof(encryptInfo)) < 0)
			{
				printf("Can't read encrypt file\n");
			}
			else
			{
				printf("Key : ");
				for(i = 0; i < 16; i++)
					printf(" %02x",(u8)encryptInfo.key[i]);
				printf("\n");
				printf("SDK Version : 0x%x\n",encryptInfo.sdkVersion);
				
				char srcPath[128];
				char dstPath[128];
				if(currentMenu == 3)
				{
					sprintf(srcPath,"%s%s",menuList1[basePath], dirList[workDir].name);
					sprintf(dstPath,"ms0:/PSP/SAVEDATA/%s",dirList[workDir].name);
					sceIoMkdir(dstPath,0777);
				}
				else
				{
					sprintf(srcPath,"ms0:/PSP/SAVEDATA/%s",dirList[workDir].name);
					sprintf(dstPath,"%s%s",menuList1[basePath], dirList[workDir].name);
				}
					
				int dfd;
				dfd = sceIoDopen(srcPath);
				if(dfd >= 0)
				{
					SceIoDirent dirinfo;
					while(sceIoDread(dfd, &dirinfo) > 0)
					{
						
						if(!(dirinfo.d_stat.st_mode & 0x2000)) // is not a file
							continue;
							
						if(strcmp(dirinfo.d_name,"ENCRYPT_INFO.BIN") == 0) // don't copy encrypt info
							continue;
							
						FileCopy(srcPath, dstPath, dirinfo.d_name);
							
					}
					sceIoDclose(dfd);
				}
				
				if(currentMenu == 3)
				{
						
					char decryptedFile[258], encryptedFile[258], srcSFO[258], dstSFO[258];
					sprintf(decryptedFile,"%s/%s",srcPath ,dirList[workDir].saveFile);
					sprintf(srcSFO,"%s/PARAM.SFO",srcPath);

					sprintf(encryptedFile,"%s/%s",dstPath ,dirList[workDir].saveFile);
					sprintf(dstSFO,"%s/PARAM.SFO",dstPath);
						
					printf("Encoding %s into %s\n",decryptedFile, encryptedFile);
						
					int ret = encrypt_file(decryptedFile, 
											encryptedFile, 
											dirList[workDir].saveFile, 
											srcSFO, 
											dstSFO, 
											encryptInfo.key[0] != 0 ? encryptInfo.key : NULL, 
											GetSDKMainVersion(encryptInfo.sdkVersion)
											);
					
					if(ret < 0) {
						printf("Error: encrypt_file() returned %d\n\n", ret);
					} else {
						printf("Successfully wrote %d bytes to\n", ret);
						printf("  %s\n", encryptedFile);
						printf("and updated hashes in\n");
						printf("  %s\n\n", dstSFO);
					}
				}
				else
				{
					char decryptedFile[258], encryptedFile[258];
					sprintf(encryptedFile,"%s/%s",srcPath ,dirList[workDir].saveFile);
					sprintf(decryptedFile,"%s/%s",dstPath ,dirList[workDir].saveFile);
						
					printf("Decoding %s into %s\n",encryptedFile, decryptedFile);
						
					int ret = decrypt_file(decryptedFile, encryptedFile, encryptInfo.key[0] != 0 ? encryptInfo.key : NULL, GetSDKMainVersion(encryptInfo.sdkVersion));
					
					if(ret < 0) {
						printf("Error: decrypt_file() returned %d\n\n", ret);
					} else {
						printf("Successfully wrote %d bytes to\n", ret);
						printf("  %s\n", decryptedFile);
					}
				}
				printf("   > Back\n");
				
				int input = ProcessInput(1, &selectedOption);
				if(input >= 0)
				{
					if(currentMenu == 3)
						currentMenu = 2;
					else
						currentMenu = 5;
					selectedOption = 0;
				}
			}
		}
		break;
		default:
			sceKernelExitGame();
			break;
		}
	   
		pspDebugScreenClear();
		sceDisplayWaitVblankStart();
		sceGuSwapBuffers();
	}
	return 0;
} 
Esempio n. 23
0
bool IPsecWin7InitDriverInner()
{
	char sys_filename[MAX_PATH];
	bool install_driver = true;
	HANDLE hEngine;
	UINT ret;
	FWPM_SESSION0 session;
	UINT id;
	FWPM_CALLOUT0 callout;

	Format(sys_filename, sizeof(sys_filename), IPSEC_WIN7_DST_SYS, MsGetSystem32Dir());

	if (IsFileExists(sys_filename) && MsIsServiceInstalled(IPSEC_WIN7_DRIVER_NAME))
	{
		if (GetCurrentIPsecWin7DriverBuild() >= CEDAR_BUILD)
		{
			// Not to install since the latest version has been already installed
			install_driver = false;
		}
	}

	if (install_driver)
	{
		char src_filename[MAX_PATH];

		if (MsIsWindows10() == false)
		{
			Format(src_filename, sizeof(src_filename),
				"|DriverPackages\\Wfp\\%s\\pxwfp_%s.sys",
				(MsIsX64() ? "x64" : "x86"), (MsIsX64() ? "x64" : "x86"));
		}
		else
		{
			Format(src_filename, sizeof(src_filename),
				"|DriverPackages\\Wfp_Win10\\%s\\pxwfp_%s.sys",
				(MsIsX64() ? "x64" : "x86"), (MsIsX64() ? "x64" : "x86"));
		}

		// Copy the driver
		if (FileCopy(src_filename, sys_filename) == false)
		{
			Debug("%s copy failed. %u\n", sys_filename, GetLastError());
			if (IsFileExists(sys_filename) == false)
			{
				Debug("%s failed. Abort.\n", sys_filename);
				return false;
			}
		}
		else
		{
			Debug("%s copied.\n", sys_filename);
		}

		// Set the build number
		SetCurrentIPsecWin7DriverBuild();
	}

	// Get whether the device drivers is already installed
	if (MsIsServiceInstalled(IPSEC_WIN7_DRIVER_NAME) == false)
	{
		wchar_t sys_filename_w[MAX_PATH];

		StrToUni(sys_filename_w, sizeof(sys_filename_w), sys_filename);

		// Run a new installation
		if (MsInstallDeviceDriverW(IPSEC_WIN7_DRIVER_NAME, IPSEC_WIN7_DRIVER_TITLE,
			sys_filename_w, NULL) == false)
		{
			// Installation failed
			Debug("MsInstallDeviceDriverW failed.\n");
			return false;
		}
	}

	// Start if the device driver is stopped
	if (MsIsServiceRunning(IPSEC_WIN7_DRIVER_NAME) == false)
	{
		if (MsStartService(IPSEC_WIN7_DRIVER_NAME) == false)
		{
			// Start failure
			Debug("MsStartService failed.\n");
			return false;
		}

		Debug("%s service started.\n", IPSEC_WIN7_DRIVER_NAME);
	}
	else
	{
		Debug("%s service was already started.\n", IPSEC_WIN7_DRIVER_NAME);
	}

	// Open the WFP
	Zero(&session, sizeof(session));

	ret = api->FwpmEngineOpen0(NULL, RPC_C_AUTHN_DEFAULT, NULL, &session, &hEngine);
	if (ret)
	{
		Debug("FwpmEngineOpen0 failed.\n");
		return false;
	}

	// Create the Callout Driver (IPv4)
	Zero(&callout, sizeof(callout));
	callout.calloutKey = GUID_WFP_CALLOUT_DRIVER_V4;
	callout.applicableLayer = FWPM_LAYER_INBOUND_IPPACKET_V4;
	callout.displayData.name = IPSEC_WIN7_DRIVER_TITLE_V4;
	ret = api->FwpmCalloutAdd0(hEngine, &callout, NULL, &id);
	if (ret)
	{
		Debug("FwpmCalloutAdd0 for IPv4 Failed: 0x%X\n", ret);
	}
	else
	{
		Debug("FwpmCalloutAdd0 for IPv4 Ok.\n");
	}

	// Create the Callout Driver (IPv6)
	Zero(&callout, sizeof(callout));
	callout.calloutKey = GUID_WFP_CALLOUT_DRIVER_V6;
	callout.applicableLayer = FWPM_LAYER_INBOUND_IPPACKET_V6;
	callout.displayData.name = IPSEC_WIN7_DRIVER_TITLE_V6;
	ret = api->FwpmCalloutAdd0(hEngine, &callout, NULL, &id);
	if (ret)
	{
		Debug("FwpmCalloutAdd0 for IPv6 Failed: 0x%X\n", ret);
	}
	else
	{
		Debug("FwpmCalloutAdd0 for IPv6 Ok.\n");
	}

	api->FwpmEngineClose0(hEngine);

	return true;
}
Esempio n. 24
0
WORD Install(CHAR szSourcePath[],CHAR szDestPath)
    {
    HFILE hSource;
    HFILE hDestination;
    WORD wCount;
    WORD wStatus;
    WORD wTemp;
    WORD wAttrib;
    WORD wIndex;
    DWORD dwFilePosition;
    WORD wDestPathLength;
    WORD wSourcePathLength;

    DosGetDateTime(&stDateTime);
    stCodeKey.dwCopyKey = (DWORD)stDateTime.hours;
    stCodeKey.dwCopyKey |= (DWORD)stDateTime.minutes << 4;
    stCodeKey.dwCopyKey |= (DWORD)stDateTime.seconds << 10;
    stCodeKey.dwCopyKey |= (DWORD)stDateTime.hundredths << 16;
    stCodeKey.dwCopyKey |= (DWORD)stDateTime.day << 23;
    stCodeKey.dwCopyKey |= (DWORD)stDateTime.month << 27;
    stCodeKey.dwCopyKey |= (DWORD)stDateTime.year << 31;

    wSourcePathLength = strlen(szSourthPath);
    AppendPath(&szSourcePath[wSourcePathLength)],szSourceFile);
    if (DosSetFileMode(abySourcePath,0x0000,0L));
    if ((wLastError = DosOpen(abySourcePath,(PHFILE)&hSource,(PUSHORT)&wStatus,0L,0,0x01,0x61a2,0L)) != 0)
      return(SOURCE_FILE_OPEN);

    DosChgFilePtr(hSource,oFileOffset + oCopyCount,0,&dwFilePosition);
    if ((wLastError = DosRead(hSource,&(BYTE)wTemp,2,&wCount)) != 0)
      return(SOURCE_FILE_READ);

    if (wTemp == 0)
      return(SOURCE_NO_LICENSE);

    if ((wLastError = DosQFileMode(abyDestPath,&wAttrib,0L)) != 0)
      return(SOURCE_FILE_MODE);

    if ((wAttrib & 0x0010) != 0x0010)
      return(DEST_BAD_PATH);

    wDestPathLength = strlen(szDestPath);
    AppendPath(&szDestPath[wDestPathLength],szDeviceFile);
    if (wLastError = FileCopy(szSourcePath,szDestPath) != 0)
        return(SOURCE_FILE_COPY);

    if ((wLastError = DosOpen(szDestPath,(PHFILE)&hDestination,(PUSHORT)&wStatus,0L,0,1,0x6192,0L)) != 0)
        return(DEST_FILE_OPEN);

    stCodeKey.wCopyCount = 0;
    DosChgFilePtr(hDestination,oFileOffset + oCopyKey,0,&dwFilePosition);
    if ((wLastError = DosWrite(hDestination,&(BYTE)stCodeKey.dwCopyKey,6,&wCount)) != 0)
        return(DEST_WRITE_CODE_KEY);

    DosClose(hDestination);
    DosSetFileMode(abyDestPath,0x0021,0L);
    stCodeKey.wCopyCount = wTemp;

    AppendPath(&abyDestPath[wDestPathLength],abyHiddenFile);
    AppendPath(&abySourcePath[wSourcePathLength],abyHiddenFile);

    if (wLastError = FileCopy(abySourcePath,abyDestPath) != 0)
        {
        DosClose(hSource);
        AppendPath(&abySourcePath[wSourcePathLength],abyDeviceFile);
        DosDelete(abyDestPath,0L);
        return(HIDE_FILE_COPY);
        }

    if ((wLastError = DosOpen(abyDestPath,(PHFILE)&hDestination,(PUSHORT)&wStatus,0L,0,1,0x6192,0L)) != 0)
        {
        DosClose(hSource);
        AppendPath(&abySourcePath[wSourcePathLength],abyDeviceFile);
        DosDelete(abyDestPath,0L);
        return(HIDE_FILE_COPY);
        }

    DosChgFilePtr(hDestination,20,0,&dwFilePosition);
    if ((wLastError = DosWrite(hDestination,(&(BYTE)stCodeKey.dwCopyKey),20,&wCount)) != 0)
        {
        DosClose(hDestination);
        DosClose(hSource);
        AppendPath(&abySourcePath[wSourcePathLength],abyDeviceFile);
        DosDelete(abyDestPath,0L);
        return(HIDE_FILE_WRITE);
        }

    DosClose(hDestination);

    DosSetFileMode(abySourcePath,0x0027,0L);
    DosSetFileMode(abyDestPath,0x0027,0L);

    stCodeKey.wCopyCount--;
    DosChgFilePtr(hSource,oFileOffset + oCopyCount,0,&dwFilePosition);
    if ((wLastError = DosWrite(hSource,&(BYTE)stCodeKey.wCopyCount,2,&wCount)) != 0)
        {
        DosClose(hSource);
        DosSetFileMode(abyDestPath,0x0000,0L);
        DosDelete(abyDestPath,0L);
        return(SOURCE_WRITE_CODE_KEY);
        }
    DosClose(hSource);
    AppendPath(&abyDestPath[wDestPathLength],abyDeviceFile);
    if (FixConfigFile())
        {
        printf("% successfully installed.  You must use UNINST.EXE to move the\n",abyDeviceFile);
        printf("device driver to another machine or directory\n");
        if (stCodeKey.wCopyCount != 0)
            {
            printf("\nThere are %u %s device driver licenses still\n",stCodeKey.wCopyCount,abyDeviceFile);
            printf("available for installation.\n\n");
            }
        }
    }
Esempio n. 25
0
///////////////////////////////////////////////////////////////
//
// 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;
}
Esempio n. 26
0
//////////////////////////////////////////////////////////
//
// InitLocalization
//
// Start localization thingmy
//
//////////////////////////////////////////////////////////
void InitLocalization( bool bNoFail )
{
    static bool bDone = false;
    if ( bDone )
        return;

    // Check for and load core.dll for localization
    // Use launch relative path so core.dll can get updated
    SString strCoreDLL = PathJoin( GetLaunchPath(), "mta", MTA_DLL_NAME );
    if ( !FileExists ( strCoreDLL ) )
    {
        if ( !bNoFail )
            return;
        DisplayErrorMessageBox ( ("Load failed.  Please ensure that "
                            "the file core.dll is in the modules "
                            "directory within the MTA root directory."), _E("CL23"), "core-missing" ); // Core.dll missing

        return ExitProcess( EXIT_ERROR );
    }

    // Use registry setting of mta path for dlls, as they will not be present in update files
    const SString strMTASAPath = GetMTASAPath ();
    SetDllDirectory( PathJoin( strMTASAPath, "mta" ) );

    // See if xinput is loadable (XInput9_1_0.dll is core.dll dependency)
    HMODULE hXInputModule = LoadLibrary( "XInput9_1_0.dll" );
    if ( hXInputModule )
        FreeLibrary( hXInputModule );
    else
    {
        // If not, do hack to use dll supplied with MTA
        SString strDest = PathJoin( strMTASAPath, "mta", "XInput9_1_0.dll" );
        if ( !FileExists( strDest ) )
        {
            SString strSrc = PathJoin( strMTASAPath, "mta", "XInput9_1_0_mta.dll" );       
            FileCopy( strSrc, strDest );
        }
    }

    // Check if the core can be loaded - failure may mean msvcr90.dll or d3dx9_40.dll etc is not installed
    HMODULE hCoreModule = LoadLibrary( strCoreDLL );
    if ( hCoreModule == NULL )
    {
        if ( !bNoFail )
            return;
        DisplayErrorMessageBox ( ("Loading core failed.  Please ensure that \n"
                            "Microsoft Visual C++ 2008 SP1 Redistributable Package (x86) \n"
                            "and the latest DirectX is correctly installed."), _E("CL24"), "vc-redist-missing" );  // Core.dll load failed.  Ensure VC++ Redists and DX are installed
        return ExitProcess( EXIT_ERROR );
    }

    // Grab our locale from the registry if possible, if not Windows
    SString strLocale = GetApplicationSetting ( "locale" );
    if ( strLocale.empty() )
    {
        setlocale(LC_ALL, "");
        char* szLocale = setlocale(LC_ALL, NULL);
        strLocale = szLocale;
    }

    typedef CLocalizationInterface* (__cdecl *FUNC_CREATELOCALIZATIONFROMENVIRONMENT)(SString strLocale);
    FUNC_CREATELOCALIZATIONFROMENVIRONMENT pFunc = (FUNC_CREATELOCALIZATIONFROMENVIRONMENT)GetProcAddress ( hCoreModule, "L10n_CreateLocalization" );
    CLocalizationInterface* pLocalization = pFunc(strLocale);
    if ( pLocalization == NULL )
    {
        if ( !bNoFail )
            return;

        DisplayErrorMessageBox ( ("Loading core failed.  Please ensure that \n"
                            "Microsoft Visual C++ 2008 SP1 Redistributable Package (x86) \n"
                            "and the latest DirectX is correctly installed."), _E("CL26"), "vc-redist-missing" );  // Core.dll load failed.  Ensure VC++ Redists and DX are installed
        FreeLibrary ( hCoreModule );
        return ExitProcess( EXIT_ERROR );
    }

    SAFE_DELETE( g_pLocalization );
    g_pLocalization = pLocalization;
    bDone = true;

#ifdef MTA_DEBUG
    TestDialogs();
#endif
}
Esempio n. 27
0
// Check if file exists in Save Dir. If not, copies it from Data dir.
bool CopyFileIfMissing(const std::string& filename, const std::string& srcDir, const std::string& destDir)
{
    bool doCopy = true;
    std::string dest = destDir + "/" + filename;

    if (FileExists(dest))
    {
//std::cout << "File already exists: " << dest << "\n";

        Time destTime = GetFileModifiedTime(dest);

        std::string src = srcDir + "/" + filename;
        Time srcTime = GetFileModifiedTime(src);

        if (!(destTime < srcTime))
        {
            doCopy = false;
        }
    }

    if (doCopy)
    {
#ifdef FILECOPY_DEBUG
        std::cout << "Copying file " << filename << " as dest is older than src, or doesn't exist.\n";
#endif

        if (FileCopy(srcDir, destDir, filename))
        {
#ifdef FILECOPY_DEBUG
            std::cout << "..FileCopy was OK!\n";
#endif
        }
        else
        {
            // Always show for diagnosing crashes etc
            std::cout << "FileCopy FAILED: srcDir: " << srcDir << " destDir: " << destDir << " file: " << filename << "\n";
        }
    }
    else
    {
#ifdef FILECOPY_DEBUG2
        std::cout << "No need to copy file " << filename << ", it's up to date.\n";
#endif
    }

    /*
      if (FileExists(dest))
      {
        std::cout << "File already exists: " << s << "\n";
      }
      else
      {
        std::cout << "Copying file " << filename << "\n";
        if (FileCopy(srcDir, destDir, filename))
        {
          std::cout << "..FileCopy was OK!\n";
        }
        else
        {
          std::cout << "..FileCopy FAILED!\n";
        }
      }
    */

    return true;
}
Esempio n. 28
0
HINSTANCE InstallPcdDriverInternal()
{
	char tmp[MAX_PATH];
	bool install_driver = true;
	HINSTANCE h;
	char *dll_filename;

	// Confirm whether the see.sys is installed in system32\drivers folder
	Format(tmp, sizeof(tmp), "%s\\drivers\\see.sys", MsGetSystem32Dir());

	if (IsFileExists(tmp))
	{
		// If driver file is exist, try to get build number from registry
		if (LoadPcdDriverBuild() >= CEDAR_BUILD)
		{
			// Already latest driver is installed
			install_driver = false;
		}
	}

	if (install_driver)
	{
		char *src_filename = BRIDGE_WIN32_PCD_SYS;
		// If need to install the driver, confirm user is administrator
		if (MsIsAdmin() == false)
		{
			// Non administrator can't install driver
			return NULL;
		}

		if (MsIsX64())
		{
			src_filename = BRIDGE_WIN32_PCD_SYS_X64;
		}

		if (MsIsIA64())
		{
			src_filename = BRIDGE_WIN32_PCD_SYS_IA64;
		}

		// Copy see.sys
		if (FileCopy(src_filename, tmp) == false)
		{
			return NULL;
		}

		// Save build number
		SavePcdDriverBuild(CEDAR_BUILD);
	}

	dll_filename = BRIDGE_WIN32_PCD_DLL;

	if (Is64())
	{
		if (MsIsX64())
		{
			dll_filename = BRIDGE_WIN32_PCD_DLL_X64;
		}
		else if (MsIsIA64())
		{
			dll_filename = BRIDGE_WIN32_PCD_DLL_IA64;
		}
	}

	// Try to load see.dll and initialize
	h = MsLoadLibrary(dll_filename);
	if (h == NULL)
	{
		return NULL;
	}

	return h;
}
Esempio n. 29
0
int CLuaFileDefs::fileCopy ( lua_State* luaVM )
{
//  bool fileCopy ( string filePath, string newFilePath, bool overwrite = false )
    SString filePath; SString newFilePath; bool bOverwrite;

    CScriptArgReader argStream ( luaVM );
    argStream.ReadString ( filePath );
    argStream.ReadString ( newFilePath );
    argStream.ReadBool ( bOverwrite, false );

    if ( !argStream.HasErrors () )
    {
        // Grab our lua VM
        CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine ( luaVM );
        if ( pLuaMain )
        {
            std::string strCurAbsPath;
            std::string strNewAbsPath;
            std::string strCurMetaPath;
            std::string strNewMetaPath;

            // We have a resource arguments?
            CResource* pThisResource = pLuaMain->GetResource ();
            CResource* pCurResource = pThisResource;
            CResource* pNewResource = pThisResource;
            if ( CResourceManager::ParseResourcePathInput ( filePath, pCurResource, &strCurAbsPath, &strCurMetaPath ) &&
                 CResourceManager::ParseResourcePathInput ( newFilePath, pNewResource, &strNewAbsPath, &strNewMetaPath ) )
            {
                // Do we have permissions?
                if ( ( pCurResource == pThisResource && 
                       pNewResource == pThisResource ) ||
                     m_pACLManager->CanObjectUseRight ( pThisResource->GetName ().c_str (),
                                                        CAccessControlListGroupObject::OBJECT_TYPE_RESOURCE,
                                                        "ModifyOtherObjects",
                                                        CAccessControlListRight::RIGHT_TYPE_GENERAL,
                                                        false ) )
                {
                    std::string strCurFilePath;     // Same as strCurAbsPath
                    std::string strNewFilePath;     // Same as strNewAbsPath

                     // Does source file exist?
                    if ( pCurResource->GetFilePath ( strCurMetaPath.c_str(), strCurFilePath ) )
                    {
                        // Does destination file exist?
                        if ( !bOverwrite && pNewResource->GetFilePath ( strNewMetaPath.c_str(), strNewFilePath ) )
                        {
                            argStream.SetCustomError ( SString ( "Destination file already exists (%s)", *newFilePath ), "File error" );
                        }
                        else
                        {
                            // Make sure the destination folder exists so we can copy the file
                            MakeSureDirExists ( strNewAbsPath );

                            if ( FileCopy ( strCurAbsPath, strNewAbsPath ) )
                            {
                                // If file copied return success
                                lua_pushboolean ( luaVM, true );
                                return 1;
                            }
                            else
                            {
                                argStream.SetCustomError ( SString ( "Unable to copy %s to %s", *filePath, *newFilePath ), "File error" );
                            }
                        }
                    }
                    else
                    {
                        argStream.SetCustomError ( SString ( "Source file doesn't exist (%s)", *filePath ), "File error" );
                    }
                }
                else
                {
                    // Make permissions error message
                    SString strWho;
                    if ( pThisResource != pCurResource )
                        strWho += pCurResource->GetName ();
                    if ( pThisResource != pNewResource )
                    {
                        if ( !strWho.empty () )
                            strWho += " and ";
                        strWho += pNewResource->GetName ();
                    }
                    argStream.SetCustomError ( SString ( "ModifyOtherObjects in ACL denied resource %s to access %s", pThisResource->GetName ().c_str (), *strWho ), "ACL issue" );
                }
            }
        }
    }

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

    // Failed
    lua_pushboolean ( luaVM, false );
    return 1;
}
Esempio n. 30
0
// COPY RGBA, DEPTH, FEATURE FILES INTO THE DB
// IF NO FEATURE AVAILABLE, DERIVE IT
int Insert(
		char* filename,
		char* DBFolder,
		char* categoryFolder
		){

	char srcpath[FLEN], srcfile[FLEN], dstpath[FLEN], dstfile[FLEN];
	strcpy(srcpath, filename);

	char *pch = strrchr(filename, '/')+1;
	if (pch==NULL){
		pch = filename;
	}
	strcpy(dstpath, DBFolder);
	strcat(dstpath, "/");
	strcat(dstpath, categoryFolder);
	strcat(dstpath, "/");
	strcat(dstpath, pch);

	//read and copy image file
	strcpy(srcfile, srcpath);
	strcat(srcfile, IMG_EXT);

	if (Exists(srcfile)==0){
		fprintf(stderr, "Image file does not exists!\n");
		return 1;
	}else{
		strcpy(dstfile, dstpath);
		strcat(dstfile, IMG_EXT);

		if (FileCopy(srcfile, dstfile)>0){
			fprintf(stderr, "FileCopy Failed!\n");
			return 3;
		}
	}

	//read and copy depth file
	strcpy(srcfile, srcpath);
	strcat(srcfile, DEPTH_EXT);

	if (Exists(srcfile)==0){
		fprintf(stderr, "Depth file does not exists!\n");
		//return 2;
	}else{
		strcpy(dstfile, dstpath);
		strcat(dstfile, DEPTH_EXT);

		if (FileCopy(srcfile, dstfile)>0){
			fprintf(stderr, "FileCopy Failed!\n");
			return 3;
		}
	}

	//read and copy mask file
	strcpy(srcfile, srcpath);
	strcat(srcfile, MASK_EXT);
	strcpy(dstfile, dstpath);
	strcat(dstfile, MASK_EXT);
	if (Exists(srcfile)==0){//if not exist, create a new mask covering the whole image
		strcpy(srcfile, srcpath);
		strcat(srcfile, IMG_EXT);
		IplImage* image = cvLoadImage(srcfile, CV_LOAD_IMAGE_COLOR);
		if (image==NULL){
			fprintf(stderr, "Failed to Load an image file\n");
		}
		// Fill in 255
		IplImage* mask = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U,1);
		cvSet(mask, cvScalarAll(255), NULL);
		cvSaveImage(dstfile, mask, NULL);
		cvReleaseImage(&image);
		cvReleaseImage(&mask);
	}else{
		if (FileCopy(srcfile, dstfile)>0){
			fprintf(stderr, "FileCopy Failed!\n");
			return 3;
		}
	}

	//read and copy feature file
	strcpy(srcfile, srcpath);
	strcat(srcfile, FTR_EXT);

	if (Exists(srcfile)==0){//if not exist, create a new feature file;
		int retCode = MakeFeature(dstpath);
		if (retCode){
			fprintf(stderr, "Failed to create feature\n");
		}
	}else{
		strcpy(dstfile, dstpath);
		strcat(dstfile, FTR_EXT);
		if (FileCopy(srcfile, dstfile)>0){
			fprintf(stderr, "FileCopy Failed!\n");
			return 3;
		}
	}

	return 0;
}