Пример #1
0
/*
 * Helper function for search_path
 */
static WCHAR* search_path_join_test(const WCHAR* dir,
                                      int dir_len,
                                      const WCHAR* name,
                                      int name_len,
                                      const WCHAR* ext,
                                      int ext_len,
                                      const WCHAR* cwd,
                                      int cwd_len) {
  WCHAR *result, *result_pos;
  DWORD attrs;

  if (dir_len >= 1 && (dir[0] == L'/' || dir[0] == L'\\')) {
    /* It's a full path without drive letter, use cwd's drive letter only */
    cwd_len = 2;
  } else if (dir_len >= 2 && dir[1] == L':' &&
      (dir_len < 3 || (dir[2] != L'/' && dir[2] != L'\\'))) {
    /* It's a relative path with drive letter (ext.g. D:../some/file)
     * Replace drive letter in dir by full cwd if it points to the same drive,
     * otherwise use the dir only.
     */
    if (cwd_len < 2 || _wcsnicmp(cwd, dir, 2) != 0) {
      cwd_len = 0;
    } else {
      dir += 2;
      dir_len -= 2;
    }
  } else if (dir_len > 2 && dir[1] == L':') {
    /* It's an absolute path with drive letter
     * Don't use the cwd at all
     */
    cwd_len = 0;
  }

  /* Allocate buffer for output */
  result = result_pos = (WCHAR*)malloc(sizeof(WCHAR) *
      (cwd_len + 1 + dir_len + 1 + name_len + 1 + ext_len + 1));

  /* Copy cwd */
  wcsncpy(result_pos, cwd, cwd_len);
  result_pos += cwd_len;

  /* Add a path separator if cwd didn't end with one */
  if (cwd_len && wcsrchr(L"\\/:", result_pos[-1]) == NULL) {
    result_pos[0] = L'\\';
    result_pos++;
  }

  /* Copy dir */
  wcsncpy(result_pos, dir, dir_len);
  result_pos += dir_len;

  /* Add a separator if the dir didn't end with one */
  if (dir_len && wcsrchr(L"\\/:", result_pos[-1]) == NULL) {
    result_pos[0] = L'\\';
    result_pos++;
  }

  /* Copy filename */
  wcsncpy(result_pos, name, name_len);
  result_pos += name_len;

  if (ext_len) {
    /* Add a dot if the filename didn't end with one */
    if (name_len && result_pos[-1] != '.') {
      result_pos[0] = L'.';
      result_pos++;
    }

    /* Copy extension */
    wcsncpy(result_pos, ext, ext_len);
    result_pos += ext_len;
  }

  /* Null terminator */
  result_pos[0] = L'\0';

  attrs = GetFileAttributesW(result);

  if (attrs != INVALID_FILE_ATTRIBUTES &&
     !(attrs & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT))) {
    return result;
  }

  free(result);
  return NULL;
}
Пример #2
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;
}
Пример #3
0
static UINT ACTION_SearchDirectory(MSIPACKAGE *package, MSISIGNATURE *sig,
 LPCWSTR path, int depth, LPWSTR *appValue)
{
    UINT rc;
    DWORD attr;
    LPWSTR val = NULL;

    TRACE("%p, %p, %s, %d, %p\n", package, sig, debugstr_w(path), depth,
     appValue);

    if (ACTION_IsFullPath(path))
    {
        if (sig->File)
            rc = ACTION_RecurseSearchDirectory(package, &val, sig, path, depth);
        else
        {
            /* Recursively searching a directory makes no sense when the
             * directory to search is the thing you're trying to find.
             */
            rc = ACTION_CheckDirectory(package, path, &val);
        }
    }
    else
    {
        WCHAR pathWithDrive[MAX_PATH] = { 'C',':','\\',0 };
        DWORD drives = GetLogicalDrives();
        int i;

        rc = ERROR_SUCCESS;
        for (i = 0; rc == ERROR_SUCCESS && !val && i < 26; i++)
        {
            if (!(drives & (1 << i)))
                continue;

            pathWithDrive[0] = 'A' + i;
            if (GetDriveTypeW(pathWithDrive) != DRIVE_FIXED)
                continue;

            lstrcpynW(pathWithDrive + 3, path,
                      sizeof(pathWithDrive) / sizeof(pathWithDrive[0]) - 3);

            if (sig->File)
                rc = ACTION_RecurseSearchDirectory(package, &val, sig,
                                                   pathWithDrive, depth);
            else
                rc = ACTION_CheckDirectory(package, pathWithDrive, &val);
        }
    }

    attr = GetFileAttributesW(val);
    if (attr != INVALID_FILE_ATTRIBUTES &&
        (attr & FILE_ATTRIBUTE_DIRECTORY) &&
        val && val[lstrlenW(val) - 1] != '\\')
    {
        val = msi_realloc(val, (lstrlenW(val) + 2) * sizeof(WCHAR));
        if (!val)
            rc = ERROR_OUTOFMEMORY;
        else
            PathAddBackslashW(val);
    }

    *appValue = val;

    TRACE("returning %d\n", rc);
    return rc;
}
Пример #4
0
/**
 * Yet another inline helper for determining whether
 * a given path has the SYSTEM attribute flagged on it.
 */
static inline bool has_system_attr(wchar_t* path)
{
	return GetFileAttributesW(path) & FILE_ATTRIBUTE_SYSTEM;
}
Пример #5
0
GamePlayer::GamePlayer(HINSTANCE _hInstance, HINSTANCE _hPrevInstance, LPSTR _lpCmdLine, int _nCmdShow,int width,int height)
{
	hInstance=_hInstance;
	hPrevInstance=_hPrevInstance;
	lpCmdLine=_lpCmdLine;
	nCmdShow=_nCmdShow;
	pWndClassName  = L"RGSSX Player";
	pDefaultLibrary = L"RGSS300.dll";
	pDefaultTitle  = L"Untitled";
	pDefaultScripts = L"Data\\Scripts.rvdata2";
	nScreenWidth = width;
	nScreenHeight = height;
	nEvalErrorCode = 6;
	g_hWnd = NULL;
	DWORD len = ::GetModuleFileNameW(hInstance, szAppPath, MAX_PATH);
	for (--len; len > 0; --len)
	{
		if (szAppPath[len] == L'\\' || szAppPath[len] == L'/')
		{
			szAppPath[len] = 0;
			break;
		}
	}
	::SetCurrentDirectoryW(szAppPath);
	// ini文件路径
	len = ::GetModuleFileNameW(hInstance, szIniPath, MAX_PATH);
	szIniPath[len - 1] = L'i';
	szIniPath[len - 2] = L'n';
	szIniPath[len - 3] = L'i';

	// 加密包路径
	len = ::GetModuleFileNameW(hInstance, szRgssadPath, MAX_PATH);
	for (--len; len > 0; --len)
	{
		if (szRgssadPath[len] == L'.')
		{
			szRgssadPath[len + 1] = L'r';
			szRgssadPath[len + 2] = L'g';
			szRgssadPath[len + 3] = L's';
			szRgssadPath[len + 4] = L's';
			szRgssadPath[len + 5] = L'3';
			szRgssadPath[len + 6] = L'a';
			szRgssadPath[len + 7] = 0;
			break;
		}
	}

	// ini文件存在
	if (GetFileAttributesW(szIniPath) != INVALID_FILE_ATTRIBUTES)
	{
		//GetPrivateProfileStringW(L"Game", L"Library2", pDefaultLibrary, szLibrary, MAX_PATH, szIniPath);
		wcscpy_s(szLibrary, pDefaultLibrary);
		GetPrivateProfileStringW(L"Game", L"Title",  pDefaultTitle,   szTitle, MAX_PATH, szIniPath);
		//GetPrivateProfileStringW(L"Game", L"Scripts", pDefaultScripts, szScripts, MAX_PATH, szIniPath);
		wcscpy_s(szScripts, pDefaultScripts);
	}
	else
	{
		wcscpy_s(szLibrary, pDefaultLibrary);
		wcscpy_s(szTitle, pDefaultTitle);
		wcscpy_s(szScripts, pDefaultScripts);
	}

	if (GetFileAttributesW(szRgssadPath) != INVALID_FILE_ATTRIBUTES)
		pRgssad = szRgssadPath;

}
Пример #6
0
PRBool
GRE_GetPathFromRegKey(HKEY aRegKey,
                      const GREVersionRange *versions,
                      PRUint32 versionsLength,
                      const GREProperty *properties,
                      PRUint32 propertiesLength,
                      char* aBuffer, PRUint32 aBufLen)
{
  // Formerly, GREs were registered at the registry key
  // HKLM/Software/mozilla.org/GRE/<version> valuepair GreHome=Path.
  // Nowadays, they are registered in any subkey of
  // Software/mozilla.org/GRE, with the following valuepairs:
  //   Version=<version> (REG_SZ)
  //   GreHome=<path>    (REG_SZ or REG_EXPAND_SZ)
  //   <Property>=<value> (REG_SZ)
  //
  // Additional meta-info may be available in the future, including
  // localization info and other information which might be pertinent
  // to selecting one GRE over another.
  //
  // When a GRE is being registered, it should try to register itself at
  // HKLM/Software/mozilla.org/GRE/<Version> first, to preserve compatibility
  // with older glue. If this key is already taken (i.e. there is more than
  // one GRE of that version installed), it should append a unique number to
  // the version, for example:
  //   1.1 (already in use), 1.1_1, 1.1_2, etc...

  DWORD i = 0;
  PRUnichar buffer[MAXPATHLEN + 1];

  while (PR_TRUE) {
    PRUnichar name[MAXPATHLEN + 1];
    DWORD nameLen = MAXPATHLEN;
    if (::RegEnumKeyExW(aRegKey, i, name, &nameLen, NULL, NULL, NULL, NULL) !=
          ERROR_SUCCESS) {
        break;
    }

    HKEY subKey = NULL;
    if (::RegOpenKeyExW(aRegKey, name, 0, KEY_QUERY_VALUE, &subKey) !=
          ERROR_SUCCESS) {
        continue;
    }

    PRUnichar version[40];
    DWORD versionlen = 40;
    PRUnichar pathbuf[MAXPATHLEN + 1];
    DWORD pathlen;
    DWORD pathtype;

    PRBool ok = PR_FALSE;

    if (::RegQueryValueExW(subKey, L"Version", NULL, NULL,
                           (BYTE*) version, &versionlen) == ERROR_SUCCESS &&
          CheckVersion(version, versions, versionsLength)) {

      ok = PR_TRUE;
      const GREProperty *props = properties;
      const GREProperty *propsEnd = properties + propertiesLength;
      for (; ok && props < propsEnd; ++props) {
        pathlen = MAXPATHLEN + 1;

        AutoWString wproperty(ConvertUTF8toNewUTF16(props->property));
        AutoWString wvalue(ConvertUTF8toNewUTF16(props->value));
        if (::RegQueryValueExW(subKey, wproperty, NULL, &pathtype,
                               (BYTE*) pathbuf, &pathlen) != ERROR_SUCCESS ||
            wcscmp(pathbuf,  wvalue))
            ok = PR_FALSE;
      }

      pathlen = sizeof(pathbuf);
      if (ok &&
          (!::RegQueryValueExW(subKey, L"GreHome", NULL, &pathtype,
                              (BYTE*) pathbuf, &pathlen) == ERROR_SUCCESS ||
           !*pathbuf ||
           !CopyWithEnvExpansion(buffer, pathbuf, MAXPATHLEN, pathtype))) {
        ok = PR_FALSE;
      }
      else if (!wcsncat(buffer, L"\\" LXPCOM_DLL, aBufLen) 
#ifdef WINCE
               || (GetFileAttributesW(buffer) == INVALID_FILE_ATTRIBUTES)
#else
               || _waccess(buffer, R_OK)
#endif
               ) {
        ok = PR_FALSE;
      }
    }

    RegCloseKey(subKey);

    if (ok) {
      WideCharToMultiByte(CP_UTF8, 0, buffer, -1, aBuffer, aBufLen, NULL, NULL);
      return PR_TRUE;
    }

    ++i;
  }

  aBuffer[0] = '\0';

  return PR_FALSE;
}
Пример #7
0
static HRESULT WINAPI IAssemblyCacheImpl_InstallAssembly(IAssemblyCache *iface,
                                                         DWORD dwFlags,
                                                         LPCWSTR pszManifestFilePath,
                                                         LPCFUSION_INSTALL_REFERENCE pRefData)
{
    static const WCHAR format[] =
        {'%','s','\\','%','s','\\','%','s','_','_','%','s','\\',0};

    ASSEMBLY *assembly;
    LPWSTR filename;
    LPWSTR name = NULL;
    LPWSTR token = NULL;
    LPWSTR version = NULL;
    LPWSTR asmpath = NULL;
    WCHAR path[MAX_PATH];
    WCHAR asmdir[MAX_PATH];
    LPWSTR ext;
    HRESULT hr;

    static const WCHAR ext_exe[] = {'.','e','x','e',0};
    static const WCHAR ext_dll[] = {'.','d','l','l',0};

    TRACE("(%p, %d, %s, %p)\n", iface, dwFlags,
          debugstr_w(pszManifestFilePath), pRefData);

    if (!pszManifestFilePath || !*pszManifestFilePath)
        return E_INVALIDARG;

    if (!(ext = strrchrW(pszManifestFilePath, '.')))
        return HRESULT_FROM_WIN32(ERROR_INVALID_NAME);

    if (lstrcmpiW(ext, ext_exe) && lstrcmpiW(ext, ext_dll))
        return HRESULT_FROM_WIN32(ERROR_INVALID_NAME);

    if (GetFileAttributesW(pszManifestFilePath) == INVALID_FILE_ATTRIBUTES)
        return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);

    hr = assembly_create(&assembly, pszManifestFilePath);
    if (FAILED(hr))
    {
        hr = COR_E_ASSEMBLYEXPECTED;
        goto done;
    }

    hr = assembly_get_name(assembly, &name);
    if (FAILED(hr))
        goto done;

    hr = assembly_get_pubkey_token(assembly, &token);
    if (FAILED(hr))
        goto done;

    hr = assembly_get_version(assembly, &version);
    if (FAILED(hr))
        goto done;

    get_assembly_directory(asmdir, MAX_PATH, assembly_get_architecture(assembly));

    sprintfW(path, format, asmdir, name, version, token);

    create_full_path(path);

    hr = assembly_get_path(assembly, &asmpath);
    if (FAILED(hr))
        goto done;

    filename = PathFindFileNameW(asmpath);

    strcatW(path, filename);
    if (!CopyFileW(asmpath, path, FALSE))
        hr = HRESULT_FROM_WIN32(GetLastError());

