Beispiel #1
0
/**
 * Obtains the path of a file in the same directory as the specified file.
 *
 * @param  destinationBuffer A buffer of size MAX_PATH + 1 to store the result.
 * @param  siblingFIlePath   The path of another file in the same directory
 * @param  newFileName       The filename of another file in the same directory
 * @return TRUE if successful
 */
BOOL
PathGetSiblingFilePath(LPWSTR destinationBuffer,
                       LPCWSTR siblingFilePath,
                       LPCWSTR newFileName)
{
  if (wcslen(siblingFilePath) >= MAX_PATH) {
    return FALSE;
  }

  wcsncpy(destinationBuffer, siblingFilePath, MAX_PATH);
  if (!PathRemoveFileSpecW(destinationBuffer)) {
    return FALSE;
  }

  if (wcslen(destinationBuffer) + wcslen(newFileName) >= MAX_PATH) {
    return FALSE;
  }

  return PathAppendSafe(destinationBuffer, newFileName);
}
Beispiel #2
0
BOOL PathToCombineW(LPWSTR lpfile, size_t str_len)
{
    size_t n = 1;
    if ( lpfile[0] == L'%' )
    {
        WCHAR buf_env[VALUE_LEN+1] = {0};
        while ( lpfile[n] != L'\0' )
        {
            if ( lpfile[n] == L'%' )
            {
                break;
            }
            ++n;
        }
        if ( n < str_len )
        {
            _snwprintf(buf_env, n+1 ,L"%ls", lpfile);
        }
        if ( wcslen(buf_env) > 1 && ExpandEnvironmentStringsW(buf_env,buf_env,VALUE_LEN) > 0 )
        {
            WCHAR tmp_env[VALUE_LEN+1] = {0};
            _snwprintf(tmp_env, str_len ,L"%ls%ls", buf_env, &lpfile[n+1]);
            n = _snwprintf(lpfile, str_len ,L"%ls", tmp_env);
        }
    }
    if ( lpfile[1] != L':' )
    {
        WCHAR buf_modname[VALUE_LEN+1] = {0};
        charTochar(lpfile);
        if ( GetModuleFileNameW( dll_module, buf_modname, VALUE_LEN) > 0)
        {
            WCHAR tmp_path[MAX_PATH] = {0};
            PathRemoveFileSpecW(buf_modname);
            if ( PathCombineW(tmp_path,buf_modname,lpfile) )
            {
                n = _snwprintf(lpfile,str_len,L"%ls",tmp_path);
            }
        }
    }
    return (n>0);
}
bool OverrideRPTDirectory(char *newPath)
{
# if defined(WZ_CC_MINGW)
	wchar_t buf[MAX_PATH];

	if (!MultiByteToWideChar(CP_UTF8, 0, newPath, -1, buf, MAX_PATH))
	{
		//conversion failed-- we won't use the user's directory.

		LPVOID lpMsgBuf;
		DWORD dw = GetLastError();
		TCHAR szBuffer[4196];

		FormatMessage(
		    FORMAT_MESSAGE_ALLOCATE_BUFFER |
		    FORMAT_MESSAGE_FROM_SYSTEM |
		    FORMAT_MESSAGE_IGNORE_INSERTS,
		    NULL,
		    dw,
		    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		    (LPTSTR) &lpMsgBuf,
		    0, NULL);

		wsprintf(szBuffer, _T("Exception handler failed setting new directory with error %d: %s\n"), dw, lpMsgBuf);
		MessageBox((HWND)MB_ICONEXCLAMATION, szBuffer, _T("Error"), MB_OK);

		LocalFree(lpMsgBuf);

		return false;
	}
	PathRemoveFileSpecW(buf);
	wcscat(buf, L"\\logs\\"); // stuff it in the logs directory
	wcscat(buf, L"Warzone2100.RPT");
	ResetRPTDirectory(buf);
#elif defined(WZ_OS_UNIX) && !defined(WZ_OS_MAC)
	sstrcpy(WritePath, newPath);
#endif
	return true;
}
Beispiel #4
0
void GBAConfigDirectory(char* out, size_t outLength) {
	struct VFile* portable;
#ifndef _WIN32
	getcwd(out, outLength);
	strncat(out, PATH_SEP "portable.ini", outLength - strlen(out));
	portable = VFileOpen(out, O_RDONLY);
	if (portable) {
		getcwd(out, outLength);
		portable->close(portable);
		return;
	}

	char* home = getenv("HOME");
	snprintf(out, outLength, "%s/.config", home);
	mkdir(out, 0755);
        snprintf(out, outLength, "%s/.config/%s", home, binaryName);
	mkdir(out, 0755);
#else
	wchar_t wpath[MAX_PATH];
	wchar_t wprojectName[MAX_PATH];
	MultiByteToWideChar(CP_UTF8, 0, projectName, -1, wprojectName, MAX_PATH);
	HMODULE hModule = GetModuleHandleW(NULL);
	GetModuleFileNameW(hModule, wpath, MAX_PATH);
	PathRemoveFileSpecW(wpath);
	WideCharToMultiByte(CP_UTF8, 0, wpath, -1, out, outLength, 0, 0);
	StringCchCatA(out, outLength, "\\portable.ini");
	portable = VFileOpen(out, O_RDONLY);
	if (portable) {
		portable->close(portable);
	} else {
		wchar_t* home;
		SHGetKnownFolderPath(&FOLDERID_RoamingAppData, 0, NULL, &home);
		StringCchPrintfW(wpath, MAX_PATH, L"%ws\\%ws", home, wprojectName);
		CoTaskMemFree(home);
		CreateDirectoryW(wpath, NULL);
	}
	WideCharToMultiByte(CP_UTF8, 0, wpath, -1, out, outLength, 0, 0);
#endif
}
int __stdcall WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nShowCmd)
{
	std::wstring wsIni(512, 0);
	GetModuleFileName(hInstance, &wsIni[0], 511);
	PathRemoveExtension(&wsIni[0]);
	wcscat(&wsIni[0], L".ini");

	std::wstring wcRunPath(512, 0);
	GetModuleFileName(hInstance, &wcRunPath[0], 511);
	PathRemoveFileSpecW(&wcRunPath[0]);

	std::wstring wcExe(512, 0);
	GetModuleFileName(hInstance, &wcExe[0], 511);

	OptionsHelper oh(wsIni, wcExe);
	SoundHelper sh(wcRunPath + L"\\resources\\error.wav", wcRunPath + L"\\resources\\switch.wav");

	g_switcher = std::unique_ptr<Switcher>(new Switcher(oh, sh));

	g_bHookActive = true;

	g_hKbdHook = SetWindowsHookEx(WH_KEYBOARD_LL, SwitcherKeyboardHook, hInstance, NULL);
	g_switcher->Enable();
	// assert

	if (!IsDebuggerPresent()) g_hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, SwitcherMouseHook, hInstance, NULL);
	// assert

	AppDlg dlg(hInstance, *g_switcher, oh);
	dlg.ShowDlg();

	g_bHookActive = false;
	UnhookWindowsHookEx(g_hKbdHook);
	if (!IsDebuggerPresent()) UnhookWindowsHookEx(g_hMouseHook);

	oh.SaveOptions();

	return 0;
}
	static bool make_directory_raw(std::wstring path)
	{
		// allow multiple tries (to build parent directories)
		while (true) {
			if (!CreateDirectoryW(path.c_str(), 0)) {
				DWORD err = GetLastError();
				if (err == ERROR_ALREADY_EXISTS) {
					DWORD attrs = GetFileAttributesW(path.c_str());
					return ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY);
				} else if (err == ERROR_PATH_NOT_FOUND) {
					if (!PathRemoveFileSpecW(&path[0]))
						return false;
					path.resize(wcslen(&path[0]));
					if (!path.empty() || !make_directory_raw(path)) {
						return false;
					}
				} else {
					Output("error while attempting to create directory '%s'\n", transcode_utf16_to_utf8(path).c_str());
					return false;
				}
			}
		}
	}
