Exemple #1
0
BOOL WINAPI ini_ready(LPWSTR inifull_name,DWORD str_len)
{
    BOOL rect = FALSE;
#ifdef LIBPORTABLE_STATIC
    dll_module = NULL;
#endif
    GetModuleFileNameW(dll_module,inifull_name,str_len);
    PathRemoveFileSpecW(inifull_name);
    PathAppendW(inifull_name,L"portable.ini");
    rect = PathFileExistsW(inifull_name);
    if (!rect)
    {
        if ( PathRemoveFileSpecW(inifull_name) )
        {
            PathAppendW(inifull_name,L"tmemutil.ini");
            rect = PathFileExistsW(inifull_name);
        }
    }
    return rect;
}
void FileAccessWindows::close() {

	if (!f)
		return;

	fclose(f);
	f = NULL;

	if (save_path!="") {

		//unlink(save_path.utf8().get_data());
		//print_line("renaming..");
		//_wunlink(save_path.c_str()); //unlink if exists
		//int rename_error = _wrename((save_path+".tmp").c_str(),save_path.c_str());


		bool rename_error;

#ifdef WINRT_ENABLED
		// WinRT has no PathFileExists, so we check attributes instead
		DWORD fileAttr;

		fileAttr = GetFileAttributesW(save_path.c_str());
		if (INVALID_FILE_ATTRIBUTES == fileAttr) {
#else
		if (!PathFileExistsW(save_path.c_str())) {
#endif
			//creating new file
			rename_error = _wrename((save_path+".tmp").c_str(),save_path.c_str())!=0;
		} else {
			//atomic replace for existing file
			rename_error = !ReplaceFileW(save_path.c_str(), (save_path+".tmp").c_str(), NULL, 2|4, NULL, NULL);
		}
		if (rename_error && close_fail_notify) {
			close_fail_notify(save_path);
		}

		save_path="";
		ERR_FAIL_COND( rename_error );
	}

}
bool FileAccessWindows::is_open() const {

	return (f!=NULL);
}
void FileAccessWindows::seek(size_t p_position) {

	ERR_FAIL_COND(!f);
	last_error=OK;
	if ( fseek(f,p_position,SEEK_SET) )
		check_errors();
}
int LauncherStartup(const wchar_t *args, int channel) {
  wchar_t pwszPath[UNC_MAX_PATH];
  GetModuleFileNameW(nullptr, pwszPath, UNC_MAX_PATH);
  PathRemoveFileSpecW(pwszPath);
  PathRemoveFileSpecW(pwszPath);
  PathRemoveFileSpecW(pwszPath);
  std::wstring psfile = pwszPath;
  switch (channel) {
  case kOpenEnvironment:
    psfile += L"\\bin\\ClangBuilderEnvironment.ps1";
    break;
  case kBaseBuilder:
    psfile += L"\\bin\\ClangBuilderManager.ps1";
    break;
  case kNinjaBootstrap:
    psfile += L"\\bin\\ClangBuilderBootstrap.ps1";
    break;
  default:
    psfile = L"Not support channel value: " + std::to_wstring(channel);
    OutErrorMessage(psfile.c_str(), L"Not support clangbuilder channel !");
    return -2;
  }
  if (!PathFileExistsW(psfile.c_str())) {
    OutErrorMessage(psfile.c_str(), L"PathFileExists return false");
    return -1;
  }

  if (SHGetFolderPathW(NULL, CSIDL_SYSTEM, NULL, 0, pwszPath) != S_OK) {
    return -1;
  }
  auto length = wcslen(pwszPath);
  StringCchCatW(pwszPath, UNC_MAX_PATH - length,
                L"\\WindowsPowerShell\\v1.0\\powershell.exe ");
  length = wcslen(pwszPath);
  auto offsetPtr = pwszPath + length;
  StringCchPrintfW(offsetPtr, UNC_MAX_PATH - length,
                   L" -NoLogo -NoExit   -File \"%s\" %s", psfile.c_str(), args);
  PROCESS_INFORMATION pi;
  STARTUPINFO si;
  ZeroMemory(&si, sizeof(si));
  ZeroMemory(&pi, sizeof(pi));
  si.cb = sizeof(si);
  si.dwFlags = STARTF_USESHOWWINDOW;
  si.wShowWindow = SW_SHOW;
  if (CreateProcessW(nullptr, pwszPath, NULL, NULL, FALSE,
                     CREATE_NEW_CONSOLE | NORMAL_PRIORITY_CLASS, NULL, NULL,
                     &si, &pi)) {
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
    return 0;
  }
  return GetLastError();
}
int PathForResourceWithPathW (const wchar_t *path, const wchar_t *nm, 
								wchar_t *locFile, int locFileLen) {

	wchar_t tmpBuffer[TMP_BUF_SIZE];

	// build the path to the executable in the generic
	// resources folder, check there first
	swprintf(tmpBuffer, TMP_BUF_SIZE, L"%ls.Resources\\%ls", path, nm);

	if (!PathFileExistsW(tmpBuffer)) {
		// didn't hit generic resource folder, so need to get language codes
		_setLanguageIfNeeded();

		// test to see if localized directory exists, 
		// if so, we don't fall back if we don't find the file.
		swprintf(tmpBuffer, TMP_BUF_SIZE, 
				  L"%ls.Resources\\%S.lproj", path, isoLangCode);

		if (PathFileExistsW(tmpBuffer)) {
			swprintf(tmpBuffer, TMP_BUF_SIZE, L"%ls\\%ls", tmpBuffer, nm);

			if (!PathFileExistsW(tmpBuffer)) return 0;

			wcsncpy(locFile, tmpBuffer, locFileLen);
			return (int) wcslen(locFile);
		}

		// fall back on DEFAULT_LANG_CODE if still no good
		swprintf(tmpBuffer, TMP_BUF_SIZE, L"%ls.Resources\\%S.lproj\\%ls", 
			path, DEFAULT_LANG_CODE, nm);

		// we can't find the resource, so return 0
		if (!PathFileExistsW(tmpBuffer)) return 0;
	}
	
	wcsncpy(locFile, tmpBuffer, locFileLen);
	return (int) wcslen(locFile);


}
Exemple #5
0
bool Cx_PluginLoader::LoadPlugin(const wchar_t* filename)
{
    if (!x3InMainThread())
    {
        X3LOG_WARNING2(L"Can't load plugin in sub thread.", filename);
        return false;
    }

    CLockCount locker(&m_loading);
    int existIndex = GetPluginIndex(filename);

    if (existIndex >= 0 && m_modules[existIndex]->hdll)
    {
        if (_wcsicmp(filename, m_modules[existIndex]->filename) != 0)
        {
            X3LOG_DEBUG2(L"The plugin is already loaded.",
                filename << L", " << (m_modules[existIndex]->filename));
        }
        return false;
    }

    HMODULE hdll = x3LoadLibrary(filename);
    DWORD errcode = GetLastError();

    if (hdll)
    {
        if (RegisterPlugin(hdll))
        {
            int moduleIndex = FindModule(hdll);

            ASSERT(moduleIndex >= 0);
            ASSERT(existIndex < 0 || existIndex == moduleIndex);

            m_modules[moduleIndex]->owned = true;
#ifdef _WIN32
            DisableThreadLibraryCalls(hdll);
#endif
        }
        else
        {
            FreeLibrary(hdll);
            hdll = NULL;
        }
    }
    else if (PathFileExistsW(filename))
    {
        X3LOG_WARNING2(L"Fail to load plugin.", 
            x3::GetSystemErrorString(errcode) << L", " << filename);
    }

    return hdll != NULL;
}
Exemple #6
0
    bool File::PathExists(const MistString& path) {
#ifdef MIST_OS_WINDOWS
        return PathFileExistsW(path.c_str())?true:false;

#else
        struct stat sb;
        
        if (stat(string::WStringToString(path).c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
            return true;
        }
#endif
        
        return false;
    }
Exemple #7
0
void shell_open_with_notepad(const std::string &file_path, bool exsists_only) {
  if (std::string(file_path.begin(), file_path.begin() + 7) == "file://") {
    const std::string fp(file_path.begin() + 7, file_path.end());

    wchar_t soure_buff[MAX_PATH];
    soure_buff[MultiByteToWideChar(CP_UTF8, 0, fp.c_str(), fp.size(), soure_buff, MAX_PATH)] = '\0';

    wchar_t params_buff[MAX_PATH];
    params_buff[MultiByteToWideChar(CP_UTF8, 0, std::string("\"" + fp + "\"").c_str(), fp.size() + 2, params_buff, MAX_PATH)] = '\0';

    if (!exsists_only || PathFileExistsW(soure_buff) == TRUE)
      ShellExecuteW(NULL, NULL, L"notepad.exe", params_buff, NULL, SW_SHOWDEFAULT);
  }
}
Exemple #8
0
bool Files::fileExists(const std::string &path)
{
    #ifdef _WIN32
    std::wstring wpath = Str2WStr(path);
    return PathFileExistsW(wpath.c_str()) == TRUE;
    #else
    FILE *ops = fopen(path.c_str(), "rb");
    if(ops)
    {
        fclose(ops);
        return true;
    }
    return false;
    #endif
}
Exemple #9
0
BOOL WINAPI WaitWriteFile(LPCWSTR ap_path)
{
	BOOL  ret = FALSE;
	WCHAR profile_path[MAX_PATH+1] = {0};
	BOOL  pname = is_thunderbird();
	if (pname)
	{
		_snwprintf(profile_path,MAX_PATH,L"%ls%ls",ap_path,L"\\Thunderbird\\profiles.ini");
	}
	else
	{
		_snwprintf(profile_path,MAX_PATH,L"%ls%ls",ap_path,L"\\Mozilla\\Firefox\\profiles.ini");
	}
	if ( PathFileExistsW(profile_path) )
	{
		if (pname)
		{
			ret = WritePrivateProfileStringW(L"Profile0",L"Path",L"../../",profile_path);
		}
		else
		{
			ret = WritePrivateProfileStringW(L"Profile0",L"Path",L"../../../",profile_path);
		}
	}
	else
	{
		LPWSTR szDir;
		if ( (szDir = (LPWSTR)SYS_MALLOC( sizeof(profile_path) ) ) != NULL )
		{
			wcsncpy (szDir, profile_path, MAX_PATH);
			PathRemoveFileSpecW( szDir );
			SHCreateDirectoryExW(NULL,szDir,NULL);
			SYS_FREE(szDir);
			WritePrivateProfileSectionW(L"General",L"StartWithLastProfile=1\r\n\0",profile_path);
			if (pname)
			{
				ret = WritePrivateProfileSectionW(L"Profile0",L"Name=default\r\nIsRelative=1\r\nPath=../../\r\nDefault=1\r\n\0" \
												,profile_path);
			}
			else
			{
				ret = WritePrivateProfileSectionW(L"Profile0",L"Name=default\r\nIsRelative=1\r\nPath=../../../\r\nDefault=1\r\n\0" \
												,profile_path);
			}
		}
	}
	return ret;
}
Exemple #10
0
    bool File::FileExists(const MistString& filepath) {
#ifdef MIST_OS_WINDOWS
        return PathFileExistsW(filepath.c_str())?true:false;
        
#elif defined(MIST_OS_FAMILY_APPLE)
        return mist_apple_file_exists(filepath);
#else
        
        struct stat sb;
        
        if (stat(Miststring::WStringToString(filepath).c_str(), &sb) == 0 && S_ISREG(sb.st_mode)) {
            return true;
        }
#endif
        return false;
    }
Exemple #11
0
void GreenChrome()
{
    // exe路径
    wchar_t exePath[MAX_PATH];
    GetModuleFileNameW(NULL, exePath, MAX_PATH);

    // exe所在文件夹
    wchar_t exeFolder[MAX_PATH];
    wcscpy(exeFolder, exePath);
    PathRemoveFileSpecW(exeFolder);

    // 生成默认ini文件
    wchar_t iniPath[MAX_PATH];
    ReleaseIni(exeFolder, iniPath);

    // 读取配置
    ReadConfig(iniPath);

    // 启动单次功能
    bool first_run = OnceFeature(iniPath);

    // 自定义用户数据目录
    CustomUserData(iniPath);

    // 打造便携版chrome
    MakePortable(iniPath);

    // 给resources.pak打补丁
    PatchResourcesPak(iniPath);

    // 标签页,书签,地址栏增强
    TabBookmark();

    // 父进程不是Chrome,则需要启动追加参数功能
    wchar_t parentPath[MAX_PATH];
    if (GetParentPath(parentPath))
    {
        if (PathFileExistsW(parentPath) && _wcsicmp(parentPath, exePath) != 0)
        {
            CustomCommand(iniPath, exeFolder, exePath, first_run);
        }
    }
    else
    {
        DebugLog(L"GetParentPath failed");
    }
}
Exemple #12
0
static void DoRestore(RecycleBinMenu *This)
{

    /*TODO add prompts*/
    UINT i;
    for(i=0;i<This->cidl;i++)
    {
        WIN32_FIND_DATAW data;
        TRASH_UnpackItemID(&((This->apidl[i])->mkid),&data);
        if(PathFileExistsW(data.cFileName))
        {
            PIDLIST_ABSOLUTE dest_pidl = ILCreateFromPathW(data.cFileName);
            WCHAR message[100];
            WCHAR caption[50];
            if(_ILIsFolder(ILFindLastID(dest_pidl)))
                LoadStringW(shell32_hInstance,IDS_RECYCLEBIN_OVERWRITEFOLDER,
                            message,sizeof(message)/sizeof(WCHAR));
            else
                LoadStringW(shell32_hInstance,IDS_RECYCLEBIN_OVERWRITEFILE,
                            message,sizeof(message)/sizeof(WCHAR));
            LoadStringW(shell32_hInstance,IDS_RECYCLEBIN_OVERWRITE_CAPTION,
                        caption,sizeof(caption)/sizeof(WCHAR));

            if(ShellMessageBoxW(shell32_hInstance,GetActiveWindow(),message,
                                caption,MB_YESNO|MB_ICONEXCLAMATION,
                                data.cFileName)!=IDYES)
                continue;
        }
        if(SUCCEEDED(TRASH_RestoreItem(This->apidl[i])))
        {
            IPersistFolder2 *persist;
            LPITEMIDLIST root_pidl;
            PIDLIST_ABSOLUTE dest_pidl = ILCreateFromPathW(data.cFileName);
            BOOL is_folder = _ILIsFolder(ILFindLastID(dest_pidl));
            IShellFolder2_QueryInterface(This->folder,&IID_IPersistFolder2,
                                         (void**)&persist);
            IPersistFolder2_GetCurFolder(persist,&root_pidl);
            SHChangeNotify(is_folder ? SHCNE_RMDIR : SHCNE_DELETE,
                           SHCNF_IDLIST,ILCombine(root_pidl,This->apidl[i]),0);
            SHChangeNotify(is_folder ? SHCNE_MKDIR : SHCNE_CREATE,
                           SHCNF_IDLIST,dest_pidl,0);
            ILFree(dest_pidl);
            ILFree(root_pidl);
        }
    }
}
Exemple #13
0
bool CFrameWndFactory::CreateFrameWnd(LPCWSTR factoryFile)
{
    CXTPWinDwmWrapper().SetProcessDPIAware();   // Support high DPI on Vista or above.

    std::wstring xtpfile(getTranslationsPath(L"ToolkitPro.Resource.xml"));
    if (PathFileExistsW(xtpfile.c_str()))
        XTPResourceManager()->SetResourceFile(xtpfile.c_str());
    else
        TRACE1("Warning: no translation file '%s'\n", xtpfile.c_str());

    Object<IConfigXml> xmlfile(x3::clsidXmlFile);
    ASSERT_MESSAGE(xmlfile, "Need the configxml plugin.");
    xmlfile->SetFileName((getConfigPath() + factoryFile).c_str());
    ASSERT_MESSAGE(xmlfile->Reload(), "No xml file or need to setup MSXML4.");

    ConfigSection root(xmlfile->GetData()->GetSection(L""));
    ConfigSection mainframe(root.GetSection(L"mainframe"));
    bool mdi = root->GetBool(L"mdi", false);

    g_factoryRoot = root;
    g_factoryRoot->SetString(L"_appid", m_appid.c_str());

    Object<IUIOptionsInit> initOptions(clsidUIOptions);
    initOptions->setFileName((getConfigPath() + 
        root->GetString(L"optionsFile", L"uioptions.xml")).c_str());

    RegisterDocTemplate(mdi, mainframe, root.GetSection(L"views"));
    if (mdi)
    {
        CMainMDIFrame* pFrame = new CMainMDIFrame;
        if (!pFrame->LoadFrame(0))
            return FALSE;

        std::vector<ViewItem>::const_iterator it = s_views.begin();
        for (; it != s_views.end(); ++it)
        {
            if (!it->caption.empty())
            {
                CDocument* pDoc = it->pTemplate->OpenDocumentFile(NULL);
                pDoc->SetTitle(it->caption.c_str());
            }
        }
    }

    return ProcessShellCommand();
}
Exemple #14
0
static HRESULT Folder_Constructor(VARIANT *dir, Folder **ppsdf)
{
    FolderImpl *This;
    HRESULT ret;

    *ppsdf = NULL;

    switch (V_VT(dir))
    {
        case VT_I4:
            /* FIXME: add some checks */
            break;
        case VT_BSTR:
            if (PathIsDirectoryW(V_BSTR(dir)) &&
                !PathIsRelativeW(V_BSTR(dir)) &&
                PathFileExistsW(V_BSTR(dir)))
                break;
        default:
            return S_FALSE;
    }

    This = HeapAlloc(GetProcessHeap(), 0, sizeof(FolderImpl));
    if (!This) return E_OUTOFMEMORY;
    This->Folder_iface.lpVtbl = &FolderImpl_Vtbl;
    This->ref = 1;

    ret = load_type_info(&IID_Folder3, &This->iTypeInfo);
    if (FAILED(ret))
    {
        HeapFree(GetProcessHeap(), 0, This);
        return ret;
    }

    VariantInit(&This->dir);
    ret = VariantCopy(&This->dir, dir);
    if (FAILED(ret))
    {
        ITypeInfo_Release(This->iTypeInfo);
        HeapFree(GetProcessHeap(), 0, This);
        return E_OUTOFMEMORY;
    }

    *ppsdf = (Folder*)This;
    return ret;
}
Exemple #15
0
/*
* ClangBuilderEnvironment.ps1
* ClangBuilderManager.ps1
* ClangBuilderBootstrap.ps1
*/
bool SearchClangbuilderPsEngine(std::wstring &psfile, const wchar_t *name)
{
	std::array<wchar_t, PATHCCH_MAX_CCH> engine_;
	GetModuleFileNameW(HINST_THISCOMPONENT, engine_.data(), PATHCCH_MAX_CCH);
	std::wstring tmpfile;
	for (int i = 0; i < 5; i++) {
		if (!PathRemoveFileSpecW(engine_.data())) {
			return false;
		}
		tmpfile.assign(engine_.data());
		tmpfile.append(L"\\bin\\").append(name);
		if (PathFileExistsW(tmpfile.c_str())) {
			psfile.assign(std::move(tmpfile));
			return true;
		}
	}
	return false;
}
Exemple #16
0
Fichier : path.c Projet : cexer/wke
LPWSTR FixupHtmlFilePath(LPWSTR path)
{
    WCHAR fullPath[MAX_PATH + 1] = { 0 };
    LPWSTR fullUrl = NULL;
    
    do
    {
        if (path)
        {
            GetWorkingPath(fullPath, MAX_PATH, path);
            if (PathFileExistsW(fullPath))
                break;

            GetProgramPath(fullPath, MAX_PATH, path);
            if (PathFileExistsW(fullPath))
                break;   
        }

        GetWorkingPath(fullPath, MAX_PATH, L"main.html");
        if (PathFileExistsW(fullPath))
            break;

        GetWorkingPath(fullPath, MAX_PATH, L"wkexe.html");
        if (PathFileExistsW(fullPath))
            break;    

        GetProgramPath(fullPath, MAX_PATH, L"index.html");
        if (PathFileExistsW(fullPath))
            break;    

        GetProgramPath(fullPath, MAX_PATH, L"main.html");
        if (PathFileExistsW(fullPath))
            break;

        GetProgramPath(fullPath, MAX_PATH, L"wkexe.html");
        if (PathFileExistsW(fullPath))
            break;

        return path;
    }
    while (0);

    fullUrl = (WCHAR*)malloc(sizeof(WCHAR) * (MAX_PATH + 1 + 10));
    _snwprintf(fullUrl, MAX_PATH + 1 + 10, L"file:///%s", fullPath);
    return fullUrl;
}
Exemple #17
0
void ExchndlSetup(const char *packageVersion)
{
# if defined(WZ_CC_MINGW)
	wchar_t miniDumpPath[PATH_MAX] = {'\0'};

#ifdef HAVE_BFD
	bfd_init();
#endif /* HAVE_BFD */

	// Install the unhandled exception filter function
	prevExceptionFilter = SetUnhandledExceptionFilter(TopLevelExceptionFilter);

	// Retrieve the current version
	formattedVersionString = strdup(packageVersion);

	// Because of UAC on vista / win7 we use this to write our dumps to (unless we override it via OverrideRPTDirectory())
	// NOTE: CSIDL_PERSONAL =  C:\Users\user name\Documents
	if ( SUCCEEDED( SHGetFolderPathW( NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, miniDumpPath ) ))
	{
		PathAppendW( miniDumpPath, WSTRING(WZ_WRITEDIR));
		PathAppendW( miniDumpPath, L"\\logs" );

		if( !PathFileExistsW( miniDumpPath ) )
		{
			if( ERROR_SUCCESS != SHCreateDirectoryExW( NULL, miniDumpPath, NULL ) )
			{
				wcscpy(miniDumpPath, L"c:\\temp");
			}
		}
	}
	else
	{	// should never fail, but if it does, we fall back to this
		wcscpy(miniDumpPath, L"c:\\temp");
	}

	wcscat(szLogFileName, L"Warzone2100.RPT");
	wcscat(miniDumpPath, L"\\");
	wcscat(miniDumpPath,szLogFileName);
	wcscpy(szLogFileName, miniDumpPath);

	atexit(ExchndlShutdown);
#endif
}
	static std::string FindUserDir()
	{
		wchar_t appdata_path[MAX_PATH];
		if (SHGetFolderPathW(0, CSIDL_PERSONAL, 0, SHGFP_TYPE_CURRENT, appdata_path) != S_OK) {
			Output("Couldn't get user documents folder path\n");
			exit(-1);
		}

		std::wstring path(appdata_path);
		path += L"/Pioneersp";

		if (!PathFileExistsW(path.c_str())) {
			if (SHCreateDirectoryExW(0, path.c_str(), 0) != ERROR_SUCCESS) {
				std::string utf8path = transcode_utf16_to_utf8(path);
				Output("Couldn't create user game folder '%s'", utf8path.c_str());
				exit(-1);
			}
		}

		return transcode_utf16_to_utf8(path);
	}
void  CGameUpdate::UpdateAfter()
{
	//当真正更新了文件(索引在更新前己经被删除),
	//以及版本号不相同(有可能不需要更新(版本号不相同索引也被删除))时,
	//都需要写索引文件,以及动态还原。
	std::wstring idxfile = m_strCliPath + INDEX_FILE_NAMEW;
	if (!PathFileExistsW(idxfile.c_str()))
	{
		//write local idxfile.
		HANDLE hFile = CreateFileW(idxfile.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (hFile != INVALID_HANDLE_VALUE)
		{
			DWORD dwWriteBytes = 0;
			::WriteFile(hFile, m_pIdxfile, m_nIdxfileSize, &dwWriteBytes, NULL);
			SetFileTime(hFile, NULL, NULL, &m_ftIdxfile);
			CloseHandle(hFile);
		}

		//write virtual device idxfile.
		if (_wcsicmp(m_strDevPath.c_str(), m_strCliPath.c_str()) != 0)
		{
			std::wstring devidxfile = m_strDevPath + INDEX_FILE_NAMEW;
			HANDLE hFile = CreateFileW(devidxfile.c_str(), GENERIC_WRITE, 0, NULL, 
				CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
			if (hFile != INVALID_HANDLE_VALUE)
			{
				DWORD dwWriteBytes = 0;
				::WriteFile(hFile, m_pIdxfile, m_nIdxfileSize, &dwWriteBytes, NULL);
				SetFileTime(hFile, NULL, NULL, &m_ftIdxfile);
				CloseHandle(hFile);
			}
		}

		//notify server game update finished.
		m_Server.ReportUpdateFinished(m_dwGid, m_dwSvrIdxVer, m_strCliPath.c_str());

		//hy dynamic execute update directory.
		hy_ExueteUpdateDir(m_strCliPath.c_str());
	}
}
Exemple #20
0
void shell_move_file(const std::string & source, bool unlink_source, const std::string & target) {
  if (std::string(source.begin(), source.begin() + 7) == "file://") {
    const std::string sfp(source.begin() + 7, source.end());

    wchar_t soure_buff[MAX_PATH];
    soure_buff[MultiByteToWideChar(CP_UTF8, 0, sfp.c_str(), sfp.size(), soure_buff, MAX_PATH)] = '\0';

    if (PathFileExistsW(soure_buff) == TRUE) {
      if (std::string(target.begin(), target.begin() + 7) == "file://") {
        const std::string tfp(target.begin() + 7, target.end());

        wchar_t target_buff[MAX_PATH];
        target_buff[MultiByteToWideChar(CP_UTF8, 0, tfp.c_str(), tfp.size(), target_buff, MAX_PATH)] = '\0';

        CopyFileW(soure_buff, target_buff, false);
      }

      if (unlink_source) {
        DeleteFileW(soure_buff);
      }
    }
  }
}
Exemple #21
0
static void copy_file(LPCWSTR source, LPCWSTR destination)
{
    WCHAR destfile[MAX_PATH];

    /* append source filename if destination is a directory */
    if (PathIsDirectoryW(destination))
    {
        PathCombineW(destfile, destination, PathFindFileNameW(source));
        destination = destfile;
    }

    if (PathFileExistsW(destination) && !force_mode)
    {
        static const WCHAR overwriteMsg[] = {'O','v','e','r','w','r','i','t','e',' ','"','%','s','"','?',0};
        static const WCHAR titleMsg[] = {'E','x','t','r','a','c','t',0};
        WCHAR msg[MAX_PATH+100];
        snprintfW(msg, sizeof(msg)/sizeof(msg[0]), overwriteMsg, destination);
        if (MessageBoxW(NULL, msg, titleMsg, MB_YESNO | MB_ICONWARNING) != IDYES)
            return;
    }

    WINE_TRACE("copying %s to %s\n", wine_dbgstr_w(source), wine_dbgstr_w(destination));
    CopyFileW(source, destination, FALSE);
}
void DominoDocArtifact::Upload(const std::wstring& fileToUpload)
{
    if(!PathFileExistsW(fileToUpload.c_str()))
      throw Workshare::System::IO::FileNotFoundException(_bstr_t(fileToUpload.c_str()), _T("Only files that exist can be uploaded to a Lotus Domino Repository"));

   DominoDoc::IDocumentPtr spDocument = GetDocument();      

   wchar_t tempPath[MAX_PATH] = {0};
   if(0 == ::GetTempPathW(MAX_PATH, tempPath))
   {
      DWORD lastError = ::GetLastError();
      std::tostringstream msg;
      msg << _T("Failed to get the temporary path while uploading artifact, ") << m_documentId << _T(", version, ") << m_versionLabel << _T(" which came from repository, ") << m_libraryUrl << std::ends;
      throw Workshare::System::SystemException(msg.str().c_str(), lastError);
   }

   wchar_t tempFileName[_MAX_PATH] = {0};   
   if(0 == GetTempFileNameW(tempPath, L"WC", 0, tempFileName))
   {
      DWORD lastError = ::GetLastError();
      std::tostringstream msg;
      msg << _T("Failed to get the temporary filename while uploading artifact, ") << m_documentId << _T(", version, ") << m_versionLabel << _T(" which came from repository, ") << m_libraryUrl << std::ends;
      throw Workshare::System::SystemException(msg.str().c_str(), lastError);
   }
   DeleteFileW(tempFileName);  
   PathRemoveExtensionW(tempFileName);
   if(!::CreateDirectoryW(tempFileName, NULL))
   {
      DWORD lastError = ::GetLastError();
      std::tostringstream msg;
      msg << _T("Failed to create a temporary directory [") << tempFileName << _T(", to upload [") << fileToUpload << _T("] for uploading artifact, ") << m_documentId << _T(", version, ") << m_versionLabel << _T(" which came from repository, ") << m_libraryUrl << std::ends;
      throw Workshare::System::SystemException(msg.str().c_str(), lastError);
   }

   wchar_t fileName[MAX_PATH] = {0};
   lstrcpyW(fileName, tempFileName);
   if(spDocument->FileName.length() > 0)
      PathAppendW(fileName,spDocument->FileName);
   else
      PathAppendW(fileName, PathFindFileNameW(fileToUpload.c_str()));

   if(!CopyFileW(fileToUpload.c_str(), fileName, TRUE))
   {
      DWORD lastError = ::GetLastError();
      std::tostringstream msg;
      msg << _T("Failed to copy [") << fileToUpload << _T("] to [") << fileName << _T("] while uploading artifact, ") << m_documentId << _T(", version, ") << m_versionLabel << _T(" which came from repository, ") << m_libraryUrl << std::ends;
      throw Workshare::System::SystemException(msg.str().c_str(), lastError);
   }

   try
   {
      spDocument->SetToWorkingCopy();
      spDocument->SetContents(fileName);
      spDocument->Save();
      spDocument->CheckIn(c_revisiontypeDraft, 1, VARIANT_FALSE, "Created By Workshare");        

      wchar_t versionLabel[32] = {0};
      _snwprintf(versionLabel, 32, L"%d.%d", spDocument->VersionNumber, spDocument->DraftNumber);      
      m_versionLabel = versionLabel;

      Log(_T("The file [%S] was uploaded to the Domino.Doc library [%S] as document [%S]"), fileToUpload.c_str(), m_libraryUrl.c_str(), m_documentId.c_str());

      DeleteFileW(fileName);      
      RemoveDirectoryW(tempFileName);
   }
   catch(...)
   {
      DeleteFileW(fileName);
      RemoveDirectoryW(tempFileName);
      throw;
   }   
}
void FileAccessWindows::close() {

	if (!f)
		return;

	fclose(f);
	f = NULL;

	if (save_path != "") {

		bool rename_error = true;
		int attempts = 4;
		while (rename_error && attempts) {
			// This workaround of trying multiple times is added to deal with paranoid Windows
			// antiviruses that love reading just written files even if they are not executable, thus
			// locking the file and preventing renaming from happening.

#ifdef UWP_ENABLED
			// UWP has no PathFileExists, so we check attributes instead
			DWORD fileAttr;

			fileAttr = GetFileAttributesW(save_path.c_str());
			if (INVALID_FILE_ATTRIBUTES == fileAttr) {
#else
			if (!PathFileExistsW(save_path.c_str())) {
#endif
				//creating new file
				rename_error = _wrename((save_path + ".tmp").c_str(), save_path.c_str()) != 0;
			} else {
				//atomic replace for existing file
				rename_error = !ReplaceFileW(save_path.c_str(), (save_path + ".tmp").c_str(), NULL, 2 | 4, NULL, NULL);
			}
			if (rename_error) {
				attempts--;
				OS::get_singleton()->delay_usec(100000); // wait 100msec and try again
			}
		}

		if (rename_error) {
			if (close_fail_notify) {
				close_fail_notify(save_path);
			}

			ERR_EXPLAIN("Safe save failed. This may be a permissions problem, but also may happen because you are running a paranoid antivirus. If this is the case, please switch to Windows Defender or disable the 'safe save' option in editor settings. This makes it work, but increases the risk of file corruption in a crash.");
		}

		save_path = "";

		ERR_FAIL_COND(rename_error);
	}
}

String FileAccessWindows::get_path() const {

	return path_src;
}

String FileAccessWindows::get_path_absolute() const {

	return path;
}

bool FileAccessWindows::is_open() const {

	return (f != NULL);
}
void FileAccessWindows::seek(size_t p_position) {

	ERR_FAIL_COND(!f);
	last_error = OK;
	if (fseek(f, p_position, SEEK_SET))
		check_errors();
}
Exemple #24
0
 inline int PathFileExistsX(const wchar_t* path)
 {
   return TRUE == PathFileExistsW(path);
 }
Exemple #25
0
/* Find path to Dia in the registry and then launch it with the
   passed command line.*/
int LaunchDia(int nArgs, LPWSTR *szArglist, int start_at)
{
    HKEY hRegData;
    char szAppPath[_MAX_PATH];   /* path to exe */
	char szDiaKey[255*2]; /* just incase * 2 */
	char *uri_args = NULL;
	char *uri_args_cpy = NULL;
	char *filename_utf8 = NULL;
	char *filename_uri = NULL;
    DWORD dwSize;
    DWORD dwType = 0;
    DWORD dwDisp;
    int i, iRetCode=-1;
	GError *error = NULL;

    /* Read path to Dia */
    sprintf(szDiaKey, "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\%s", 
            (gUseRegVal) ? gszDiaExe : __argv[1]);

    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, szDiaKey, 0, KEY_READ, &hRegData) == ERROR_SUCCESS)
    {
        dwSize = sizeof(szAppPath);
        if (RegQueryValueEx(hRegData, "", 0, &dwType,
                            (PBYTE)szAppPath, (LPDWORD)&dwSize) == ERROR_SUCCESS)
        {
            /**
	     * Extract the path from where diaw.exe was launched. Could
             * use the path in registry, but you never know where in the
             * string it will be.
	     */
            char szPath[_MAX_PATH]={0};
            char *pEnd = strrchr(szAppPath, '\\');

            /* Could we find last slash? */
            if (pEnd != NULL)
            {
                int len = pEnd-szAppPath;
                
                /* just incase */
                if (len > 0 && len < _MAX_PATH)
                {
                    strncpy(szPath, szAppPath, len);
                }
            }
          
			/**
			 * Create commandline with URIs
			 */
			uri_args_cpy = g_strdup("");
			for(i = start_at; i<nArgs; i++)
			{
				if((0 == wcsncmp(szArglist[i], L"--", 2)) && !PathFileExistsW(szArglist[i]))
				{
					uri_args = g_strdup_printf("%s %s", uri_args_cpy, __argv[i]);
					g_free(uri_args_cpy);
					uri_args_cpy = uri_args;
				}
				else
				{
					filename_utf8 = g_utf16_to_utf8(szArglist[i], -1, NULL, NULL, &error);
					if(error) {
						MessageBox(NULL, "Error converting to UTF-8!", gszVersion, MB_ICONEXCLAMATION);
						g_free(filename_utf8);
						g_free(uri_args);
						g_free(uri_args_cpy);
						return -1;
					}
					
					filename_uri = g_filename_to_uri(filename_utf8, NULL, &error);
					if(error) {
						MessageBox(NULL, "Error converting to URI!", gszVersion, MB_ICONEXCLAMATION);
						g_free(filename_uri);
						g_free(uri_args);
						g_free(uri_args_cpy);					
						g_free(filename_utf8);
						return -1;
					}
					else
					{
						uri_args = g_strdup_printf("%s %s", uri_args_cpy, filename_uri);
						g_free(uri_args_cpy);
						g_free(filename_uri);
						uri_args_cpy = uri_args;
					}
					g_free(filename_utf8);
				}
			}
            /**
	     * Try launching Dia with the passed params.
	     */
            if (ShellExecute(NULL, "open", szAppPath,
                             uri_args, szPath, SW_SHOW) <= (HINSTANCE)32)
            {
                MessageBox(NULL, "Failed to launch Dia!", gszVersion, MB_ICONEXCLAMATION);
            }
            else
            {
                iRetCode = 0;
            }
			g_free(uri_args);
			g_free(uri_args_cpy);
        }
    }
    else
    {
        MessageBox(NULL, "Error reading registry!", gszVersion, MB_ICONSTOP);
    }

    /* close the key */
    RegCloseKey(hRegData);

    return iRetCode;
}
/** 
 * Upload locally built symbols to network symbol storage.
 *
 * Use case:
 *   Game designers use game from source (without prebuild game .dll-files).
 *   In this case all game .dll-files are compiled locally.
 *   For post-mortem debug programmers need .dll and .pdb files from designers.
 */
bool FWindowsPlatformStackWalk::UploadLocalSymbols()
{
	InitStackWalking();

#if WINVER > 0x502
	// Upload locally compiled files to symbol storage.
	FString SymbolStorage;
	if (!GConfig->GetString( CrashReporterSettings, TEXT( "UploadSymbolsPath" ), SymbolStorage, GEditorPerProjectIni ) || SymbolStorage.IsEmpty())
	{
		// Nothing to do.
		return true;
	}
	// Prepare string
	SymbolStorage.ReplaceInline( TEXT( "/" ), TEXT( "\\" ), ESearchCase::CaseSensitive );
	SymbolStorage = TEXT( "SRV*" ) + SymbolStorage;

	int32 ErrorCode = 0;
	HANDLE ProcessHandle = GetCurrentProcess();

	// Enumerate process modules.
	HMODULE* ModuleHandlePointer = GetProcessModules( ProcessHandle );
	if (!ModuleHandlePointer)
	{
		ErrorCode = GetLastError();
		return false;
	}

#if WITH_EDITOR
	// Get Unreal Engine Editor directory for detecting non-game editor binaries.
	FString EnginePath = FPaths::ConvertRelativePathToFull( FPaths::EngineDir() );
	FPaths::MakePlatformFilename( EnginePath );
#endif

	// Upload all locally built modules.
	for (int32 ModuleIndex = 0; ModuleHandlePointer[ModuleIndex]; ModuleIndex++)
	{
		WCHAR ImageName[MAX_PATH] = {0};
		FGetModuleFileNameEx( ProcessHandle, ModuleHandlePointer[ModuleIndex], ImageName, MAX_PATH );

#if WITH_EDITOR
		WCHAR RelativePath[MAX_PATH];
		// Skip binaries inside Unreal Engine Editor directory (non-game editor binaries)
		if (PathRelativePathTo( RelativePath, *EnginePath, FILE_ATTRIBUTE_DIRECTORY, ImageName, 0 ) && FCString::Strncmp( RelativePath, TEXT( "..\\" ), 3 ))
		{
			continue;
		}
#endif

		WCHAR DebugName[MAX_PATH];
		FCString::Strcpy( DebugName, ImageName );

		if (PathRenameExtensionW( DebugName, L".pdb" ))
		{
			// Upload only if found .pdb file
			if (PathFileExistsW( DebugName ))
			{
				// Upload original file
				UE_LOG( LogWindows, Log, TEXT( "Uploading to symbol storage: %s" ), ImageName );
				if (!SymSrvStoreFileW( ProcessHandle, *SymbolStorage, ImageName, SYMSTOREOPT_PASS_IF_EXISTS ))
				{
					UE_LOG( LogWindows, Warning, TEXT( "Uploading to symbol storage failed: %s. Error: %d" ), ImageName, GetLastError() );
				}

				// Upload debug symbols
				UE_LOG( LogWindows, Log, TEXT( "Uploading to symbol storage: %s" ), DebugName );
				if (!SymSrvStoreFileW( ProcessHandle, *SymbolStorage, DebugName, SYMSTOREOPT_PASS_IF_EXISTS ))
				{
					UE_LOG( LogWindows, Warning, TEXT( "Uploading to symbol storage failed: %s. Error: %d" ), DebugName, GetLastError() );
				}
			}
		}
	}
#else
	UE_LOG( LogWindows, Log, TEXT( "Symbol server not supported on Windows XP." ) );
#endif
	return true;
}
Artifact DominoDocArtifact::CreateRelatedItem(const std::wstring& filenameToRelate, const std::wstring& type,const std::wstring& AvailableFileFormats,bool ShowUI)
{
// HACKETY
	UNREFERENCED_PARAMETER(AvailableFileFormats);
	UNREFERENCED_PARAMETER(ShowUI);
   if(0 != lstrcmpiW(type.c_str(), L"W3"))
      throw Workshare::ArgumentException(_T("type"), _T("We only support the W3 type"));

   if(filenameToRelate.empty())
      throw Workshare::ArgumentException(_T("filenameToRelate"), _T("We need a file name to create a related item."));

   if(!PathFileExistsW(filenameToRelate.c_str()))
      throw Workshare::System::IO::FileNotFoundException(_bstr_t(filenameToRelate.c_str()), _T("Only files that exist can be uploaded to a Lotus Domino Repository"));

   DominoDoc::IDocumentPtr spDocument = GetDocument();      

   wchar_t tempPath[MAX_PATH] = {0};
   if(0 == ::GetTempPathW(MAX_PATH, tempPath))
   {
      DWORD lastError = ::GetLastError();
      std::tostringstream msg;
      msg << _T("Failed to get the temporary path while uploading artifact, ") << m_documentId << _T(", version, ") << m_versionLabel << _T(" which came from repository, ") << m_libraryUrl << std::ends;
      throw Workshare::System::SystemException(msg.str().c_str(), lastError);
   }

   wchar_t tempFileName[_MAX_PATH] = {0};   
   if(0 == GetTempFileNameW(tempPath, L"WC", 0, tempFileName))
   {
      DWORD lastError = ::GetLastError();
      std::tostringstream msg;
      msg << _T("Failed to get the temporary filename while uploading artifact, ") << m_documentId << _T(", version, ") << m_versionLabel << _T(" which came from repository, ") << m_libraryUrl << std::ends;
      throw Workshare::System::SystemException(msg.str().c_str(), lastError);
   }
   DeleteFileW(tempFileName);  
   PathRemoveExtensionW(tempFileName);
   if(!::CreateDirectoryW(tempFileName, NULL))
   {
      DWORD lastError = ::GetLastError();
      std::tostringstream msg;
      msg << "Failed to create a temporary directory [" << tempFileName << ", to upload [" << filenameToRelate << "] for uploading artifact, " << m_documentId << ", version, " << m_versionLabel << " which came from repository, " << m_libraryUrl << std::ends;
	  throw Workshare::System::SystemException(msg.str().c_str(), lastError);
   }

   wchar_t fileName[MAX_PATH] = {0};
   lstrcpyW(fileName, tempFileName);
   if(spDocument->FileName.length() > 0)
      PathAppendW(fileName,spDocument->FileName);
   else
      PathAppendW(fileName, PathFindFileNameW(filenameToRelate.c_str()));

   PathRemoveExtensionW(fileName);
   lstrcatW(fileName, L".");
   lstrcatW(fileName, type.c_str());   

   if(!CopyFileW(filenameToRelate.c_str(), fileName, TRUE))
   {
      DWORD lastError = ::GetLastError();
      std::tostringstream msg;
      msg << _T("Failed to copy [") << filenameToRelate << _T("] to [") << fileName << _T("] while uploading artifact, ") << m_documentId << _T(", version, ") << m_versionLabel << _T(" which came from repository, ") << m_libraryUrl << std::ends;
      throw Workshare::System::SystemException(msg.str().c_str(), lastError);
   }

   try
   {
      DominoDoc::IBinderPtr spBinder = spDocument->Binder;
      DominoDoc::IDocumentsPtr spDocuments = spBinder->Documents;
      DominoDoc::IDocumentPtr spRelatedDocument = spDocuments->Add();

      std::wstring title = this->Name + L".W3";
      spRelatedDocument->Title = title.c_str();
      spRelatedDocument->Description = L"File Used by workshare during the collaboration process";
      spRelatedDocument->SetContents(fileName);
      spRelatedDocument->Save(); 
      spRelatedDocument->CheckIn(c_revisiontypeVersion, c_actionReplace, VARIANT_TRUE, _T("Workshare Collaboration Document")); 
      
      DeleteFileW(fileName);      
      RemoveDirectoryW(tempFileName);

      return new DominoDocArtifact(spRelatedDocument);
   }
   catch(...)
   {
      DeleteFileW(fileName);
      RemoveDirectoryW(tempFileName);
      throw;
   }  
}
Exemple #28
0
void ExchndlSetup(const char *packageVersion)
{
# if defined(WZ_CC_MINGW)
	wchar_t miniDumpPath[PATH_MAX] = {'\0'};
	DWORD dwRetVal = 0;
#ifdef HAVE_BFD
	bfd_init();
#endif /* HAVE_BFD */

	// Install the unhandled exception filter function
	prevExceptionFilter = SetUnhandledExceptionFilter(TopLevelExceptionFilter);

	// Retrieve the current version
	formattedVersionString = strdup(packageVersion);
#ifndef WZ_PORTABLE
	// Because of UAC on vista / win7 we use this to write our dumps to (unless we override it via OverrideRPTDirectory())
	// NOTE: CSIDL_PERSONAL =  C:\Users\user name\Documents
	if ( SUCCEEDED( SHGetFolderPathW( NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, miniDumpPath ) ))
	{
		PathAppendW( miniDumpPath, WSTRING(WZ_WRITEDIR));
		PathAppendW( miniDumpPath, L"\\logs" );

		if( !PathFileExistsW( miniDumpPath ) )
		{
			if( ERROR_SUCCESS != SHCreateDirectoryExW( NULL, miniDumpPath, NULL ) )
			{
				//last attempt to get a path
				dwRetVal = GetTempPathW(PATH_MAX, miniDumpPath);
				if (dwRetVal > MAX_PATH || (dwRetVal == 0))
				{
					MessageBox((HWND)MB_ICONEXCLAMATION, "Could not created a temporary directory!\nProgram will now exit." , _T("Error"), MB_OK);
					exit(1);
				}
			}
		}
	}
#else
	// we use where they installed it on, since this is a removeable drive (most likely), we will use where the program is located in.
	if (dwRetVal = GetCurrentDirectoryW(MAX_PATH, miniDumpPath))
	{
		if(dwRetVal > MAX_PATH)
		{
			MessageBox((HWND)MB_ICONEXCLAMATION, "Buffer exceeds maximum path to create directory.  Exiting.", _T("Error"), MB_OK);
			exit(1);
		}
		PathAppendW( miniDumpPath, WSTRING(WZ_WRITEDIR));
		PathAppendW( miniDumpPath, L"\\logs" );
	}
#endif
	else
	{	// should never fail, but if it does, we fall back to this
		dwRetVal = GetTempPathW(PATH_MAX, miniDumpPath);
		if (dwRetVal > MAX_PATH || (dwRetVal == 0))
		{
			MessageBox((HWND)MB_ICONEXCLAMATION, "Could not created a temporary directory!\nProgram will now exit." , _T("Error!"), MB_OK);
			exit(1);
		}
	}

	wcscat(szLogFileName, L"Warzone2100.RPT");
	wcscat(miniDumpPath, L"\\");
	wcscat(miniDumpPath,szLogFileName);
	wcscpy(szLogFileName, miniDumpPath);

	atexit(ExchndlShutdown);
#endif
}
Exemple #29
0
int main()
{
    LPWSTR *argv; int argc;

    argv = CommandLineToArgvW(GetCommandLineW(), &argc);
    if(argv == NULL) {
        error("Error parsing commandline options!\n");
    }

    if(argc < 4) {
        error(
            "Usage: %S <options..>\n"
            "Options:\n"
            "  --crt                  CreateRemoteThread injection\n"
            "  --apc                  QueueUserAPC injection\n"
            "  --free                 Do not inject our monitor\n"
            "  --dll <dll>            DLL to inject\n"
            "  --app <app>            Path to application to start\n"
            "  --args <args>          Command-line arguments\n"
            "                         Excluding the application path!\n"
            "  --curdir <dirpath>     Current working directory\n"
            "  --maximize             Maximize the newly created GUI\n"
            "  --pid <pid>            Process identifier to inject\n"
            "  --process-name <name>  Process name to inject\n"
            "  --tid <tid>            Thread identifier to inject\n"
            "  --from <pid>           Inject from another process\n"
            "  --from-process <name>  "
            "Inject from another process, resolves pid\n"
            "  --only-start           "
            "Start the application and print pid/tid\n"
            "  --resume-thread        "
            "Resume the thread of the pid/tid target\n"
            "  --config <path>        "
            "Configuration file for the monitor\n"
            "  --dbg <path>           "
            "Attach debugger to target process\n"
            "  --dump <filepath>      "
            "Dump process memory with --pid to filepath\n"
            "  --verbose              Verbose switch\n",
            argv[0]
        );
    }

    const wchar_t *dll_path = NULL, *app_path = NULL, *arguments = L"";
    const wchar_t *config_file = NULL, *from_process = NULL, *dbg_path = NULL;
    const wchar_t *curdir = NULL, *process_name = NULL, *dump_path = NULL;
    uint32_t pid = 0, tid = 0, from = 0, inj_mode = INJECT_NONE;
    uint32_t show_window = SW_SHOWNORMAL, only_start = 0, resume_thread_ = 0;

    for (int idx = 1; idx < argc; idx++) {
        if(wcscmp(argv[idx], L"--crt") == 0) {
            inj_mode = INJECT_CRT;
            continue;
        }

        if(wcscmp(argv[idx], L"--apc") == 0) {
            inj_mode = INJECT_APC;
            continue;
        }

        if(wcscmp(argv[idx], L"--free") == 0) {
            inj_mode = INJECT_FREE;
            continue;
        }

        if(wcscmp(argv[idx], L"--dll") == 0) {
            dll_path = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--app") == 0) {
            app_path = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--args") == 0) {
            arguments = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--curdir") == 0) {
            curdir = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--maximize") == 0) {
            show_window = SW_MAXIMIZE;
            continue;
        }

        if(wcscmp(argv[idx], L"--pid") == 0) {
            pid = wcstol(argv[++idx], NULL, 10);
            continue;
        }

        if(wcscmp(argv[idx], L"--process-name") == 0) {
            process_name = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--tid") == 0) {
            tid = wcstol(argv[++idx], NULL, 10);
            continue;
        }

        if(wcscmp(argv[idx], L"--from") == 0) {
            from = wcstol(argv[++idx], NULL, 10);
            continue;
        }

        if(wcscmp(argv[idx], L"--from-process") == 0) {
            from_process = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--only-start") == 0) {
            only_start = 1;
            continue;
        }

        if(wcscmp(argv[idx], L"--resume-thread") == 0) {
            resume_thread_ = 1;
            continue;
        }

        if(wcscmp(argv[idx], L"--config") == 0) {
            config_file = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--dbg") == 0) {
            dbg_path = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--dump") == 0) {
            dump_path = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--verbose") == 0) {
            verbose = 1;
            continue;
        }

        error("[-] Found unsupported argument: %S\n", argv[idx]);
        return 1;
    }

    // Dump memory of a process.
    if(dump_path != NULL && pid != 0) {
        dump(pid, dump_path);
        return 0;
    }

    if(inj_mode == INJECT_NONE) {
        error("[-] No injection method has been provided!\n");
    }

    if(inj_mode == INJECT_CRT && pid == 0 && process_name == NULL &&
            app_path == NULL) {
        error("[-] No injection target has been provided!\n");
    }

    if(inj_mode == INJECT_APC && tid == 0 && process_name == NULL &&
            app_path == NULL) {
        error("[-] No injection target has been provided!\n");
    }

    if(inj_mode == INJECT_FREE && app_path == NULL) {
        error("[-] An app path is required when not injecting!\n");
    }

    if(pid != 0 && process_name != NULL) {
        error("[-] Both pid and process-name were set!\n");
    }

    static wchar_t dllpath[MAX_PATH_W];

    if(inj_mode == INJECT_FREE) {
        if(dll_path != NULL || tid != 0 || pid != 0) {
            error("[-] Unused --tid/--pid/--dll provided in --free mode!\n");
        }
    }

    if(inj_mode != INJECT_FREE) {
        if(PathFileExistsW(dll_path) == FALSE) {
            error("[-] Invalid DLL filepath has been provided\n");
        }

        if(GetFullPathNameW(dll_path, MAX_PATH_W, dllpath, NULL) == 0) {
            error("[-] Invalid DLL filepath has been provided\n");
        }

        if(GetLongPathNameW(dllpath, dllpath, MAX_PATH_W) == 0) {
            error("[-] Error obtaining the dll long path name\n");
        }
    }

    if(from != 0 && from_process != NULL) {
        error("[-] Both --from and --from-process are specified\n");
    }

    grant_debug_privileges(GetCurrentProcessId());

    if(app_path != NULL) {
        // If a process name has been provided as source process, then find
        // its process identifier (or first, if multiple).
        if(from_process != NULL) {
            from = pid_from_process_name(from_process);
        }

        // If no source process has been specified, then we use our
        // own process.
        if(from == 0) {
            from = GetCurrentProcessId();
        }

        if(PathFileExistsW(app_path) == FALSE) {
            error("[-] Invalid app filepath has been provided\n");
        }

        static wchar_t dirpath[MAX_PATH_W], filepath[MAX_PATH_W];

        // If a current working directory has been set then we use that
        // current working directory. Otherwise default to $TEMP.
        if(curdir != NULL) {
            // Allow the current working directory to be
            // specified as, e.g., %TEMP%.
            if(ExpandEnvironmentStringsW(curdir, dirpath, MAX_PATH_W) == 0) {
                error("[-] Error expanding environment variables\n");
            }

            curdir = dirpath;
        }
        else {
            // We don't want to be expanding the environment variable buffer
            // as that will probably corrupt the heap or so.
            curdir = wcscpy(dirpath, _wgetenv(L"TEMP"));
        }

        if(GetLongPathNameW(dirpath, dirpath, MAX_PATH_W) == 0) {
            error("[-] Error obtaining the curdir long path name\n");
        }

        if(GetFullPathNameW(app_path, MAX_PATH_W, filepath, NULL) == 0) {
            error("[-] Invalid app filepath has been provided\n");
        }

        if(GetLongPathNameW(filepath, filepath, MAX_PATH_W) == 0) {
            error("[-] Error obtaining the app long path name\n");
        }

        pid = start_app(from, filepath, arguments, curdir, &tid, show_window);
    }

    if(pid == 0 && process_name != NULL) {
        pid = pid_from_process_name(process_name);
    }

    // Drop the configuration file if available.
    if(config_file != NULL) {
        static wchar_t filepath[MAX_PATH_W];

        wsprintfW(filepath, L"C:\\cuckoo_%d.ini", pid);
        if(MoveFileW(config_file, filepath) == FALSE) {
            error("[-] Error dropping configuration file: %ld\n",
                GetLastError());
        }
    }

    // Do not do actual injection here, just have the application launched.
    if(only_start != 0) {
        printf("%d %d", pid, tid);
        return 0;
    }

    switch (inj_mode) {
    case INJECT_CRT:
        load_dll_crt(pid, dllpath);
        break;

    case INJECT_APC:
        load_dll_apc(pid, tid, dllpath);
        break;

    case INJECT_FREE:
        break;

    default:
        error("[-] Unhandled injection mode: %d\n", inj_mode);
    }

    if(dbg_path != NULL) {
        wchar_t buf[1024];
        wsprintfW(buf, L"\"%s\" -p %d", dbg_path, pid);

        start_app(GetCurrentProcessId(), dbg_path, buf,
            NULL, NULL, SW_SHOWNORMAL);

        Sleep(5000);
    }

    if((app_path != NULL || resume_thread_ != 0) && tid != 0) {
        resume_thread(tid);
    }

    // Report the process identifier.
    printf("%d", pid);
    return 0;
}
Exemple #30
0
/*
    010512 Carl Corcoran
*/
BOOL CCString::Path_FileExists()
{
    return PathFileExistsW(this->wszString);
}