done:
    HeapFree(GetProcessHeap(), 0, name);
    HeapFree(GetProcessHeap(), 0, token);
    HeapFree(GetProcessHeap(), 0, version);
    HeapFree(GetProcessHeap(), 0, asmpath);
    assembly_release(assembly);
    return hr;
}
Пример #8
0
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();
}
Пример #9
0
HRESULT FileMoniker_CreateFromDisplayName(LPBC pbc, LPCOLESTR szDisplayName,
                                          LPDWORD pchEaten, IMoniker **ppmk)
{
    LPCWSTR end;
    static const WCHAR wszSeparators[] = {':','\\','/','!',0};

    for (end = szDisplayName + strlenW(szDisplayName);
         end && (end != szDisplayName);
         end = memrpbrkW(szDisplayName, end - szDisplayName, wszSeparators))
    {
        HRESULT hr;
        IRunningObjectTable *rot;
        IMoniker *file_moniker;
        LPWSTR file_display_name;
        LPWSTR full_path_name;
        DWORD full_path_name_len;
        int len = end - szDisplayName;

        file_display_name = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
        if (!file_display_name) return E_OUTOFMEMORY;
        memcpy(file_display_name, szDisplayName, len * sizeof(WCHAR));
        file_display_name[len] = '\0';

        hr = CreateFileMoniker(file_display_name, &file_moniker);
        if (FAILED(hr))
        {
            HeapFree(GetProcessHeap(), 0, file_display_name);
            return hr;
        }

        hr = IBindCtx_GetRunningObjectTable(pbc, &rot);
        if (FAILED(hr))
        {
            HeapFree(GetProcessHeap(), 0, file_display_name);
            IMoniker_Release(file_moniker);
            return hr;
        }

        hr = IRunningObjectTable_IsRunning(rot, file_moniker);
        IRunningObjectTable_Release(rot);
        if (FAILED(hr))
        {
            HeapFree(GetProcessHeap(), 0, file_display_name);
            IMoniker_Release(file_moniker);
            return hr;
        }
        if (hr == S_OK)
        {
            TRACE("found running file moniker for %s\n", debugstr_w(file_display_name));
            *pchEaten = len;
            *ppmk = file_moniker;
            HeapFree(GetProcessHeap(), 0, file_display_name);
            return S_OK;
        }

        full_path_name_len = GetFullPathNameW(file_display_name, 0, NULL, NULL);
        if (!full_path_name_len)
        {
            HeapFree(GetProcessHeap(), 0, file_display_name);
            IMoniker_Release(file_moniker);
            return MK_E_SYNTAX;
        }
        full_path_name = HeapAlloc(GetProcessHeap(), 0, full_path_name_len * sizeof(WCHAR));
        if (!full_path_name)
        {
            HeapFree(GetProcessHeap(), 0, file_display_name);
            IMoniker_Release(file_moniker);
            return E_OUTOFMEMORY;
        }
        GetFullPathNameW(file_display_name, full_path_name_len, full_path_name, NULL);

        if (GetFileAttributesW(full_path_name) == INVALID_FILE_ATTRIBUTES)
            TRACE("couldn't open file %s\n", debugstr_w(full_path_name));
        else
        {
            TRACE("got file moniker for %s\n", debugstr_w(szDisplayName));
            *pchEaten = len;
            *ppmk = file_moniker;
            HeapFree(GetProcessHeap(), 0, file_display_name);
            HeapFree(GetProcessHeap(), 0, full_path_name);
            return S_OK;
        }
        HeapFree(GetProcessHeap(), 0, file_display_name);
        HeapFree(GetProcessHeap(), 0, full_path_name);
        IMoniker_Release(file_moniker);
    }

    return MK_E_CANTOPENFILE;
}
Пример #10
0
/*
 * Arguments: path (string), [more_info (boolean)]
 * Returns: [is_directory (boolean), is_file (boolean),
 *	is_read (boolean), is_write (boolean), is_execute (boolean),
 *	[is_link (boolean), size (number),
 *	access_time (number), modify_time (number), create_time (number)]]
 */
static int
sys_stat (lua_State *L)
{
  const char *path = luaL_checkstring(L, 1);
  const int more_info = lua_toboolean(L, 2);
#ifndef _WIN32
  struct stat st;
#else
  struct _stat st;
#endif
  int res;

  sys_vm_leave(L);
#ifndef _WIN32
  res = stat(path, &st);
#else
  {
    void *os_path = utf8_to_filename(path);
    if (!os_path)
      return sys_seterror(L, ERROR_NOT_ENOUGH_MEMORY);

    res = is_WinNT ? _wstat(os_path, &st) : _stat(os_path, &st);

    free(os_path);
  }
#endif
  sys_vm_enter(L);

  if (!res) {
    /* is directory? */
    lua_pushboolean(L,
#ifndef _WIN32
     S_ISDIR(st.st_mode)
#else
     st.st_mode & _S_IFDIR
#endif
    );
    /* is regular file? */
    lua_pushboolean(L,
#ifndef _WIN32
     S_ISREG(st.st_mode)
#else
     st.st_mode & _S_IFREG
#endif
    );
    /* can anyone read from file? */
    lua_pushboolean(L,
#ifndef _WIN32
     st.st_mode & (S_IRUSR | S_IRGRP | S_IROTH)
#else
     st.st_mode & _S_IREAD
#endif
    );
    /* can anyone write to file? */
    lua_pushboolean(L,
#ifndef _WIN32
     st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)
#else
     st.st_mode & _S_IWRITE
#endif
    );
    /* can anyone execute the file? */
    lua_pushboolean(L,
#ifndef _WIN32
     st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)
#else
     st.st_mode & _S_IEXEC
#endif
    );
    if (more_info) {
      /* is link? */
#ifndef _WIN32
      lua_pushboolean(L, S_ISLNK(st.st_mode));
#else
      DWORD attr;
      {
        void *os_path = utf8_to_filename(path);
        if (!os_path)
          return sys_seterror(L, ERROR_NOT_ENOUGH_MEMORY);

        attr = is_WinNT
         ? GetFileAttributesW(os_path)
         : GetFileAttributesA(os_path);

        free(os_path);
      }
      lua_pushboolean(L,
       attr > 0 && (attr & FILE_ATTRIBUTE_REPARSE_POINT));
#endif
      lua_pushnumber(L, (lua_Number) st.st_size);  /* size in bytes */
      lua_pushnumber(L, (lua_Number) st.st_atime);  /* access time */
      lua_pushnumber(L, (lua_Number) st.st_mtime);  /* modification time */
      lua_pushnumber(L, (lua_Number) st.st_ctime);  /* creation time */
      return 10;
    }
    return 5;
  }
  return sys_seterror(L, 0);
}
Пример #11
0
/*
 * opendir
 *
 * Returns a pointer to a DIR structure appropriately filled in to begin
 * searching a directory.
 */