Beispiel #7
0
void GBAConfigMakePortable(const struct GBAConfig* config) {
	struct VFile* portable;
#ifndef _WIN32
	char out[PATH_MAX];
	getcwd(out, PATH_MAX);
	strncat(out, PATH_SEP "portable.ini", PATH_MAX - strlen(out));
	portable = VFileOpen(out, O_WRONLY | O_CREAT);
#else
	char out[MAX_PATH];
	wchar_t wpath[MAX_PATH];
	wchar_t wprojectName[MAX_PATH];
	MultiByteToWideChar(CP_UTF8, 0, projectName, -1, wprojectName, MAX_PATH);
	HMODULE hModule = GetModuleHandleW(NULL);
	GetModuleFileNameW(hModule, wpath, MAX_PATH);
	PathRemoveFileSpecW(wpath);
	WideCharToMultiByte(CP_UTF8, 0, wpath, -1, out, MAX_PATH, 0, 0);
	StringCchCatA(out, MAX_PATH, "\\portable.ini");
	portable = VFileOpen(out, O_WRONLY | O_CREAT);
#endif
	if (portable) {
		portable->close(portable);
		GBAConfigSave(config);
	}
}
Beispiel #8
0
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd)
{
    INITCOMMONCONTROLSEX icc = { 0 };
    struct CONVERT_CB_DATA conv = { 0 };
    LPWSTR lpBrowseResult = NULL;
    WCHAR szwExePath[MAX_PATH] = { 0 };
    WCHAR szwDest[MAX_PATH] = { 0 };
    DWORD nTotal = 0;
    DWORD nConverted = 0;
    HWND hwndProgressDlg = NULL;
    HICON hIcon = NULL;
    BOOL bEnd = FALSE;
    MSG msg = { 0 };

    icc.dwSize = sizeof(INITCOMMONCONTROLSEX);
    icc.dwICC  = ICC_LINK_CLASS;
    InitCommonControlsEx(&icc);

    // Select .h3m files to convert
    lpBrowseResult = UtilBrowseForMultipleFiles(MSG_BROWSE, L"H3C (*.h3c)\0*.h3c\0", &nTotal);
    if (NULL == lpBrowseResult)
    {
        return 1;
    }

    // Obtain own path, establish conversion destination subfolder \\converted
    GetModuleFileNameW(GetModuleHandle(NULL), szwExePath, MAX_PATH);
    PathRemoveFileSpecW(szwExePath);
    _snwprintf(szwDest, sizeof(szwDest) / sizeof(szwDest[0]) - 1, L"%s\\converted", szwExePath);
    CreateDirectoryW(szwDest, NULL);

    // Create conversion progress dialog
    hIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1));
    hwndProgressDlg = progress_dialog_init(TITLE_INITIAL, hIcon);
    DestroyIcon(hIcon);

    // Start conversion thread
    conv.dwMainThreadId = GetCurrentThreadId();
    conv.lpSrc = lpBrowseResult;
    conv.lpDest = szwDest;
    CloseHandle(CreateThread(NULL, 0, _ConvertThreadProc, (LPVOID)&conv, 0, NULL));

    while (GetMessage(&msg, NULL, 0, 0) > 0)
    {
        switch (msg.message)
        {
        case WM_SKIPPED_MAP:
            // First string in lpBrowseResult is source path
            CopySkippedMap(szwDest, lpBrowseResult, (LPCWSTR)msg.wParam);
            // Fall-through
        case WM_FAILED_MAP:
        case WM_CONVERTED_MAP:
            ++nConverted;
            UpdateGui(hwndProgressDlg, nConverted, nTotal, (LPCWSTR)msg.wParam);
            if (0 != msg.wParam)
            {
                free((LPWSTR *)msg.wParam);
            }
            break;
        case WM_CONVERTED_ALL:
            bEnd = TRUE;
            break;
        }

        if (TRUE == bEnd)
            break;

        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    // Close progress dialog and show conversion results
    DestroyWindow(hwndProgressDlg);
    _ShowDetails(&conv, szwDest);

    // Cleanup
    HeapFree(GetProcessHeap(), 0, lpBrowseResult);

    return 0;
}
Beispiel #9
0
HRESULT CLAVAudio::InitDTSDecoder()
{
  if (!m_hDllExtraDecoder) {
    // Add path of LAVAudio.ax into the Dll search path
    WCHAR wModuleFile[1024];
    GetModuleFileName(g_hInst, wModuleFile, 1024);
    PathRemoveFileSpecW(wModuleFile);
    wcscat_s(wModuleFile, TEXT("\\dtsdecoderdll.dll"));

    // Try loading from the filters directory
    HMODULE hDll = LoadLibraryEx(wModuleFile, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
    // And try from any global directories if this failed
    if (hDll == nullptr) {
      hDll = LoadLibrary(TEXT("dtsdecoderdll.dll"));
    }
    CheckPointer(hDll, E_FAIL);

    BOOL bIncompatibleDecoder = FALSE;
    if (GetModuleFileName(hDll, wModuleFile, 1024) > 0) {
      DWORD dwVersionSize = GetFileVersionInfoSize(wModuleFile, nullptr);
      if (dwVersionSize > 0) {
        void *versionInfo = CoTaskMemAlloc(dwVersionSize);
        BOOL bVersionInfoPresent = GetFileVersionInfo(wModuleFile, 0, dwVersionSize, versionInfo);
        if (bVersionInfoPresent) {
          VS_FIXEDFILEINFO *info;
          unsigned cbInfo;
          BOOL bInfoPresent = VerQueryValue(versionInfo, TEXT("\\"), (LPVOID*)&info, &cbInfo);
          if (bInfoPresent) {
            bInfoPresent = bInfoPresent;
            uint64_t version = info->dwFileVersionMS;
            version <<= 32;
            version += info->dwFileVersionLS;
            if (version && version < 0x0001000100000000i64)
              bIncompatibleDecoder = TRUE;
          }
        }
        CoTaskMemFree(versionInfo);
      }

    }

    if (bIncompatibleDecoder) {
      FreeLibrary(hDll);
      hDll = nullptr;
      return E_FAIL;
    }

    m_hDllExtraDecoder = hDll;
  }

  DTSDecoder *context = new DTSDecoder();

  context->pDtsOpen = (DtsOpen)GetProcAddress(m_hDllExtraDecoder, "DtsApiDecOpen");
  if(!context->pDtsOpen) goto fail;

  context->pDtsClose = (DtsClose)GetProcAddress(m_hDllExtraDecoder, "DtsApiDecClose");
  if(!context->pDtsClose) goto fail;

  context->pDtsReset = (DtsReset)GetProcAddress(m_hDllExtraDecoder, "DtsApiDecReset");
  if(!context->pDtsReset) goto fail;

  context->pDtsSetParam = (DtsSetParam)GetProcAddress(m_hDllExtraDecoder, "DtsApiDecSetParam");
  if(!context->pDtsSetParam) goto fail;

  context->pDtsDecode = (DtsDecode)GetProcAddress(m_hDllExtraDecoder, "DtsApiDecodeData");
  if(!context->pDtsDecode) goto fail;

  context->dtsContext = context->pDtsOpen();
  if(!context->dtsContext) goto fail;

  context->dtsPCMBuffer = (BYTE *)av_mallocz(LAV_AUDIO_BUFFER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);

  m_DTSBitDepth = 24;
  m_DTSDecodeChannels = 8;

  m_pDTSDecoderContext = context;

  FlushDTSDecoder();

  return S_OK;
fail:
  SAFE_DELETE(context);
  FreeLibrary(m_hDllExtraDecoder);
  m_hDllExtraDecoder = nullptr;
  return E_FAIL;
}
Beispiel #10
0
/*
    010509 Carl Corcoran
*/
void CCString::Path_StripToPath()
{
    PathRemoveFileSpecW(this->wszString);
}
Beispiel #11
0
/*************************************************************************
 * PathRemoveFileSpec [SHELL32.35]
 */
BOOL WINAPI PathRemoveFileSpecAW(LPVOID lpszPath)
{
	if (SHELL_OsIsUnicode())
	  return PathRemoveFileSpecW(lpszPath);
	return PathRemoveFileSpecA(lpszPath);
}
Beispiel #12
0
/**
 * Updates the service description with what is stored in updater.ini
 * at the same path as the currently executing module binary.
 *
 * @param serviceHandle A handle to an opened service with 
 *                      SERVICE_CHANGE_CONFIG access right
 * @param TRUE on succcess.
*/
BOOL
UpdateServiceDescription(SC_HANDLE serviceHandle)
{
  WCHAR updaterINIPath[MAX_PATH + 1];
  if (!GetModuleFileNameW(NULL, updaterINIPath, 
                          sizeof(updaterINIPath) /
                          sizeof(updaterINIPath[0]))) {
    LOG(("Could not obtain module filename when attempting to "
         "modify service description. (%d)\n", GetLastError()));
    return FALSE;
  }

  if (!PathRemoveFileSpecW(updaterINIPath)) {
    LOG(("Could not remove file spec when attempting to "
         "modify service description. (%d)\n", GetLastError()));
    return FALSE;
  }

  if (!PathAppendSafe(updaterINIPath, L"updater.ini")) {
    LOG(("Could not append updater.ini filename when attempting to "
         "modify service description. (%d)\n", GetLastError()));
    return FALSE;
  }

  if (GetFileAttributesW(updaterINIPath) == INVALID_FILE_ATTRIBUTES) {
    LOG(("updater.ini file does not exist, will not modify "
         "service description. (%d)\n", GetLastError()));
    return FALSE;
  }
  
  MaintenanceServiceStringTable serviceStrings;
  int rv = ReadMaintenanceServiceStrings(updaterINIPath, &serviceStrings);
  if (rv != OK || !strlen(serviceStrings.serviceDescription)) {
    LOG(("updater.ini file does not contain a maintenance "
         "service description.\n"));
    return FALSE;
  }

  WCHAR serviceDescription[MAX_TEXT_LEN];
  if (!MultiByteToWideChar(CP_UTF8, 0, 
                           serviceStrings.serviceDescription, -1,
                           serviceDescription,
                           sizeof(serviceDescription) / 
                           sizeof(serviceDescription[0]))) {
    LOG(("Could not convert description to wide string format (%d)\n", 
         GetLastError()));
    return FALSE;
  }

  SERVICE_DESCRIPTIONW descriptionConfig;
  descriptionConfig.lpDescription = serviceDescription;
  if (!ChangeServiceConfig2W(serviceHandle, 
                             SERVICE_CONFIG_DESCRIPTION, 
                             &descriptionConfig)) {
    LOG(("Could not change service config (%d)\n", GetLastError()));
    return FALSE;
  }

  LOG(("The service description was updated successfully.\n"));
  return TRUE;
}
Beispiel #13
0
bool PathRemoveFileSpec(wchar_t* path)
{
	return PathRemoveFileSpecW(path);
}
//
// Process Auto Config options:
// #1 search for '/noconfig'
// if not present and csc.cfg exists in EXE dir, inject after env var stuff
//
void ConsoleArgs::ProcessAutoConfig()
{
    bool fFoundNoConfig = false;

    // Scan the argument list for the "/noconfig" options. If present, just kill it and bail.
    for (WStrList * listArgCur = m_listArgs; listArgCur; listArgCur = listArgCur->next)
    {
        // Skip everything except options
        WCHAR * szArg = listArgCur->arg;
        if (szArg == NULL || (szArg[0] != '/' && szArg[0] != '-'))
            continue;

        if (_wcsicmp(szArg + 1, L"noconfig") == 0) {
            listArgCur->arg = NULL;
            VSFree(szArg);
            // We found it, empty it but keep checking in case they specified it twice
            fFoundNoConfig = true;
        }
    }

    if (fFoundNoConfig)
        return;

    // If we got here it means there was no '/noconfig'
    WCHAR szPath[MAX_PATH];
    if (W_IsUnicodeSystem()) {
        if(!GetModuleFileNameW(NULL, szPath, lengthof(szPath)))
            szPath[0] = 0;
    } else {
        CHAR szTemp[MAX_PATH];
        if (!GetModuleFileNameA(NULL, szTemp, lengthof(szTemp)) ||
            !MultiByteToWideChar( AreFileApisANSI() ? CP_ACP : CP_OEMCP,
                0, szTemp, -1, szPath, lengthof(szPath)))
            szPath[0] = 0;
    }
    if (*szPath && PathRemoveFileSpecW(szPath) &&
        PathAppendW(szPath, L"csc.rsp")) {

        if (W_Access( szPath, 4) == 0) { 
            // We know the file exists and that we have read access
            // so add into the list
            size_t cchLen = wcslen(szPath) + 2; // +2 for @ and terminator
            WCHAR * szPathCopy = (WCHAR*)VSAlloc( sizeof(WCHAR) * cchLen);
            if (!szPathCopy || FAILED(StringCchCopyW(szPathCopy + 1, cchLen, szPath))) {
                VSFAIL("The string changed size, or our pointers got messed up");
                m_output->ShowErrorId(FTL_NoMemory, ERROR_FATAL);
                return;
            }
            szPathCopy[0] = L'@';

            WStrList * listArgNew = new WStrList( szPathCopy, m_listArgs);
            if (!listArgNew) {
                VSFree(szPathCopy);
                m_output->ShowErrorId(FTL_NoMemory, ERROR_FATAL);
                return;
            }

            m_listArgs = listArgNew;
        }
    }
}
Beispiel #15
0
static UINT ACTION_AppSearchDr(MSIPACKAGE *package, LPWSTR *appValue, MSISIGNATURE *sig)
{
    static const WCHAR query[] =  {
        's','e','l','e','c','t',' ','*',' ',
        'f','r','o','m',' ',
        'D','r','L','o','c','a','t','o','r',' ',
        'w','h','e','r','e',' ',
        'S','i','g','n','a','t','u','r','e','_',' ','=',' ', '\'','%','s','\'',0};
    LPWSTR parent = NULL;
    LPCWSTR parentName;
    WCHAR path[MAX_PATH];
    WCHAR expanded[MAX_PATH];
    MSIRECORD *row;
    int depth;
    DWORD sz, attr;
    UINT rc;

    TRACE("%s\n", debugstr_w(sig->Name));

    *appValue = NULL;

    row = MSI_QueryGetRecord( package->db, query, sig->Name );
    if (!row)
    {
        TRACE("failed to query DrLocator for %s\n", debugstr_w(sig->Name));
        return ERROR_SUCCESS;
    }

    /* check whether parent is set */
    parentName = MSI_RecordGetString(row, 2);
    if (parentName)
    {
        MSISIGNATURE parentSig;

        rc = ACTION_AppSearchSigName(package, parentName, &parentSig, &parent);
        ACTION_FreeSignature(&parentSig);
        if (!parent)
        {
            msiobj_release(&row->hdr);
            return ERROR_SUCCESS;
        }
    }

    sz = MAX_PATH;
    MSI_RecordGetStringW(row, 3, path, &sz);

    if (MSI_RecordIsNull(row,4))
        depth = 0;
    else
        depth = MSI_RecordGetInteger(row,4);

    if (sz)
        ACTION_ExpandAnyPath(package, path, expanded, MAX_PATH);
    else
        strcpyW(expanded, path);

    if (parent)
    {
        attr = GetFileAttributesW(parent);
        if (attr != INVALID_FILE_ATTRIBUTES &&
            !(attr & FILE_ATTRIBUTE_DIRECTORY))
        {
            PathRemoveFileSpecW(parent);
            PathAddBackslashW(parent);
        }

        strcpyW(path, parent);
        strcatW(path, expanded);
    }
    else if (sz)
        strcpyW(path, expanded);

    PathAddBackslashW(path);

    rc = ACTION_SearchDirectory(package, sig, path, depth, appValue);

    msi_free(parent);
    msiobj_release(&row->hdr);

    TRACE("returning %d\n", rc);
    return rc;
}
Beispiel #16
0
extern "C" __declspec(dllexport) bool PinToStartMenu4XP(bool bPin, char* szPath)
{
	TSAUTO();

	TCHAR file_dir[MAX_PATH + 1] = {0};
	TCHAR *file_name;
	wchar_t* pwstr_Path = AnsiToUnicode(szPath);
	if(pwstr_Path == NULL){
		return false;
	}

	wcscpy_s(file_dir,MAX_PATH,pwstr_Path);
	PathRemoveFileSpecW(file_dir);
	file_name = PathFindFileName(pwstr_Path);
	::CoInitialize(NULL);
	CComPtr<IShellDispatch> pShellDisp;
	CComPtr<Folder> folder_ptr;
	CComPtr<FolderItem> folder_item_ptr;
	CComPtr<FolderItemVerbs> folder_item_verbs_ptr;


	HRESULT rv = CoCreateInstance( CLSID_Shell, NULL, CLSCTX_SERVER,IID_IDispatch, (LPVOID *) &pShellDisp );
	do 
	{
		IF_FAILED_OR_NULL_BREAK(rv,pShellDisp);
		rv = pShellDisp->NameSpace(_variant_t(file_dir),&folder_ptr);
		IF_FAILED_OR_NULL_BREAK(rv,folder_ptr);
		rv = folder_ptr->ParseName(CComBSTR(file_name),&folder_item_ptr);
		IF_FAILED_OR_NULL_BREAK(rv,folder_item_ptr);
		rv = folder_item_ptr->Verbs(&folder_item_verbs_ptr);
		IF_FAILED_OR_NULL_BREAK(rv,folder_item_verbs_ptr);
		long count = 0;
		folder_item_verbs_ptr->get_Count(&count);
		for (long i = 0; i < count ; ++i)
		{
			FolderItemVerb* item_verb = NULL;
			rv = folder_item_verbs_ptr->Item(_variant_t(i),&item_verb);
			if (SUCCEEDED(rv) && item_verb)
			{
				CComBSTR bstrName;
				item_verb->get_Name(&bstrName);

				if ( VerbNameMatch(bstrName,bPin) )
				{
					TSDEBUG4CXX("Find Verb to Pin:"<< bstrName);
					int i = 0;
					do
					{
						rv = item_verb->DoIt();
						TSDEBUG4CXX("Try Do Verb. NO." << i+1 << ", return="<<rv);
						if (SUCCEEDED(rv))
						{
							::SHChangeNotify(SHCNE_UPDATEDIR|SHCNE_INTERRUPT|SHCNE_ASSOCCHANGED, SHCNF_IDLIST |SHCNF_FLUSH | SHCNF_PATH|SHCNE_ASSOCCHANGED,
								pwstr_Path,0);
							Sleep(500);
							delete [] pwstr_Path;
							::CoUninitialize();
							return true;
						}else
						{
							Sleep(500);
							rv = item_verb->DoIt();
						}
					}while ( i++ < 3);
						
					break;
				}
			}
		}
	} while (0);
	delete [] pwstr_Path;
	::CoUninitialize();
	return false;
}
Beispiel #17
0
int ExtractCurrentFile(HZIP hZip,bool bSkipPath)
{
    int r=-1;
    char filename_inzip[256];
    unz_file_info64 file_info;
    ZIPDECOMPRESSION *p=(ZIPDECOMPRESSION*)hZip;
    int err=unzGetCurrentFileInfo64(p->hZip,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
    if (err == UNZ_OK)
    {
        bool bEncrypted=((file_info.flag & 1) != 0);
        if ((bEncrypted) && (!p->bEncrypted))
        {
            ArchSetLastError(ARCH_ZIP_IS_ENCRYPTED);
            return -1;
        }

        char *lpPassword=((bEncrypted) && (p->bEncrypted)) ? p->szPassword : 0;
        int err=unzOpenCurrentFilePassword(p->hZip,lpPassword);
        if (err == UNZ_OK)
        {
            void *buf=_alloc(INT_BUF_SIZE);
            if (buf)
            {
                if (p->bExctractToMem)
                {
                    p->lpMem=VirtualAlloc(NULL,file_info.uncompressed_size,MEM_COMMIT,PAGE_READWRITE);
                    p->dwSize=file_info.uncompressed_size;
                    byte *pMem=(byte*)p->lpMem;
                    if (p->lpMem)
                    {
                        do
                        {
                            err=unzReadCurrentFile(p->hZip,pMem,INT_BUF_SIZE);
                            if (err < 0)
                            {
                                VirtualFree(p->lpMem,file_info.uncompressed_size,MEM_DECOMMIT);
                                break;
                            }
                            pMem+=err;
                        }
                        while (err > 0);
                    }
                    else
                        ArchSetLastError(ARCH_NO_MEM);

                    if (!err)
                        r=1;
                }
                else
                {
                    WCHAR *unicode_filename_inzip=OemToUnicodeEx(filename_inzip,-1),
                          file_to_store[MAX_PATH],
                          destPath[MAX_PATH],
                          *filename=unicode_filename_inzip;
                    if (bSkipPath)
                    {
                        WCHAR *p,*filename_withoutpath;
                        p=filename_withoutpath=unicode_filename_inzip;
                        while ((*p) != '\0')
                        {
                            if ((*p == '/') || (*p == '\\'))
                                filename_withoutpath=p+1;
                            p++;
                        }
                        filename=filename_withoutpath;
                    }

                    int dwLen=wsprintfW(destPath,L"%s\\%s",p->strOutputDir,filename);
                    for (int i=0; i < dwLen; i++)
                    {
                        if (destPath[i] == '/')
                            destPath[i]='\\';
                    }
                    lstrcpyW(file_to_store,destPath);
                    if (PathRemoveFileSpecW(destPath) != FALSE)
                        CreateDirectoryTree(destPath);
                    MemFree(unicode_filename_inzip);

                    HANDLE fout=CreateFileW(file_to_store,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,0,NULL);
                    do
                    {
                        DWORD dwSize;
                        err=unzReadCurrentFile(p->hZip,buf,INT_BUF_SIZE);
                        if (err < 0)
                            break;
                        if (!WriteFile(fout,buf,err,&dwSize,0))
                        {
                            err=-1;
                            break;
                        }
                    }
                    while (err > 0);
                    SysCloseHandle(fout);
                    if (!err)
                    {
                        change_file_date(file_to_store,file_info.dosDate,file_info.tmu_date);
                        r=1;
                    }
                    else
                        DeleteFileW(file_to_store);
                }
                MemFree(buf);
            }
            unzCloseCurrentFile(p->hZip);
        }
    }
    return r;
}
Beispiel #18
0
VOID LoadSatellites(PWCHAR Satellites, HANDLE hModuleToPatch, char* szExportName)
{
	PWCHAR CurrSatellite = Satellites;
	NTSTATUS ntStatus;

	while (CurrSatellite[0] != 0)
	{
		WCHAR WinDir[MAX_PATH];
		WCHAR SysDir[MAX_PATH];
		WCHAR Path[MAX_PATH*4];
		WCHAR Name[MAX_PATH];
		UNICODE_STRING SatelliteName;
		HANDLE hModule;
		DWORD CurrSatellite_PathLen = (DWORD)wcslen(CurrSatellite);
		WCHAR ExeName[MAX_PATH];

// prepare parameters
		memcpy(Path, CurrSatellite, sizeof(WCHAR)*(CurrSatellite_PathLen+1));
		PathRemoveFileSpecW(Path);
		if (GetWindowsDirectoryW(WinDir, _countof(WinDir)))
		{
			wcscat(Path, L";");
			wcscat(Path, WinDir);
		}
		if (GetSystemDirectoryW(SysDir, _countof(SysDir)))
		{
			wcscat(Path, L";");
			wcscat(Path, SysDir);
		}

		memcpy(Name, CurrSatellite, sizeof(WCHAR)*(CurrSatellite_PathLen+1));
		PathStripPathW(Name);

		SatelliteName.Length = (USHORT)wcslen(Name)*sizeof(WCHAR);
		SatelliteName.MaximumLength = (USHORT)(SatelliteName.Length+sizeof(WCHAR));
		SatelliteName.Buffer = Name;

// call original LdrLoadDll
		ntStatus = ((fLdrLoadDll)g_pLdrLoadDll_Context->m_Thunk)(Path, 0, &SatelliteName, &hModule);

		ExeName[0] = 0;
		GetModuleFileNameW(NULL, ExeName, _countof(ExeName));
		PathStripPathW(ExeName);
		DbPrint("r3hook::LoadSatellites - %hs \'%ls\' module into process \'%ls\', search path \'%ls\'\n",
			ntStatus == 0 ? "successefully loaded(or it was already loaded)" : "failed to load",
			Name, ExeName, Path);

		if (ntStatus == 0L && hModule)
		{
			if (szExportName)
			{
				t_fHookHandlerExport f_HookExport;

				DbPrint("r3hook::LoadSatellites - trying to call %hs...\n", szExportName);
				f_HookExport = (t_fHookHandlerExport)GetProcAddress(hModule, szExportName);
				if (f_HookExport)
				{
					//DbPrint("r3hook::LoadSatellites - calling HookExports\n");
					f_HookExport(hModuleToPatch);
				}
				else
					DbPrint("r3hook::LoadSatellites - export '%hs' not found in module %ls\n", szExportName, Name);
			}
		}

		CurrSatellite += CurrSatellite_PathLen+1;
	}
}
Beispiel #19
0
HRESULT __stdcall BtrfsContextMenu::Initialize(PCIDLIST_ABSOLUTE pidlFolder, IDataObject* pdtobj, HKEY hkeyProgID) {
    HANDLE h;
    IO_STATUS_BLOCK iosb;
    btrfs_get_file_ids bgfi;
    NTSTATUS Status;
    
    if (!pidlFolder) {
        FORMATETC format = { CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
        UINT num_files, i;
        WCHAR fn[MAX_PATH];
        HDROP hdrop;
        
        if (!pdtobj)
            return E_FAIL;
        
        stgm.tymed = TYMED_HGLOBAL;
        
        if (FAILED(pdtobj->GetData(&format, &stgm)))
            return E_INVALIDARG;
        
        stgm_set = TRUE;
        
        hdrop = (HDROP)GlobalLock(stgm.hGlobal);
        
        if (!hdrop) {
            ReleaseStgMedium(&stgm);
            stgm_set = FALSE;
            return E_INVALIDARG;
        }
         
        num_files = DragQueryFileW((HDROP)stgm.hGlobal, 0xFFFFFFFF, NULL, 0);
        
        for (i = 0; i < num_files; i++) {
            if (DragQueryFileW((HDROP)stgm.hGlobal, i, fn, sizeof(fn) / sizeof(MAX_PATH))) {
                h = CreateFileW(fn, FILE_TRAVERSE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
    
                if (h != INVALID_HANDLE_VALUE) {
                    Status = NtFsControlFile(h, NULL, NULL, NULL, &iosb, FSCTL_BTRFS_GET_FILE_IDS, NULL, 0, &bgfi, sizeof(btrfs_get_file_ids));
                        
                    if (Status == STATUS_SUCCESS && bgfi.inode == 0x100 && !bgfi.top) {
                        WCHAR parpath[MAX_PATH];
                        HANDLE h2;
                        
                        StringCchCopyW(parpath, sizeof(parpath) / sizeof(WCHAR), fn);
                        
                        PathRemoveFileSpecW(parpath);
                        
                        h2 = CreateFileW(parpath, FILE_ADD_SUBDIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
    
                        if (h2 == INVALID_HANDLE_VALUE) {
                            CloseHandle(h);
                            return E_FAIL;
                        }
                        
                        ignore = FALSE;
                        bg = FALSE;
                        
                        CloseHandle(h2);
                        CloseHandle(h);
                        return S_OK;
                    }
                    
                    CloseHandle(h);
                }
            }
        }
        
        return S_OK;
    }

    if (!SHGetPathFromIDListW(pidlFolder, path))
        return E_FAIL;
    
    // check we have permissions to create new subdirectory
    
    h = CreateFileW(path, FILE_ADD_SUBDIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
    
    if (h == INVALID_HANDLE_VALUE)
        return E_FAIL;
    
    // check is Btrfs volume
    
    Status = NtFsControlFile(h, NULL, NULL, NULL, &iosb, FSCTL_BTRFS_GET_FILE_IDS, NULL, 0, &bgfi, sizeof(btrfs_get_file_ids));
    
    if (Status != STATUS_SUCCESS) {
        CloseHandle(h);
        return E_FAIL;
    }
    
    CloseHandle(h);
    
    ignore = FALSE;
    bg = TRUE;
    
    return S_OK;
}
Beispiel #20
0
static WCHAR *search_file( MSIPACKAGE *package, WCHAR *path, MSISIGNATURE *sig )
{
    VS_FIXEDFILEINFO *info;
    DWORD attr, size;
    LPWSTR val = NULL;
    LPBYTE buffer;

    if (!sig->File)
    {
        PathRemoveFileSpecW(path);
        PathAddBackslashW(path);

        attr = msi_get_file_attributes( package, path );
        if (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY))
            return strdupW(path);

        return NULL;
    }

    attr = msi_get_file_attributes( package, path );
    if (attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY))
        return NULL;

    size = msi_get_file_version_info( package, path, 0, NULL );
    if (!size)
        return strdupW(path);

    buffer = msi_alloc(size);
    if (!buffer)
        return NULL;

    size = msi_get_file_version_info( package, path, size, buffer );
    if (!size)
        goto done;

    if (!VerQueryValueW(buffer, szBackSlash, (LPVOID)&info, &size) || !info)
        goto done;

    if (sig->MinVersionLS || sig->MinVersionMS)
    {
        if (info->dwFileVersionMS < sig->MinVersionMS)
            goto done;

        if (info->dwFileVersionMS == sig->MinVersionMS &&
            info->dwFileVersionLS < sig->MinVersionLS)
            goto done;
    }

    if (sig->MaxVersionLS || sig->MaxVersionMS)
    {
        if (info->dwFileVersionMS > sig->MaxVersionMS)
            goto done;

        if (info->dwFileVersionMS == sig->MaxVersionMS &&
            info->dwFileVersionLS > sig->MaxVersionLS)
            goto done;
    }

    val = strdupW(path);

done:
    msi_free(buffer);
    return val;
}
Beispiel #21
0
BOOL WINAPI in_whitelist(LPCWSTR lpfile)
{
	WCHAR *moz_processes[] = {L"", L"plugin-container.exe", L"plugin-hang-ui.exe", L"webapprt-stub.exe",
							  L"webapp-uninstaller.exe",L"WSEnable.exe",L"uninstall\\helper.exe",
							  L"crashreporter.exe",L"CommandExecuteHandler.exe",L"maintenanceservice.exe",
							  L"maintenanceservice_installer.exe",L"updater.exe"
							 };
	static  WCHAR white_list[EXCLUDE_NUM][VALUE_LEN+1];
	int		i = sizeof(moz_processes)/sizeof(moz_processes[0]);
	LPCWSTR pname = lpfile;
	BOOL    ret = FALSE;
	if (lpfile[0] == L'"')
	{
		pname = &lpfile[1];
	}
	/* 遍历白名单一次,只需遍历一次 */
	ret = stristrW(white_list[1],L"plugin-container.exe") != NULL;
	if ( !ret )
	{
		/* firefox目录下进程的路径 */
		int num;
		WCHAR temp[VALUE_LEN+1];
		GetModuleFileNameW(NULL,temp,VALUE_LEN);
		wcsncpy(white_list[0],(LPCWSTR)temp,VALUE_LEN);
		PathRemoveFileSpecW(temp);
		for(num=1; num<i; ++num)
		{
			_snwprintf(white_list[num],VALUE_LEN,L"%ls\\%ls", temp, moz_processes[num]);
		}
		ret = foreach_section(L"whitelist", &white_list[num], EXCLUDE_NUM-num);
	}
	if ( (ret = !ret) == FALSE )
	{
		/* 核对白名单 */
		for ( i=0; i<EXCLUDE_NUM ; i++ )
		{
			if (wcslen(white_list[i]) == 0)
			{
				continue;
			}
			if ( StrChrW(white_list[i],L'*') || StrChrW(white_list[i],L'?') )
			{
				if ( PathMatchSpecW(pname,white_list[i]) )
				{
					ret = TRUE;
					break;
				}
			}
			else if (white_list[i][1] != L':')
			{
				PathToCombineW(white_list[i],VALUE_LEN);
			}
			if (_wcsnicmp(white_list[i],pname,wcslen(white_list[i]))==0)
			{
				ret = TRUE;
				break;
			}
		}
	}
	return ret;
}
Beispiel #22
0
static LPWSTR app_search_file(LPWSTR path, MSISIGNATURE *sig)
{
    VS_FIXEDFILEINFO *info;
    DWORD attr, handle, size;
    LPWSTR val = NULL;
    LPBYTE buffer;

    if (!sig->File)
    {
        PathRemoveFileSpecW(path);
        PathAddBackslashW(path);

        attr = GetFileAttributesW(path);
        if (attr != INVALID_FILE_ATTRIBUTES &&
            (attr & FILE_ATTRIBUTE_DIRECTORY))
            return strdupW(path);

        return NULL;
    }

    attr = GetFileAttributesW(path);
    if (attr == INVALID_FILE_ATTRIBUTES ||
        (attr & FILE_ATTRIBUTE_DIRECTORY))
        return NULL;

    size = GetFileVersionInfoSizeW(path, &handle);
    if (!size)
        return strdupW(path);

    buffer = msi_alloc(size);
    if (!buffer)
        return NULL;

    if (!GetFileVersionInfoW(path, 0, size, buffer))
        goto done;

    if (!VerQueryValueW(buffer, szBackSlash, (LPVOID)&info, &size) || !info)
        goto done;

    if (sig->MinVersionLS || sig->MinVersionMS)
    {
        if (info->dwFileVersionMS < sig->MinVersionMS)
            goto done;

        if (info->dwFileVersionMS == sig->MinVersionMS &&
            info->dwFileVersionLS < sig->MinVersionLS)
            goto done;
    }

    if (sig->MaxVersionLS || sig->MaxVersionMS)
    {
        if (info->dwFileVersionMS > sig->MaxVersionMS)
            goto done;

        if (info->dwFileVersionMS == sig->MaxVersionMS &&
            info->dwFileVersionLS > sig->MaxVersionLS)
            goto done;
    }

    val = strdupW(path);

done:
    msi_free(buffer);
    return val;
}
Beispiel #23
0
/** \brief 主函数
 *
 * 主启动函数。负责调用启动DLL的启动函数
 */
INT WINAPI WinMain(HINSTANCE currentInstance, HINSTANCE previousInstance, LPSTR pCommandLine, INT showType)
{
	INT exitCode = -1;

	/* 获得几个要加到Path的文件夹路径 */
	wchar_t binaryPath[MAX_PATH];
	wchar_t pathEnvironmentVariable[32767 /* http://msdn.microsoft.com/en-us/library/windows/desktop/ms683188.aspx */ ];
	std::wstring newPathEnvironmentVariable;

	// 当前exe路径
	GetModuleFileNameW(currentInstance, binaryPath, sizeof(binaryPath) / sizeof(binaryPath[0]));
	PathRemoveBlanksW(binaryPath);
	PathUnquoteSpacesW(binaryPath);
	PathRemoveBackslashW(binaryPath);

	// bin文件夹路径
	PathRemoveFileSpecW(binaryPath);
	PathAppendW(binaryPath, L"bin");

	// 拷贝到待增加路径字符串
	newPathEnvironmentVariable.append(binaryPath);

	// plugin文件夹路径
	PathRemoveFileSpecW(binaryPath);
	PathAppendW(binaryPath, L"plugin");

	// 拷贝到待增加路径字符串
	newPathEnvironmentVariable.append(L";");
	newPathEnvironmentVariable.append(binaryPath);

	/* 设置PATH环境变量 */
	// 获取环境变量
	pathEnvironmentVariable[0] = L'\0';
	DWORD length = GetEnvironmentVariableW(L"PATH", pathEnvironmentVariable, sizeof(pathEnvironmentVariable) / sizeof(pathEnvironmentVariable[0]));

	// 组合新环境变量
	if (length > 0)
		newPathEnvironmentVariable.append(L";");

	newPathEnvironmentVariable.append(pathEnvironmentVariable);

	// 拷贝回去
	wcscpy_s(pathEnvironmentVariable, newPathEnvironmentVariable.c_str());

	// 设置环境变量
	SetEnvironmentVariableW(L"PATH", pathEnvironmentVariable);

	/* 载入CRT的Dll,防止Dll冲突 */

	// 再次得到bin文件夹路径
	PathRemoveFileSpecW(binaryPath);
	PathAppendW(binaryPath, L"bin");

#ifdef _DEBUG
	PathAppendW(binaryPath, L"msvcr100d.dll");
	HMODULE msvcr100 = LoadLibraryW(binaryPath);

	PathRemoveFileSpecW(binaryPath);
	PathAppendW(binaryPath, L"msvcp100d.dll");
	HMODULE msvcp100 = LoadLibraryW(binaryPath);
#else
	PathAppendW(binaryPath, L"msvcr100.dll");
	HMODULE msvcr100 = LoadLibraryW(binaryPath);

	PathRemoveFileSpecW(binaryPath);
	PathAppendW(binaryPath, L"msvcp100.dll");
	HMODULE msvcp100 = LoadLibraryW(binaryPath);
#endif

	// 尝试载入YDWEStartup.dll
	HMODULE startupModule = LoadLibraryW(L"YDWEStartup.dll");
	if (startupModule)
	{
		TPFStartup pfStartup = (TPFStartup)GetProcAddress(startupModule, "YDWEStartup");
		if (pfStartup)
			exitCode = pfStartup(currentInstance, previousInstance, pCommandLine, showType);

		FreeLibrary(startupModule);
	}

	if (msvcp100)
		FreeLibrary(msvcp100);
	if (msvcr100)
		FreeLibrary(msvcr100);

	return exitCode;
}
Beispiel #24
0
static SHIMGVW_FILENODE*
pBuildFileList(LPWSTR szFirstFile)
{
    HANDLE hFindHandle;
    WCHAR *extension;
    WCHAR szSearchPath[MAX_PATH];
    WCHAR szSearchMask[MAX_PATH];
    WCHAR szFileTypes[MAX_PATH];
    WIN32_FIND_DATAW findData;
    SHIMGVW_FILENODE *currentNode;
    SHIMGVW_FILENODE *root;
    SHIMGVW_FILENODE *conductor;
    ImageCodecInfo *codecInfo;
    UINT num;
    UINT size;
    UINT j;


    wcscpy(szSearchPath, szFirstFile);
    PathRemoveFileSpecW(szSearchPath);

    GdipGetImageDecodersSize(&num, &size);
    codecInfo = malloc(size);
    if (!codecInfo)
    {
        DPRINT1("malloc() failed in pLoadFileList()\n");
        return NULL;
    }

    GdipGetImageDecoders(num, size, codecInfo);

    root = malloc(sizeof(SHIMGVW_FILENODE));
    if (!root)
    {
        DPRINT1("malloc() failed in pLoadFileList()\n");
        free(codecInfo);
        return NULL;
    }

    conductor = root;

    for (j = 0; j < num; ++j)
    {
        StringCbPrintfExW(szFileTypes, MAX_PATH, NULL, NULL, 0, L"%ls", codecInfo[j].FilenameExtension);
        
        extension = wcstok(szFileTypes, L";");
        while (extension != NULL)
        {
            StringCbPrintfExW(szSearchMask, MAX_PATH, NULL, NULL, 0, L"%ls%ls%ls", szSearchPath, L"\\", extension);

            hFindHandle = FindFirstFileW(szSearchMask, &findData);
            if (hFindHandle != INVALID_HANDLE_VALUE)
            {
                do
                {
                    StringCbPrintfExW(conductor->FileName, MAX_PATH, NULL, NULL, 0, L"%ls%ls%ls", szSearchPath, L"\\", findData.cFileName);

                    // compare the name of the requested file with the one currently found.
                    // if the name matches, the current node is returned by the function.
                    if (wcscmp(szFirstFile, conductor->FileName) == 0)
                    {
                        currentNode = conductor;
                    }

                    conductor->Next = malloc(sizeof(SHIMGVW_FILENODE));

                    // if malloc fails, make circular what we have and return it
                    if (!conductor->Next)
                    {
                        DPRINT1("malloc() failed in pLoadFileList()\n");
                        
                        conductor->Next = root;
                        root->Prev = conductor;

                        FindClose(hFindHandle);
                        free(codecInfo);
                        return conductor;
                    }

                    conductor->Next->Prev = conductor;
                    conductor = conductor->Next;
                }
                while (FindNextFileW(hFindHandle, &findData) != 0);

                FindClose(hFindHandle);
            }

            extension = wcstok(NULL, L";");
        }
    }

    // we now have a node too much in the list. In case the requested file was not found,
    // we use this node to store the name of it, otherwise we free it.
    if (currentNode == NULL)
    {
        StringCbPrintfExW(conductor->FileName, MAX_PATH, NULL, NULL, 0, L"%ls", szFirstFile);
        currentNode = conductor;
    }
    else
    {
        conductor = conductor->Prev;
        free(conductor->Next);
    }

    // link the last node with the first one to make the list circular
    conductor->Next = root;
    root->Prev = conductor;
    conductor = currentNode;

    free(codecInfo);

    return conductor;
}
Beispiel #25
0
static void create_snapshot(HWND hwnd, WCHAR* fn) {
    HANDLE h;
    NTSTATUS Status;
    IO_STATUS_BLOCK iosb;
    btrfs_get_file_ids bgfi;
    
    h = CreateFileW(fn, FILE_TRAVERSE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
    
    if (h != INVALID_HANDLE_VALUE) {
        Status = NtFsControlFile(h, NULL, NULL, NULL, &iosb, FSCTL_BTRFS_GET_FILE_IDS, NULL, 0, &bgfi, sizeof(btrfs_get_file_ids));
            
        if (Status == STATUS_SUCCESS && bgfi.inode == 0x100 && !bgfi.top) {
            WCHAR parpath[MAX_PATH], subvolname[MAX_PATH], templ[MAX_PATH], name[MAX_PATH], searchpath[MAX_PATH];
            HANDLE h2, fff;
            btrfs_create_snapshot* bcs;
            ULONG namelen, pathend;
            WIN32_FIND_DATAW wfd;
            SYSTEMTIME time;
            
            StringCchCopyW(parpath, sizeof(parpath) / sizeof(WCHAR), fn);
            PathRemoveFileSpecW(parpath);
            
            StringCchCopyW(subvolname, sizeof(subvolname) / sizeof(WCHAR), fn);
            PathStripPathW(subvolname);
            
            h2 = CreateFileW(parpath, FILE_ADD_SUBDIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

            if (h2 == INVALID_HANDLE_VALUE) {
                ShowError(hwnd, GetLastError());
                CloseHandle(h);
                return;
            }
            
            if (!LoadStringW(module, IDS_SNAPSHOT_FILENAME, templ, MAX_PATH)) {
                ShowError(hwnd, GetLastError());
                CloseHandle(h);
                CloseHandle(h2);
                return;
            }
            
            GetLocalTime(&time);
            
            if (StringCchPrintfW(name, sizeof(name) / sizeof(WCHAR), templ, subvolname, time.wYear, time.wMonth, time.wDay) == STRSAFE_E_INSUFFICIENT_BUFFER) {
                MessageBoxW(hwnd, L"Filename too long.\n", L"Error", MB_ICONERROR);
                CloseHandle(h);
                CloseHandle(h2);
                return;
            }
            
            StringCchCopyW(searchpath, sizeof(searchpath) / sizeof(WCHAR), parpath);
            StringCchCatW(searchpath, sizeof(searchpath) / sizeof(WCHAR), L"\\");
            pathend = wcslen(searchpath);
            
            StringCchCatW(searchpath, sizeof(searchpath) / sizeof(WCHAR), name);
            
            fff = FindFirstFileW(searchpath, &wfd);
            
            if (fff != INVALID_HANDLE_VALUE) {
                ULONG i = wcslen(searchpath), num = 2;
                
                do {
                    FindClose(fff);
                    
                    searchpath[i] = 0;
                    if (StringCchPrintfW(searchpath, sizeof(searchpath) / sizeof(WCHAR), L"%s (%u)", searchpath, num) == STRSAFE_E_INSUFFICIENT_BUFFER) {
                        MessageBoxW(hwnd, L"Filename too long.\n", L"Error", MB_ICONERROR);
                        CloseHandle(h);
                        CloseHandle(h2);
                        return;
                    }

                    fff = FindFirstFileW(searchpath, &wfd);
                    num++;
                } while (fff != INVALID_HANDLE_VALUE);
            }
            
            namelen = wcslen(&searchpath[pathend]) * sizeof(WCHAR);
                        
            bcs = (btrfs_create_snapshot*)malloc(sizeof(btrfs_create_snapshot) - 1 + namelen);
            bcs->subvol = h;
            bcs->namelen = namelen;
            memcpy(bcs->name, &searchpath[pathend], namelen);
            
            Status = NtFsControlFile(h2, NULL, NULL, NULL, &iosb, FSCTL_BTRFS_CREATE_SNAPSHOT, NULL, 0, bcs, sizeof(btrfs_create_snapshot) - 1 + namelen);
        
            if (Status != STATUS_SUCCESS)
                ShowNtStatusError(hwnd, Status);
            
            CloseHandle(h2);
        }
        
        CloseHandle(h);
    } else
        ShowError(hwnd, GetLastError());
}