_TDIR *
_topendir (const _TCHAR *szPath)
{
  _TDIR *nd;
  unsigned int rc;
  _TCHAR szFullPath[MAX_PATH];

  errno = 0;

  if (!szPath)
    {
      errno = EFAULT;
      return (_TDIR *) 0;
    }

  if (szPath[0] == _T('\0'))
    {
      errno = ENOTDIR;
      return (_TDIR *) 0;
    }

  /* Attempt to determine if the given path really is a directory. */
  rc = GetFileAttributesW (szPath);
  if (rc == INVALID_FILE_ATTRIBUTES)
    {
      /* call GetLastError for more error info */
      errno = ENOENT;
      return (_TDIR *) 0;
    }
  if (!(rc & FILE_ATTRIBUTE_DIRECTORY))
    {
      /* Error, entry exists but not a directory. */
      errno = ENOTDIR;
      return (_TDIR *) 0;
    }

  /* Make an absolute pathname.  */
  _tfullpath (szFullPath, szPath, MAX_PATH);

  /* Allocate enough space to store DIR structure and the complete
   * directory path given. */
  nd = (_TDIR *) malloc (sizeof (_TDIR) + (_tcslen (szFullPath)
					   + _tcslen (SLASH)
					   + _tcslen (SUFFIX) + 1)
					  * sizeof (_TCHAR));

  if (!nd)
    {
      /* Error, out of memory. */
      errno = ENOMEM;
      return (_TDIR *) 0;
    }

  /* Create the search expression. */
  _tcscpy (nd->dd_name, szFullPath);

  /* Add on a slash if the path does not end with one. */
  if (nd->dd_name[0] != _T('\0') &&
      nd->dd_name[_tcslen (nd->dd_name) - 1] != _T('/') &&
      nd->dd_name[_tcslen (nd->dd_name) - 1] != _T('\\'))
    {
      _tcscat (nd->dd_name, SLASH);
    }

  /* Add on the search pattern */
  _tcscat (nd->dd_name, SUFFIX);

  /* Initialize handle to -1 so that a premature closedir doesn't try
   * to call _findclose on it. */
  nd->dd_handle = -1;

  /* Initialize the status. */
  nd->dd_stat = 0;

  /* Initialize the dirent structure. ino and reclen are invalid under
   * Win32, and name simply points at the appropriate part of the
   * findfirst_t structure. */
  nd->dd_dir.d_ino = 0;
  nd->dd_dir.d_reclen = 0;
  nd->dd_dir.d_namlen = 0;
  memset (nd->dd_dir.d_name, 0, 260 /*FILENAME_MAX*/);

  return nd;
}
Пример #12
0
static void setup_environment(LPWSTR top_level_path, int full_path)
{
	WCHAR msystem[64];
	LPWSTR path2 = NULL;
	int len;

	/* Set MSYSTEM */
	swprintf(msystem, sizeof(msystem),
		L"MINGW%d", (int) sizeof(void *) * 8);
	SetEnvironmentVariable(L"MSYSTEM", msystem);

	/* if not set, set PLINK_PROTOCOL to ssh */
	if (!GetEnvironmentVariable(L"PLINK_PROTOCOL", NULL, 0))
		SetEnvironmentVariable(L"PLINK_PROTOCOL", L"ssh");

	/*
	 * set HOME to %HOMEDRIVE%%HOMEPATH% or %USERPROFILE%
	 * With roaming profiles: HOMEPATH is the roaming location and
	 * USERPROFILE is the local location
	 */
	if (!GetEnvironmentVariable(L"HOME", NULL, 0)) {
		LPWSTR e = NULL;
		len = GetEnvironmentVariable(L"HOMEPATH", NULL, 0);
		if (len) {
			DWORD attr, drvlen = GetEnvironmentVariable(L"HOMEDRIVE", NULL, 0);
			e = (LPWSTR)malloc(sizeof(WCHAR) * (drvlen + len));
			drvlen = GetEnvironmentVariable(L"HOMEDRIVE", e, drvlen);
			GetEnvironmentVariable(L"HOMEPATH", e + drvlen, len);
			/* check if the path exists */
			attr = GetFileAttributesW(e);
			if (attr != INVALID_FILE_ATTRIBUTES
					&& (attr & FILE_ATTRIBUTE_DIRECTORY))
				SetEnvironmentVariable(L"HOME", e);
			else
				len = 0; /* use USERPROFILE */
			free(e);
		}

		if (len == 0) {
			len = GetEnvironmentVariable(L"USERPROFILE", NULL, 0);
			if (len != 0) {
				e = (LPWSTR)malloc(len * sizeof(WCHAR));
				GetEnvironmentVariable(L"USERPROFILE", e, len);
				SetEnvironmentVariable(L"HOME", e);
				free(e);
			}
		}
	}

	/* extend the PATH */
	len = GetEnvironmentVariable(L"PATH", NULL, 0);
	len = sizeof(WCHAR) * (len + 3 * MAX_PATH);
	path2 = (LPWSTR)malloc(len);
	wcscpy(path2, top_level_path);
	if (!full_path)
		PathAppend(path2, L"cmd;");
	else {
		PathAppend(path2, msystem_bin);
		if (_waccess(path2, 0) != -1) {
			/* We are in an MSys2-based setup */
			int len2 = GetEnvironmentVariable(L"HOME", NULL, 0);

			wcscat(path2, L";");
			wcscat(path2, top_level_path);
			PathAppend(path2, L"usr\\bin;");
			if (len2 + 6 < MAX_PATH) {
				GetEnvironmentVariable(L"HOME",
						path2 + wcslen(path2), len2);
				PathAppend(path2, L"bin;");
			}
		}
		else {
			/* Fall back to MSys1 paths */
			wcscpy(path2, top_level_path);
			PathAppend(path2, L"bin;");
			wcscat(path2, top_level_path);
			PathAppend(path2, L"mingw\\bin;");
		}
	}
	GetEnvironmentVariable(L"PATH", path2 + wcslen(path2),
				(len / sizeof(WCHAR)) - wcslen(path2));
	SetEnvironmentVariable(L"PATH", path2);
	free(path2);

}
Пример #13
0
bool path_exists(const std::string &path)
{
	DWORD dwAttrib = GetFileAttributesW(utf8_to_utf16(path).c_str());
	return dwAttrib != INVALID_FILE_ATTRIBUTES;
}
Пример #14
0
posix_errno_t efile_read_info(const efile_path_t *path, int follow_links, efile_fileinfo_t *result) {
    BY_HANDLE_FILE_INFORMATION native_file_info;
    DWORD attributes;
    int is_link;

    sys_memset(&native_file_info, 0, sizeof(native_file_info));
    is_link = 0;

    attributes = GetFileAttributesW((WCHAR*)path->data);

    if(attributes == INVALID_FILE_ATTRIBUTES) {
        DWORD last_error = GetLastError();

        /* Querying a network share root fails with ERROR_BAD_NETPATH, so we'll
         * fake it as a directory just like local roots. */
        if(!is_path_root(path) || last_error != ERROR_BAD_NETPATH) {
            return windows_to_posix_errno(last_error);
        }

        attributes = FILE_ATTRIBUTE_DIRECTORY;
    } else if(is_path_root(path)) {
        /* Local (or mounted) roots can be queried with GetFileAttributesW but
         * lack support for GetFileInformationByHandle, so we'll skip that
         * part. */
    } else {
        HANDLE handle;

        if(attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
            is_link = is_name_surrogate(path);
        }

        if(follow_links && is_link) {
            posix_errno_t posix_errno;
            efile_path_t resolved_path;

            posix_errno = internal_read_link(path, &resolved_path);

            if(posix_errno != 0) {
                return posix_errno;
            }

            return efile_read_info(&resolved_path, 0, result);
        }

        handle = CreateFileW((const WCHAR*)path->data, GENERIC_READ,
            FILE_SHARE_FLAGS, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS,
            NULL);

        /* The old driver never cared whether this succeeded. */
        if(handle != INVALID_HANDLE_VALUE) {
            GetFileInformationByHandle(handle, &native_file_info);
            CloseHandle(handle);
        }

        FILETIME_TO_EPOCH(result->m_time, native_file_info.ftLastWriteTime);
        FILETIME_TO_EPOCH(result->a_time, native_file_info.ftLastAccessTime);
        FILETIME_TO_EPOCH(result->c_time, native_file_info.ftCreationTime);

        if(result->m_time == -EPOCH_DIFFERENCE) {
            /* Default to 1970 just like the old driver. */
            result->m_time = 0;
        }

        if(result->a_time == -EPOCH_DIFFERENCE) {
            result->a_time = result->m_time;
        }

        if(result->c_time == -EPOCH_DIFFERENCE) {
            result->c_time = result->m_time;
        }
    }

    if(is_link) {
        result->type = EFILE_FILETYPE_SYMLINK;
        /* This should be _S_IFLNK, but the old driver always set
         * non-directories to _S_IFREG. */
        result->mode |= _S_IFREG;
    } else if(attributes & FILE_ATTRIBUTE_DIRECTORY) {
        result->type = EFILE_FILETYPE_DIRECTORY;
        result->mode |= _S_IFDIR | _S_IEXEC;
    } else {
        if(is_executable_file(path)) {
            result->mode |= _S_IEXEC;
        }

        result->type = EFILE_FILETYPE_REGULAR;
        result->mode |= _S_IFREG;
    }

    if(!(attributes & FILE_ATTRIBUTE_READONLY)) {
        result->access = EFILE_ACCESS_READ | EFILE_ACCESS_WRITE;
        result->mode |= _S_IREAD | _S_IWRITE;
    } else {
        result->access = EFILE_ACCESS_READ;
        result->mode |= _S_IREAD;
    }

    /* Propagate user mode-bits to group/other fields */
    result->mode |= (result->mode & 0700) >> 3;
    result->mode |= (result->mode & 0700) >> 6;

    result->size =
        ((Uint64)native_file_info.nFileSizeHigh << 32ull) |
        (Uint64)native_file_info.nFileSizeLow;

    result->links = MAX(1, native_file_info.nNumberOfLinks);

    result->major_device = get_drive_number(path);
    result->minor_device = 0;
    result->inode = 0;
    result->uid = 0;
    result->gid = 0;

    return 0;
}
Пример #15
0
/***********************************************************************
 *      SetupCopyOEMInfW  (SETUPAPI.@)
 */
BOOL WINAPI SetupCopyOEMInfW( PCWSTR source, PCWSTR location,
                              DWORD media_type, DWORD style, PWSTR dest,
                              DWORD buffer_size, PDWORD required_size, PWSTR *component )
{
    BOOL ret = FALSE;
    WCHAR target[MAX_PATH], catalog_file[MAX_PATH], *p;
    static const WCHAR inf[] = { '\\','i','n','f','\\',0 };
    static const WCHAR wszVersion[] = { 'V','e','r','s','i','o','n',0 };
    static const WCHAR wszCatalogFile[] = { 'C','a','t','a','l','o','g','F','i','l','e',0 };
    DWORD size;
    HINF hinf;

    TRACE("%s, %s, %d, %d, %p, %d, %p, %p\n", debugstr_w(source), debugstr_w(location),
          media_type, style, dest, buffer_size, required_size, component);

    if (!source)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    /* check for a relative path */
    if (!(*source == '\\' || (*source && source[1] == ':')))
    {
        SetLastError(ERROR_FILE_NOT_FOUND);
        return FALSE;
    }

    if (!GetWindowsDirectoryW( target, sizeof(target)/sizeof(WCHAR) )) return FALSE;

    strcatW( target, inf );
    if ((p = strrchrW( source, '\\' )))
        strcatW( target, p + 1 );

    /* does the file exist already? */
    if ((GetFileAttributesW( target ) != INVALID_FILE_ATTRIBUTES) &&
        !(style & SP_COPY_NOOVERWRITE))
    {
        static const WCHAR oem[] = { 'o','e','m',0 };
        unsigned int i;
        LARGE_INTEGER source_file_size;
        HANDLE source_file;

        source_file = CreateFileW( source, FILE_READ_DATA | FILE_READ_ATTRIBUTES,
                                   FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                                   NULL, OPEN_EXISTING, 0, NULL );
        if (source_file == INVALID_HANDLE_VALUE)
            return FALSE;

        if (!GetFileSizeEx( source_file, &source_file_size ))
        {
            CloseHandle( source_file );
            return FALSE;
        }

        p = strrchrW( target, '\\' ) + 1;
        memcpy( p, oem, sizeof(oem) );
        p += sizeof(oem)/sizeof(oem[0]) - 1;

        /* generate OEMnnn.inf ending */
        for (i = 0; i < OEM_INDEX_LIMIT; i++)
        {
            static const WCHAR format[] = { '%','u','.','i','n','f',0 };
            HANDLE dest_file;
            LARGE_INTEGER dest_file_size;

            wsprintfW( p, format, i );
            dest_file = CreateFileW( target, FILE_READ_DATA | FILE_READ_ATTRIBUTES,
                                     FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                                     NULL, OPEN_EXISTING, 0, NULL );
            /* if we found a file name that doesn't exist then we're done */
            if (dest_file == INVALID_HANDLE_VALUE)
                break;
            /* now check if the same inf file has already been copied to the inf
             * directory. if so, use that file and don't create a new one */
            if (!GetFileSizeEx( dest_file, &dest_file_size ) ||
                (dest_file_size.QuadPart != source_file_size.QuadPart) ||
                compare_files( source_file, dest_file ))
            {
                CloseHandle( dest_file );
                continue;
            }
            CloseHandle( dest_file );
            break;
        }

        CloseHandle( source_file );
        if (i == OEM_INDEX_LIMIT)
        {
            SetLastError( ERROR_FILENAME_EXCED_RANGE );
            return FALSE;
        }
    }

    hinf = SetupOpenInfFileW( source, NULL, INF_STYLE_WIN4, NULL );
    if (hinf == INVALID_HANDLE_VALUE) return FALSE;

    if (SetupGetLineTextW( NULL, hinf, wszVersion, wszCatalogFile, catalog_file,
                           sizeof(catalog_file)/sizeof(catalog_file[0]), NULL ))
    {
        WCHAR source_cat[MAX_PATH];
        strcpyW( source_cat, source );

        p = strrchrW( source_cat, '\\' );
        if (p) p++;
        else p = source_cat;

        strcpyW( p, catalog_file );

        FIXME("install catalog file %s\n", debugstr_w( source_cat ));
    }
    SetupCloseInfFile( hinf );

    if (!(ret = CopyFileW( source, target, (style & SP_COPY_NOOVERWRITE) != 0 )))
        return ret;

    if (style & SP_COPY_DELETESOURCE)
        DeleteFileW( source );

    size = strlenW( target ) + 1;
    if (dest)
    {
        if (buffer_size >= size)
        {
            strcpyW( dest, target );
        }
        else
        {
            SetLastError( ERROR_INSUFFICIENT_BUFFER );
            ret = FALSE;
        }
    }

    if (component) *component = p + 1;
    if (required_size) *required_size = size;
    if (ret) SetLastError(ERROR_SUCCESS);

    return ret;
}
Пример #16
0
INT
SheChangeDirExW(
   register WCHAR *newdir)
{
   WCHAR wcEnvName[MAX_PATH];
   WCHAR wcNewPath[MAX_PATH];
   WCHAR wcEnvValue[MAX_PATH];

   DWORD cchPathOffset;

   WCHAR *s;
   DWORD attr;
   BOOL bUsedEnv = FALSE;

   if (newdir && *newdir &&
       ((cchPathOffset = SheGetPathOffsetW((LPWSTR)newdir)) != 0xFFFFFFFF)) {
      WCHAR wc = newdir[cchPathOffset];

      newdir[cchPathOffset] = WCHAR_NULL;
      wcscpy((LPWSTR)&wcEnvName[1], (LPWSTR)newdir);

      newdir[cchPathOffset] = wc;
      newdir += cchPathOffset;

   } else {

      GetCurrentDirectoryW(MAX_PATH, wcEnvValue);

      wcscpy((LPWSTR)&wcEnvName[1], (LPWSTR)wcEnvValue);
   }

   wcEnvName[0] = WCHAR_EQUAL;
   if ((cchPathOffset = SheGetPathOffsetW((LPWSTR)&wcEnvName[1])) != 0xFFFFFFFF) {

      // add one since the first character is "="
      wcEnvName[cchPathOffset + 1] = WCHAR_NULL;
   }

   //
   // If return value is 2, then we are a drive letter like A:
   // We need to uppercase the drive letter here, since the environ
   // vars are usually set as uppercase.
   //
   if (cchPathOffset == 2) {

      wcEnvName[1] = (WCHAR)(DWORD)CharUpper((LPWSTR)(DWORD) wcEnvName[1]);
   }

   if (newdir && *newdir &&
       ((*newdir == WCHAR_BSLASH) || (*newdir == WCHAR_SLASH))) {

      wcscpy((LPWSTR)wcNewPath, (LPWSTR)&wcEnvName[1]);
      if (lstrlen(wcNewPath) + lstrlen(newdir) < MAX_PATH ) {
          lstrcat((LPWSTR)wcNewPath, (LPWSTR)newdir);
      }

   } else {
      LPWSTR lpszEnvName;

      if (NULL != (lpszEnvName = (LPWSTR)SheGetEnvVarW(wcEnvName))) {

         wcscpy((LPWSTR)wcNewPath, lpszEnvName);
         bUsedEnv = TRUE;

      } else {

         wcscpy((LPWSTR)wcNewPath, (LPWSTR)&wcEnvName[1]);
      }

      if (newdir && *newdir) {
         if (wcNewPath[lstrlen(wcNewPath)-1] != WCHAR_BSLASH) {
            lstrcat((LPWSTR)wcNewPath, TEXT("\\"));
         }
         if (lstrlen(wcNewPath) + lstrlen(newdir) < MAX_PATH ) {
             lstrcat((LPWSTR)wcNewPath, (LPWSTR)newdir);
         }
      }
   }

   if (!GetFullPathNameW((LPWSTR)wcNewPath, MAX_PATH, wcEnvValue, &s)) {
      return( ERROR_ACCESS_DENIED );
   }

   attr = GetFileAttributesW((LPWSTR)wcEnvValue);

   if ((attr == 0xFFFFFFFF ||
       ((attr & FILE_ATTRIBUTE_DIRECTORY) &&
         !SetCurrentDirectoryW((LPWSTR)wcEnvValue)))
       && bUsedEnv ) {

      wcscpy((LPWSTR)wcEnvValue, (LPWSTR)&wcEnvName[1]);
      lstrcat((LPWSTR)wcEnvValue, TEXT("\\"));

      attr = GetFileAttributesW((LPWSTR)wcEnvValue);

   }

   if (attr == 0xFFFFFFFF || !(attr & FILE_ATTRIBUTE_DIRECTORY)) {

      return(ERROR_ACCESS_DENIED);
   }

   if (!SetCurrentDirectoryW((LPWSTR)wcEnvValue)) {
      return( ERROR_ACCESS_DENIED );
   }

   // It's ok if this fails
   SheSetEnvVarW(wcEnvName, wcEnvValue);

   wcscpy(CurDrvDirW, (LPWSTR)wcEnvValue);   // this seems right to me.
   return(SUCCESS) ;
}
Пример #17
0
static void
locate_pythons_for_key(HKEY root, REGSAM flags)
{
    HKEY core_root, ip_key;
    LSTATUS status = RegOpenKeyExW(root, CORE_PATH, 0, flags, &core_root);
    wchar_t message[MSGSIZE];
    DWORD i;
    size_t n;
    BOOL ok;
    DWORD type, data_size, attrs;
    INSTALLED_PYTHON * ip, * pip;
    wchar_t ip_version[IP_VERSION_SIZE];
    wchar_t ip_path[IP_SIZE];
    wchar_t * check;
    wchar_t ** checkp;
    wchar_t *key_name = (root == HKEY_LOCAL_MACHINE) ? L"HKLM" : L"HKCU";

    if (status != ERROR_SUCCESS)
        debug(L"locate_pythons_for_key: unable to open PythonCore key in %ls\n",
              key_name);
    else {
        ip = &installed_pythons[num_installed_pythons];
        for (i = 0; num_installed_pythons < MAX_INSTALLED_PYTHONS; i++) {
            status = RegEnumKeyW(core_root, i, ip_version, IP_VERSION_SIZE);
            if (status != ERROR_SUCCESS) {
                if (status != ERROR_NO_MORE_ITEMS) {
                    /* unexpected error */
                    winerror(status, message, MSGSIZE);
                    debug(L"Can't enumerate registry key for version %ls: %ls\n",
                          ip_version, message);
                }
                break;
            }
            else {
                wcsncpy_s(ip->version, MAX_VERSION_SIZE, ip_version,
                          MAX_VERSION_SIZE-1);
                _snwprintf_s(ip_path, IP_SIZE, _TRUNCATE,
                             L"%ls\\%ls\\InstallPath", CORE_PATH, ip_version);
                status = RegOpenKeyExW(root, ip_path, 0, flags, &ip_key);
                if (status != ERROR_SUCCESS) {
                    winerror(status, message, MSGSIZE);
                    // Note: 'message' already has a trailing \n
                    debug(L"%ls\\%ls: %ls", key_name, ip_path, message);
                    continue;
                }
                data_size = sizeof(ip->executable) - 1;
                status = RegQueryValueExW(ip_key, NULL, NULL, &type,
                                          (LPBYTE)ip->executable, &data_size);
                RegCloseKey(ip_key);
                if (status != ERROR_SUCCESS) {
                    winerror(status, message, MSGSIZE);
                    debug(L"%ls\\%ls: %ls\n", key_name, ip_path, message);
                    continue;
                }
                if (type == REG_SZ) {
                    data_size = data_size / sizeof(wchar_t) - 1;  /* for NUL */
                    if (ip->executable[data_size - 1] == L'\\')
                        --data_size; /* reg value ended in a backslash */
                    /* ip->executable is data_size long */
                    for (checkp = location_checks; *checkp; ++checkp) {
                        check = *checkp;
                        _snwprintf_s(&ip->executable[data_size],
                                     MAX_PATH - data_size,
                                     MAX_PATH - data_size,
                                     L"%ls%ls", check, PYTHON_EXECUTABLE);
                        attrs = GetFileAttributesW(ip->executable);
                        if (attrs == INVALID_FILE_ATTRIBUTES) {
                            winerror(GetLastError(), message, MSGSIZE);
                            debug(L"locate_pythons_for_key: %ls: %ls",
                                  ip->executable, message);
                        }
                        else if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
                            debug(L"locate_pythons_for_key: '%ls' is a \
directory\n",
                                  ip->executable, attrs);
                        }
                        else if (find_existing_python(ip->executable)) {
                            debug(L"locate_pythons_for_key: %ls: already \
found\n", ip->executable);
                        }
                        else {
                            /* check the executable type. */
                            ok = GetBinaryTypeW(ip->executable, &attrs);
                            if (!ok) {
                                debug(L"Failure getting binary type: %ls\n",
                                      ip->executable);
                            }
                            else {
                                if (attrs == SCS_64BIT_BINARY)
                                    ip->bits = 64;
                                else if (attrs == SCS_32BIT_BINARY)
                                    ip->bits = 32;
                                else
                                    ip->bits = 0;
                                if (ip->bits == 0) {
                                    debug(L"locate_pythons_for_key: %ls: \
invalid binary type: %X\n",
                                          ip->executable, attrs);
                                }
                                else {
                                    if (wcschr(ip->executable, L' ') != NULL) {
                                        /* has spaces, so quote */
                                        n = wcslen(ip->executable);
                                        memmove(&ip->executable[1],
                                                ip->executable, n * sizeof(wchar_t));
                                        ip->executable[0] = L'\"';
                                        ip->executable[n + 1] = L'\"';
                                        ip->executable[n + 2] = L'\0';
                                    }
                                    debug(L"locate_pythons_for_key: %ls \
is a %dbit executable\n",
                                        ip->executable, ip->bits);
                                    ++num_installed_pythons;
                                    pip = ip++;
                                    if (num_installed_pythons >=
                                        MAX_INSTALLED_PYTHONS)
                                        break;
                                    /* Copy over the attributes for the next */
                                    *ip = *pip;
                                }
                            }
                        }
                    }
Пример #18
0
UINT __stdcall UpdateHostOnlyInterfaces(MSIHANDLE hModule)
{
#ifdef VBOX_WITH_NETFLT
    netCfgLoggerEnable(hModule);

    logStringW(hModule, L"UpdateHostOnlyInterfaces: Updating all host-only interfaces");

    BOOL bSetupModeInteractive = SetupSetNonInteractiveMode(FALSE);

    WCHAR wszMpInf[MAX_PATH];
    DWORD cchMpInf = RT_ELEMENTS(wszMpInf) - sizeof("VBoxNetAdp.inf") - 1;
    LPCWSTR pwszInfPath = NULL;
    bool bIsFile = false;
    UINT uErr = MsiGetPropertyW(hModule, L"CustomActionData", wszMpInf, &cchMpInf);
    if (uErr == ERROR_SUCCESS)
    {
        if (cchMpInf)
        {
            logStringW(hModule, L"UpdateHostOnlyInterfaces: NetAdpDir property = %s", wszMpInf);
            if (wszMpInf[cchMpInf - 1] != L'\\')
            {
                wszMpInf[cchMpInf++] = L'\\';
                wszMpInf[cchMpInf]   = L'\0';
            }

            wcscat(wszMpInf, L"VBoxNetAdp.inf");
            pwszInfPath = wszMpInf;
            bIsFile = true;

            logStringW(hModule, L"UpdateHostOnlyInterfaces: Resulting INF path = %s", pwszInfPath);

            DWORD attrFile = GetFileAttributesW(pwszInfPath);
            if (attrFile == INVALID_FILE_ATTRIBUTES)
            {
                DWORD dwErr = GetLastError();
                logStringW(hModule, L"UpdateHostOnlyInterfaces: File \"%s\" not found, dwErr=%ld",
                           pwszInfPath, dwErr);
            }
            else
            {
                logStringW(hModule, L"UpdateHostOnlyInterfaces: File \"%s\" exists",
                           pwszInfPath);

                BOOL fRebootRequired = FALSE;
                HRESULT hr = VBoxNetCfgWinUpdateHostOnlyNetworkInterface(pwszInfPath, &fRebootRequired);
                if (SUCCEEDED(hr))
                {
                    if (fRebootRequired)
                    {
                        logStringW(hModule, L"UpdateHostOnlyInterfaces: Reboot required, setting REBOOT property to force");
                        HRESULT hr2 = MsiSetPropertyW(hModule, L"REBOOT", L"Force");
                        if (hr2 != ERROR_SUCCESS)
                            logStringW(hModule, L"UpdateHostOnlyInterfaces: Failed to set REBOOT property, error = 0x%x", hr2);
                    }
                }
                else
                    logStringW(hModule, L"UpdateHostOnlyInterfaces: VBoxNetCfgWinUpdateHostOnlyNetworkInterface failed, hr = 0x%x", hr);
            }
        }
        else
            logStringW(hModule, L"UpdateHostOnlyInterfaces: VBox installation path is empty");
    }
    else
        logStringW(hModule, L"UpdateHostOnlyInterfaces: Unable to retrieve VBox installation path, error = 0x%x", uErr);

    /* Restore original setup mode. */
    if (bSetupModeInteractive)
        SetupSetNonInteractiveMode(bSetupModeInteractive);

    netCfgLoggerDisable();
#endif /* VBOX_WITH_NETFLT */

    /* Never fail the install even if we did not succeed. */
    return ERROR_SUCCESS;
}
nsresult TestWinAttribs()
{
    if (!IsXPOrGreater())
      return NS_OK;
  
    printf("Is XP or greater, running tests...\n");

    nsresult rv;

    // File variables
    HANDLE hIndexed;
    nsCOMPtr<nsIFile> localFile;
    WCHAR filePath[MAX_PATH];

    // Create and open temporary file
    hIndexed = CreateFileW(L".\\indexbit.txt", 
                            GENERIC_READ | GENERIC_WRITE,
                            0, 
                            NULL,
                            CREATE_ALWAYS,        
                            FILE_ATTRIBUTE_NORMAL, //FILE_ATTRIBUTE_NOT_CONTENT_INDEXED, not supported by cf
                            NULL);  

    if(hIndexed == INVALID_HANDLE_VALUE)
    {
        fail("Test Win Attribs: Creating Test File");
        return NS_ERROR_FAILURE;
    }

    CloseHandle(hIndexed);

    GetFullPathNameW((LPCWSTR)L".\\indexbit.txt", 
                        MAX_PATH, filePath, NULL);

    //wprintf(filePath);
    //wprintf(L"\n");

    rv = NS_NewLocalFile(nsEmbedString(filePath), false,
                         getter_AddRefs(localFile));
    if (NS_FAILED(rv))
    {
        fail("Test Win Attribs: Opening Test File");
        DeleteFileW(filePath);
        return rv;
    }

    nsCOMPtr<nsILocalFileWin> localFileWin(do_QueryInterface(localFile));

    DWORD dwAttrs = GetFileAttributesW(filePath);
    if (dwAttrs == INVALID_FILE_ATTRIBUTES)
    {
        fail("Test Win Attribs: GetFileAttributesW - couldn't find our temp file.");
        DeleteFileW(filePath);
        return NS_ERROR_FAILURE;
    }

    dwAttrs |= FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
    SetFileAttributesW(filePath, dwAttrs);

    uint32_t attribs = 0;
    rv = localFileWin->GetFileAttributesWin(&attribs);
    
    if (NS_FAILED(rv))
    {
        fail("Test Win Attribs: GetFileAttributesWin failed to GET attributes. (1)");
        DeleteFileW(filePath);
        return NS_ERROR_FAILURE;
    }
    
    if (attribs & nsILocalFileWin::WFA_SEARCH_INDEXED)
    {
        fail("Test Win Attribs: GetFileAttributesWin attributed did not match. (2)");
        DeleteFileW(filePath);
        return NS_ERROR_FAILURE;
    }

    dwAttrs &= ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
    SetFileAttributesW(filePath, dwAttrs);

    rv = localFileWin->GetFileAttributesWin(&attribs);
    
    if (NS_FAILED(rv))
    {
        fail("Test Win Attribs: GetFileAttributesWin failed to GET attributes. (3)");
        DeleteFileW(filePath);
        return NS_ERROR_FAILURE;
    }

    if (!(attribs & nsILocalFileWin::WFA_SEARCH_INDEXED))
    {
        fail("Test Win Attribs: GetFileAttributesWin attributed did not match. (4)");
        DeleteFileW(filePath);
        return NS_ERROR_FAILURE;
    }

    dwAttrs &= ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
    SetFileAttributesW(filePath, dwAttrs);

    attribs = nsILocalFileWin::WFA_SEARCH_INDEXED;
    rv = localFileWin->SetFileAttributesWin(attribs);

    dwAttrs = GetFileAttributesW(filePath);

    if (NS_FAILED(rv))
    {
        fail("Test Win Attribs: GetFileAttributesWin failed to SET attributes. (5)");
        DeleteFileW(filePath);
        return NS_ERROR_FAILURE;
    }

    if (dwAttrs & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED)
    {
        fail("Test Win Attribs: SetFileAttributesWin attributed did not match. (6)");
        DeleteFileW(filePath);
        return NS_ERROR_FAILURE;
    }
    
    dwAttrs |= FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
    SetFileAttributesW(filePath, dwAttrs);

    attribs = 0;
    rv = localFileWin->SetFileAttributesWin(attribs);

    dwAttrs = GetFileAttributesW(filePath);

    if (NS_FAILED(rv))
    {
        fail("Test Win Attribs: GetFileAttributesWin failed to SET attributes. (7)");
        DeleteFileW(filePath);
        return NS_ERROR_FAILURE;
    }

    if (!(dwAttrs & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED))
    {
        fail("Test Win Attribs: SetFileAttributesWin attributed did not match. (8)");
        DeleteFileW(filePath);
        return NS_ERROR_FAILURE;
    }

    DeleteFileW(filePath);

    passed("Test Win Attribs: passed tests.");

    return NS_OK;
}
Пример #20
0
/***********************************************************************
 *             GetVersionFromFileExW   (ADVPACK.@)
 *
 * Gets the files version or language information.
 *
 * PARAMS
 *   lpszFilename [I] The file to get the info from.
 *   pdwMSVer     [O] Major version.
 *   pdwLSVer     [O] Minor version.
 *   bVersion     [I] Whether to retrieve version or language info.
 *
 * RETURNS
 *   Always returns S_OK.
 *
 * NOTES
 *   If bVersion is TRUE, version information is retrieved, else
 *   pdwMSVer gets the language ID and pdwLSVer gets the codepage ID.
 */
HRESULT WINAPI GetVersionFromFileExW(LPCWSTR lpszFilename, LPDWORD pdwMSVer,
                                     LPDWORD pdwLSVer, BOOL bVersion )
{
    VS_FIXEDFILEINFO *pFixedVersionInfo;
    LANGANDCODEPAGE *pLangAndCodePage;
    DWORD dwHandle, dwInfoSize;
    WCHAR szWinDir[MAX_PATH];
    WCHAR szFile[MAX_PATH];
    LPVOID pVersionInfo = NULL;
    BOOL bFileCopied = FALSE;
    UINT uValueLen;

    static const WCHAR backslash[] = {'\\',0};
    static const WCHAR translation[] = {
        '\\','V','a','r','F','i','l','e','I','n','f','o',
        '\\','T','r','a','n','s','l','a','t','i','o','n',0
    };

    TRACE("(%s, %p, %p, %d)\n", debugstr_w(lpszFilename),
          pdwMSVer, pdwLSVer, bVersion);

    *pdwLSVer = 0;
    *pdwMSVer = 0;

    lstrcpynW(szFile, lpszFilename, MAX_PATH);

    dwInfoSize = GetFileVersionInfoSizeW(szFile, &dwHandle);
    if (!dwInfoSize)
    {
        /* check that the file exists */
        if (GetFileAttributesW(szFile) == INVALID_FILE_ATTRIBUTES)
            return S_OK;

        /* file exists, but won't be found by GetFileVersionInfoSize,
        * so copy it to the temp dir where it will be found.
        */
        GetWindowsDirectoryW(szWinDir, MAX_PATH);
        GetTempFileNameW(szWinDir, NULL, 0, szFile);
        CopyFileW(lpszFilename, szFile, FALSE);
        bFileCopied = TRUE;

        dwInfoSize = GetFileVersionInfoSizeW(szFile, &dwHandle);
        if (!dwInfoSize)
            goto done;
    }

    pVersionInfo = HeapAlloc(GetProcessHeap(), 0, dwInfoSize);
    if (!pVersionInfo)
        goto done;

    if (!GetFileVersionInfoW(szFile, dwHandle, dwInfoSize, pVersionInfo))
        goto done;

    if (bVersion)
    {
        if (!VerQueryValueW(pVersionInfo, backslash,
            (LPVOID *)&pFixedVersionInfo, &uValueLen))
            goto done;

        if (!uValueLen)
            goto done;

        *pdwMSVer = pFixedVersionInfo->dwFileVersionMS;
        *pdwLSVer = pFixedVersionInfo->dwFileVersionLS;
    }
    else
    {
        if (!VerQueryValueW(pVersionInfo, translation,
             (LPVOID *)&pLangAndCodePage, &uValueLen))
            goto done;

        if (!uValueLen)
            goto done;

        *pdwMSVer = pLangAndCodePage->wLanguage;
        *pdwLSVer = pLangAndCodePage->wCodePage;
    }

done:
    HeapFree(GetProcessHeap(), 0, pVersionInfo);

    if (bFileCopied)
        DeleteFileW(szFile);

    return S_OK;
}
Пример #21
0
/**
 * Simple inline helper to check if a given path exists, and
 * represent a folder.
 */
static inline bool is_folder(wchar_t* path)
{
	return GetFileAttributesW((const wchar_t*)path) & FILE_ATTRIBUTE_DIRECTORY;
}
Пример #22
0
static HRESULT DELNODE_recurse_dirtree(LPWSTR fname, DWORD flags)
{
    DWORD fattrs = GetFileAttributesW(fname);
    HRESULT ret = E_FAIL;

    static const WCHAR asterisk[] = {'*',0};
    static const WCHAR dot[] = {'.',0};
    static const WCHAR dotdot[] = {'.','.',0};

    if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
    {
        HANDLE hFindFile;
        WIN32_FIND_DATAW w32fd;
        BOOL done = TRUE;
        int fname_len = lstrlenW(fname);

        /* Generate a path with wildcard suitable for iterating */
        if (fname_len && fname[fname_len-1] != '\\') fname[fname_len++] = '\\';
        lstrcpyW(fname + fname_len, asterisk);

        if ((hFindFile = FindFirstFileW(fname, &w32fd)) != INVALID_HANDLE_VALUE)
        {
            /* Iterate through the files in the directory */
            for (done = FALSE; !done; done = !FindNextFileW(hFindFile, &w32fd))
            {
                TRACE("%s\n", debugstr_w(w32fd.cFileName));
                if (lstrcmpW(dot, w32fd.cFileName) != 0 &&
                    lstrcmpW(dotdot, w32fd.cFileName) != 0)
                {
                    lstrcpyW(fname + fname_len, w32fd.cFileName);
                    if (DELNODE_recurse_dirtree(fname, flags) != S_OK)
                    {
                        break; /* Failure */
                    }
                }
            }
            FindClose(hFindFile);
        }

        /* We're done with this directory, so restore the old path without wildcard */
        *(fname + fname_len) = '\0';

        if (done)
        {
            TRACE("%s: directory\n", debugstr_w(fname));
            if (SetFileAttributesW(fname, FILE_ATTRIBUTE_NORMAL) && RemoveDirectoryW(fname))
            {
                ret = S_OK;
            }
        }
    }
    else
    {
        TRACE("%s: file\n", debugstr_w(fname));
        if (SetFileAttributesW(fname, FILE_ATTRIBUTE_NORMAL) && DeleteFileW(fname))
        {
            ret = S_OK;
        }
    }
    
    return ret;
}
Пример #23
0
static
DWORD WINAPI
ThreadFunc(LPVOID Context)
{
    CComPtr<IBindStatusCallback> dl;
    WCHAR path[MAX_PATH];
    LPWSTR p;
    HWND Dlg = (HWND) Context;
    ULONG dwContentLen, dwBytesWritten, dwBytesRead, dwStatus;
    ULONG dwCurrentBytesRead = 0;
    ULONG dwStatusLen = sizeof(dwStatus);
    BOOL bCancelled = FALSE;
    BOOL bTempfile = FALSE;
    BOOL bCab = FALSE;
    HINTERNET hOpen = NULL;
    HINTERNET hFile = NULL;
    HANDLE hOut = INVALID_HANDLE_VALUE;
    unsigned char lpBuffer[4096];
    PCWSTR lpszAgent = L"RApps/1.0";
    URL_COMPONENTS urlComponents;
    size_t urlLength;

    /* built the path for the download */
    p = wcsrchr(AppInfo->szUrlDownload, L'/');

    if (!p)
        goto end;

        if (wcscmp(AppInfo->szUrlDownload, APPLICATION_DATABASE_URL) == 0)
        {
            bCab = TRUE;
            if (!GetStorageDirectory(path, sizeof(path) / sizeof(path[0])))
                goto end;
        }
        else
        {
            if (FAILED(StringCbCopyW(path, sizeof(path),  SettingsInfo.szDownloadDir)))
                goto end;
        }


    if (GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES)
    {
        if (!CreateDirectoryW(path, NULL))
            goto end;
    }

    if (FAILED(StringCbCatW(path, sizeof(path), L"\\")))
        goto end;
    if (FAILED(StringCbCatW(path, sizeof(path), p + 1)))
        goto end;

    /* download it */
    bTempfile = TRUE;
    CDownloadDialog_Constructor(Dlg, &bCancelled, IID_PPV_ARG(IBindStatusCallback, &dl));

    if (dl == NULL)
        goto end;

    switch(SettingsInfo.Proxy)
    {
        case 0: /* preconfig */
            hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
            break;
        case 1: /* direct (no proxy) */
            hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
            break;
        case 2: /* use proxy */
            hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PROXY, SettingsInfo.szProxyServer, SettingsInfo.szNoProxyFor, 0);
            break;
        default: /* preconfig */
            hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
            break;
    }

    if (!hOpen)
        goto end;

    hFile = InternetOpenUrlW(hOpen, AppInfo->szUrlDownload, NULL, 0, INTERNET_FLAG_PRAGMA_NOCACHE|INTERNET_FLAG_KEEP_CONNECTION, 0);
    if (!hFile)
        goto end;

    if (!HttpQueryInfoW(hFile, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwStatus, &dwStatusLen, NULL))
        goto end;

    if(dwStatus != HTTP_STATUS_OK)
    {
        WCHAR szMsgText[MAX_STR_LEN];

        if (!LoadStringW(hInst, IDS_UNABLE_TO_DOWNLOAD, szMsgText, sizeof(szMsgText) / sizeof(WCHAR)))
            goto end;

        MessageBoxW(hMainWnd, szMsgText, NULL, MB_OK | MB_ICONERROR);
        goto end;
    }

    dwStatusLen = sizeof(dwStatus);

    memset(&urlComponents, 0, sizeof(urlComponents));
    urlComponents.dwStructSize = sizeof(urlComponents);

    if(FAILED(StringCbLengthW(AppInfo->szUrlDownload, sizeof(AppInfo->szUrlDownload), &urlLength)))
        goto end;
    
    urlComponents.dwSchemeLength = urlLength*sizeof(WCHAR);
    urlComponents.lpszScheme = (PWSTR)malloc(urlComponents.dwSchemeLength);
    
    if(!InternetCrackUrlW(AppInfo->szUrlDownload, urlLength+1, ICU_DECODE | ICU_ESCAPE, &urlComponents))
        goto end;
    
    if(urlComponents.nScheme == INTERNET_SCHEME_HTTP || urlComponents.nScheme == INTERNET_SCHEME_HTTPS)
        HttpQueryInfo(hFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &dwContentLen, &dwStatus, 0);

    if(urlComponents.nScheme == INTERNET_SCHEME_FTP)
        dwContentLen = FtpGetFileSize(hFile, &dwStatus);

    free(urlComponents.lpszScheme);

    hOut = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL);

    if (hOut == INVALID_HANDLE_VALUE)
        goto end;

    do
    {
        if (!InternetReadFile(hFile, lpBuffer, _countof(lpBuffer), &dwBytesRead)) goto end;
        if (!WriteFile(hOut, &lpBuffer[0], dwBytesRead, &dwBytesWritten, NULL)) goto end;
        dwCurrentBytesRead += dwBytesRead;
        dl->OnProgress(dwCurrentBytesRead, dwContentLen, 0, AppInfo->szUrlDownload);
    }
    while (dwBytesRead);

    CloseHandle(hOut);
    hOut = INVALID_HANDLE_VALUE;

    if (bCancelled)
        goto end;

    ShowWindow(Dlg, SW_HIDE);

    /* run it */
    if (!bCab)
        ShellExecuteW( NULL, L"open", path, NULL, NULL, SW_SHOWNORMAL );

end:
    if (hOut != INVALID_HANDLE_VALUE)
        CloseHandle(hOut);

    InternetCloseHandle(hFile);
    InternetCloseHandle(hOpen);

    if (bTempfile)
    {
        if (bCancelled || (SettingsInfo.bDelInstaller && !bCab))
            DeleteFileW(path);
    }

    EndDialog(Dlg, 0);

    return 0;
}
Пример #24
0
static BOOL pendingRename()
{
    static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
                                      'F','i','l','e','R','e','n','a','m','e',
                                      'O','p','e','r','a','t','i','o','n','s',0};
    static const WCHAR SessionW[] = { 'S','y','s','t','e','m','\\',
                                     'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
                                     'C','o','n','t','r','o','l','\\',
                                     'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
    WCHAR *buffer=NULL;
    const WCHAR *src=NULL, *dst=NULL;
    DWORD dataLength=0;
    HKEY hSession=NULL;
    DWORD res;

    printf("Entered\n");

    if ((res=RegOpenKeyExW(HKEY_LOCAL_MACHINE, SessionW, 0, KEY_ALL_ACCESS, &hSession))
            !=ERROR_SUCCESS)
    {
        if (res==ERROR_FILE_NOT_FOUND)
        {
            printf("The key was not found - skipping\n");
            res=TRUE;
        }
        else
        {
            printf("Couldn't open key, error %ld\n", res);
            res=FALSE;
        }

        goto end;
    }

    res=RegQueryValueExW(hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not
                                                             truely a REG_MULTI_SZ anyways */,
            NULL, &dataLength);
    if (res==ERROR_FILE_NOT_FOUND)
    {
        /* No value - nothing to do. Great! */
        printf("Value not present - nothing to rename\n");
        res=TRUE;
        goto end;
    }

    if (res!=ERROR_SUCCESS)
    {
        printf("Couldn't query value's length (%ld)\n", res);
        res=FALSE;
        goto end;
    }

    buffer=malloc(dataLength);
    if (buffer==NULL)
    {
        printf("Couldn't allocate %lu bytes for the value\n", dataLength);
        res=FALSE;
        goto end;
    }

    res=RegQueryValueExW(hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength);
    if (res!=ERROR_SUCCESS)
    {
        printf("Couldn't query value after successfully querying before (%lu),\n"
                "please report to [email protected]\n", res);
        res=FALSE;
        goto end;
    }

    /* Make sure that the data is long enough and ends with two NULLs. This
     * simplifies the code later on.
     */
    if (dataLength<2*sizeof(buffer[0]) ||
            buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
            buffer[dataLength/sizeof(buffer[0])-2]!='\0')
    {
        printf("Improper value format - doesn't end with NULL\n");
        res=FALSE;
        goto end;
    }

    for(src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
            src=dst+lstrlenW(dst)+1)
    {
        DWORD dwFlags=0;

        printf("processing next command\n");

        dst=src+lstrlenW(src)+1;

        /* We need to skip the \??\ header */
        if (src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\')
            src+=4;

        if (dst[0]=='!')
        {
            dwFlags|=MOVEFILE_REPLACE_EXISTING;
            dst++;
        }

        if (dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\')
            dst+=4;

        if (*dst!='\0')
        {
            /* Rename the file */
            MoveFileExW(src, dst, dwFlags);
        } else
        {
            /* Delete the file or directory */
			res = GetFileAttributesW (src);
            if (res != (DWORD)-1)
            {
                if ((res&FILE_ATTRIBUTE_DIRECTORY)==0)
                {
                    /* It's a file */
                    DeleteFileW(src);
                } else
                {
                    /* It's a directory */
                    RemoveDirectoryW(src);
                }
            } else
            {
                printf("couldn't get file attributes (%ld)\n", GetLastError());
            }
        }
    }

    if ((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS)
    {
        printf("Error deleting the value (%lu)\n", GetLastError());
        res=FALSE;
    } else
        res=TRUE;

end:
    if (buffer!=NULL)
        free(buffer);

    if (hSession!=NULL)
        RegCloseKey(hSession);

    return res;
}
Пример #25
0
int winAccessW(const wchar_t *path, int mode)
{
    DWORD attr = GetFileAttributesW(path);

    if(attr == 0xffffffff) return -1;
    if(mode == F_OK) return 0;

    if(mode & X_OK)
	if(!(attr & FILE_ATTRIBUTE_DIRECTORY)) { /* Directory, so OK */
	    /* Look at extension for executables */
	    wchar_t *p = wcsrchr(path, '.');
	    if(p == NULL ||
	       !((wcsicmp(p, L".exe") == 0) || (wcsicmp(p, L".com") == 0) ||
		 (wcsicmp(p, L".bat") == 0) || (wcsicmp(p, L".cmd") == 0)) )
		return -1;
	}
    {
	/* Now look for file security info */
	SECURITY_DESCRIPTOR *sdPtr = NULL;
	DWORD size = 0;
	GENERIC_MAPPING genMap;
	HANDLE hToken = NULL;
	DWORD desiredAccess = 0;
	DWORD grantedAccess = 0;
	BOOL accessYesNo = FALSE;
	PRIVILEGE_SET privSet;
	DWORD privSetSize = sizeof(PRIVILEGE_SET);
	int error;

	/* get size */
	GetFileSecurityW(path,
			 OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION
			 | DACL_SECURITY_INFORMATION, 0, 0, &size);
	error = GetLastError();
	if (error != ERROR_INSUFFICIENT_BUFFER) return -1;
	sdPtr = (SECURITY_DESCRIPTOR *) alloca(size);
	if(!GetFileSecurityW(path,
			     OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION
			     | DACL_SECURITY_INFORMATION, sdPtr, size, &size))
	    return -1;
	/*
	 * Perform security impersonation of the user and open the
	 * resulting thread token.
	 */
	if(!ImpersonateSelf(SecurityImpersonation)) return -1;
	if(!OpenThreadToken(GetCurrentThread (),
			    TOKEN_DUPLICATE | TOKEN_QUERY, FALSE,
			    &hToken)) return -1;
	if (mode & R_OK) desiredAccess |= FILE_GENERIC_READ;
	if (mode & W_OK) desiredAccess |= FILE_GENERIC_WRITE;
	if (mode & X_OK) desiredAccess |= FILE_GENERIC_EXECUTE;

	memset(&genMap, 0x0, sizeof (GENERIC_MAPPING));
	genMap.GenericRead = FILE_GENERIC_READ;
	genMap.GenericWrite = FILE_GENERIC_WRITE;
	genMap.GenericExecute = FILE_GENERIC_EXECUTE;
	genMap.GenericAll = FILE_ALL_ACCESS;
	if(!AccessCheck(sdPtr, hToken, desiredAccess, &genMap, &privSet,
			&privSetSize, &grantedAccess, &accessYesNo)) {
	    CloseHandle(hToken);
	    return -1;
	}
	CloseHandle(hToken);
	if (!accessYesNo) return -1;

	if ((mode & W_OK)
	    && !(attr & FILE_ATTRIBUTE_DIRECTORY)
	    && (attr & FILE_ATTRIBUTE_READONLY)) return -1;
    }
    return 0;
}
Пример #26
0
MVMint64 MVM_platform_unlink(const char *pathname) {
    /* Must using UTF8ToUnicode for supporting CJK Windows file name. */
    wchar_t *wpathname = UTF8ToUnicode(pathname);
    int str_len = wcslen(wpathname);
    int r;
    DWORD attrs;


    if (str_len > MAX_PATH) {
        wchar_t  abs_wpathname[4096]; /* 4096 should be enough for absolute path */
        wchar_t *lpp_part;

        /* You cannot use the "\\?\" prefix with a relative path,
         * relative paths are always limited to a total of MAX_PATH characters.
         * see http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx */
        if (!GetFullPathNameW(wpathname, 4096, abs_wpathname, &lpp_part)) {
            errno = ENOENT;
            return -1;
        }

        MVM_free(wpathname);

        str_len  = wcslen(abs_wpathname);
        wpathname = (wchar_t *)MVM_malloc((str_len + 4) * sizeof(wchar_t));
        wcscpy(wpathname, L"\\\\?\\");
        wcscat(wpathname, abs_wpathname);
    }

    attrs = GetFileAttributesW(wpathname);

    if (attrs == INVALID_FILE_ATTRIBUTES) {
        MVM_free(wpathname);
        errno = ENOENT;
        return -1;
    }
    else if (attrs & FILE_ATTRIBUTE_READONLY) {
        (void)SetFileAttributesW(wpathname, attrs & ~FILE_ATTRIBUTE_READONLY);

        r = DeleteFileW(wpathname);
        if (r == 0) {
            (void)SetFileAttributesW(wpathname, attrs);
        }

    } else {
        r = DeleteFileW(wpathname);
    }

    if (r == 0) {
        DWORD LastError = GetLastError();
        MVM_free(wpathname);

        if (LastError == ERROR_FILE_NOT_FOUND) {
            errno = ENOENT;
        }

        else if (LastError == ERROR_ACCESS_DENIED) {
            errno = EACCES;
        }

        return -1;
    }

    MVM_free(wpathname);

    return 0;
}
Пример #27
0
static UINT ACTION_AppSearchComponents(MSIPACKAGE *package, LPWSTR *appValue, MSISIGNATURE *sig)
{
    static const WCHAR query[] =  {
        'S','E','L','E','C','T',' ','*',' ',
        'F','R','O','M',' ',
        '`','C','o','m','p','L','o','c','a','t','o','r','`',' ',
        'W','H','E','R','E',' ','`','S','i','g','n','a','t','u','r','e','_','`',' ','=',' ',
        '\'','%','s','\'',0};
    static const WCHAR sigquery[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','S','i','g','n','a','t','u','r','e','`',' ',
        'W','H','E','R','E',' ','`','S','i','g','n','a','t','u','r','e','`',' ','=',' ',
        '\'','%','s','\'',0};

    MSIRECORD *row, *rec;
    LPCWSTR signature, guid;
    BOOL sigpresent = TRUE;
    BOOL isdir;
    UINT type;
    WCHAR path[MAX_PATH];
    DWORD size = MAX_PATH;
    LPWSTR ptr;
    DWORD attr;

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

    *appValue = NULL;

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

    signature = MSI_RecordGetString(row, 1);
    guid = MSI_RecordGetString(row, 2);
    type = MSI_RecordGetInteger(row, 3);

    rec = MSI_QueryGetRecord(package->db, sigquery, signature);
    if (!rec)
        sigpresent = FALSE;

    *path = '\0';
    MsiLocateComponentW(guid, path, &size);
    if (!*path)
        goto done;

    attr = GetFileAttributesW(path);
    if (attr == INVALID_FILE_ATTRIBUTES)
        goto done;

    isdir = (attr & FILE_ATTRIBUTE_DIRECTORY);

    if (type != msidbLocatorTypeDirectory && sigpresent && !isdir)
    {
        *appValue = app_search_file(path, sig);
    }
    else if (!sigpresent && (type != msidbLocatorTypeDirectory || isdir))
    {
        if (type == msidbLocatorTypeFileName)
        {
            ptr = strrchrW(path, '\\');
            *(ptr + 1) = '\0';
        }
        else
            PathAddBackslashW(path);

        *appValue = strdupW(path);
    }
    else if (sigpresent)
    {
        PathAddBackslashW(path);
        lstrcatW(path, MSI_RecordGetString(rec, 2));

        attr = GetFileAttributesW(path);
        if (attr != INVALID_FILE_ATTRIBUTES &&
            !(attr & FILE_ATTRIBUTE_DIRECTORY))
            *appValue = strdupW(path);
    }

done:
    if (rec) msiobj_release(&rec->hdr);
    msiobj_release(&row->hdr);
    return ERROR_SUCCESS;
}
Пример #28
0
int uv_fs_event_start(uv_fs_event_t* handle,
                      uv_fs_event_cb cb,
                      const char* path,
                      unsigned int flags) {
  int name_size, is_path_dir;
  DWORD attr, last_error;
  WCHAR* dir = NULL, *dir_to_watch, *pathw = NULL;
  WCHAR short_path[MAX_PATH];

  if (uv__is_active(handle))
    return UV_EINVAL;

  handle->cb = cb;
  handle->path = uv__strdup(path);
  if (!handle->path) {
    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
  }

  uv__handle_start(handle);

  /* Convert name to UTF16. */
  name_size = uv_utf8_to_utf16(path, NULL, 0) * sizeof(WCHAR);
  pathw = (WCHAR*)uv__malloc(name_size);
  if (!pathw) {
    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
  }

  if (!uv_utf8_to_utf16(path, pathw,
      name_size / sizeof(WCHAR))) {
    return uv_translate_sys_error(GetLastError());
  }

  /* Determine whether path is a file or a directory. */
  attr = GetFileAttributesW(pathw);
  if (attr == INVALID_FILE_ATTRIBUTES) {
    last_error = GetLastError();
    goto error;
  }

  is_path_dir = (attr & FILE_ATTRIBUTE_DIRECTORY) ? 1 : 0;

  if (is_path_dir) {
     /* path is a directory, so that's the directory that we will watch. */
    handle->dirw = pathw;
    dir_to_watch = pathw;
  } else {
    /*
     * path is a file.  So we split path into dir & file parts, and
     * watch the dir directory.
     */

    /* Convert to short path. */
    if (!GetShortPathNameW(pathw, short_path, ARRAY_SIZE(short_path))) {
      last_error = GetLastError();
      goto error;
    }

    if (uv_split_path(pathw, &dir, &handle->filew) != 0) {
      last_error = GetLastError();
      goto error;
    }

    if (uv_split_path(short_path, NULL, &handle->short_filew) != 0) {
      last_error = GetLastError();
      goto error;
    }

    dir_to_watch = dir;
    uv__free(pathw);
    pathw = NULL;
  }

  handle->dir_handle = CreateFileW(dir_to_watch,
                                   FILE_LIST_DIRECTORY,
                                   FILE_SHARE_READ | FILE_SHARE_DELETE |
                                     FILE_SHARE_WRITE,
                                   NULL,
                                   OPEN_EXISTING,
                                   FILE_FLAG_BACKUP_SEMANTICS |
                                     FILE_FLAG_OVERLAPPED,
                                   NULL);

  if (dir) {
    uv__free(dir);
    dir = NULL;
  }

  if (handle->dir_handle == INVALID_HANDLE_VALUE) {
    last_error = GetLastError();
    goto error;
  }

  if (CreateIoCompletionPort(handle->dir_handle,
                             handle->loop->iocp,
                             (ULONG_PTR)handle,
                             0) == NULL) {
    last_error = GetLastError();
    goto error;
  }

  if (!handle->buffer) {
    handle->buffer = (char*)uv__malloc(uv_directory_watcher_buffer_size);
  }
  if (!handle->buffer) {
    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
  }

  memset(&(handle->req.u.io.overlapped), 0,
         sizeof(handle->req.u.io.overlapped));

  if (!ReadDirectoryChangesW(handle->dir_handle,
                             handle->buffer,
                             uv_directory_watcher_buffer_size,
                             (flags & UV_FS_EVENT_RECURSIVE) ? TRUE : FALSE,
                             FILE_NOTIFY_CHANGE_FILE_NAME      |
                               FILE_NOTIFY_CHANGE_DIR_NAME     |
                               FILE_NOTIFY_CHANGE_ATTRIBUTES   |
                               FILE_NOTIFY_CHANGE_SIZE         |
                               FILE_NOTIFY_CHANGE_LAST_WRITE   |
                               FILE_NOTIFY_CHANGE_LAST_ACCESS  |
                               FILE_NOTIFY_CHANGE_CREATION     |
                               FILE_NOTIFY_CHANGE_SECURITY,
                             NULL,
                             &handle->req.u.io.overlapped,
                             NULL)) {
    last_error = GetLastError();
    goto error;
  }

  handle->req_pending = 1;
  return 0;

error:
  if (handle->path) {
    uv__free(handle->path);
    handle->path = NULL;
  }

  if (handle->filew) {
    uv__free(handle->filew);
    handle->filew = NULL;
  }

  if (handle->short_filew) {
    uv__free(handle->short_filew);
    handle->short_filew = NULL;
  }

  uv__free(pathw);

  if (handle->dir_handle != INVALID_HANDLE_VALUE) {
    CloseHandle(handle->dir_handle);
    handle->dir_handle = INVALID_HANDLE_VALUE;
  }

  if (handle->buffer) {
    uv__free(handle->buffer);
    handle->buffer = NULL;
  }

  return uv_translate_sys_error(last_error);
}
Пример #29
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;
}
Пример #30
0
BOOL
EnumAvailableApplications(INT EnumType, AVAILENUMPROC lpEnumProc)
{
    HANDLE hFind = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATAW FindFileData;
    WCHAR szPath[MAX_PATH];
    WCHAR szAppsPath[MAX_PATH];
    WCHAR szSectionLocale[MAX_PATH] = L"Section.";
    WCHAR szCabPath[MAX_PATH];
    WCHAR szLocale[4 + 1];
    APPLICATION_INFO Info;

    if (!GetCurrentDirectoryW(MAX_PATH, szPath))
    {
        return FALSE;
    }

    swprintf(szCabPath, L"%s\\rappmgr.cab", szPath);

    wcscat(szPath, L"\\rapps\\");
    wcscpy(szAppsPath, szPath);

    if (!CreateDirectory(szPath, NULL) &&
        GetLastError() != ERROR_ALREADY_EXISTS)
    {
        return FALSE;
    }

    GetLocaleInfoW(GetUserDefaultLCID(), LOCALE_ILANGUAGE, szLocale, sizeof(szLocale) / sizeof(WCHAR));
    wcscat(szSectionLocale, szLocale);

    wcscat(szPath, L"*.txt");

    hFind = FindFirstFileW(szPath, &FindFileData);
    if (hFind == INVALID_HANDLE_VALUE)
    {
        if (GetFileAttributesW(szCabPath) == INVALID_FILE_ATTRIBUTES)
            DownloadApplicationsDB(APPLICATION_DATEBASE_URL);

        ExtractFilesFromCab(szCabPath, szAppsPath);
        hFind = FindFirstFileW(szPath, &FindFileData);
        if (hFind == INVALID_HANDLE_VALUE)
            return FALSE;
    }

#define GET_STRING1(a, b)  \
    if (!ParserGetString(szSectionLocale, a, b, MAX_PATH, FindFileData.cFileName)) \
        if (!ParserGetString(L"Section", a, b, MAX_PATH, FindFileData.cFileName)) \
            continue;

#define GET_STRING2(a, b)  \
    if (!ParserGetString(szSectionLocale, a, b, MAX_PATH, FindFileData.cFileName)) \
        if (!ParserGetString(L"Section", a, b, MAX_PATH, FindFileData.cFileName)) \
            b[0] = '\0';

    do
    {
        Info.Category = ParserGetInt(szSectionLocale, L"Category", FindFileData.cFileName);
        if (Info.Category == -1)
        {
            Info.Category = ParserGetInt(L"Section", L"Category", FindFileData.cFileName);
            if (Info.Category == -1)
                continue;
        }

        if (EnumType != Info.Category && EnumType != ENUM_ALL_AVAILABLE) continue;

        GET_STRING1(L"Name", Info.szName);
        GET_STRING1(L"URLDownload", Info.szUrlDownload);

        GET_STRING2(L"RegName", Info.szRegName);
        GET_STRING2(L"Version", Info.szVersion);
        GET_STRING2(L"Licence", Info.szLicence);
        GET_STRING2(L"Description", Info.szDesc);
        GET_STRING2(L"Size", Info.szSize);
        GET_STRING2(L"URLSite", Info.szUrlSite);
        GET_STRING2(L"CDPath", Info.szCDPath);

        if (!lpEnumProc(Info)) break;
    }
    while (FindNextFileW(hFind, &FindFileData) != 0);

    FindClose(hFind);

    return TRUE;
}