2 * win32_common.c - Windows code common to applying and capturing images.
6 * Copyright (C) 2013 Eric Biggers
8 * This file is part of wimlib, a library for working with WIM files.
10 * wimlib is free software; you can redistribute it and/or modify it under the
11 * terms of the GNU General Public License as published by the Free
12 * Software Foundation; either version 3 of the License, or (at your option)
15 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 * A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with wimlib; if not, see http://www.gnu.org/licenses/.
32 #include "wimlib/win32_common.h"
34 #include "wimlib/assert.h"
35 #include "wimlib/error.h"
36 #include "wimlib/util.h"
38 #ifdef ENABLE_ERROR_MESSAGES
40 win32_error(DWORD err_code)
44 nchars = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
45 FORMAT_MESSAGE_ALLOCATE_BUFFER,
47 (wchar_t*)&buffer, 0, NULL);
49 ERROR("Error printing error message! "
50 "Computer will self-destruct in 3 seconds.");
52 ERROR("Win32 error: %ls", buffer);
56 #endif /* ENABLE_ERROR_MESSAGES */
59 win32_error_to_errno(DWORD err_code)
61 /* This mapping is that used in Cygwin.
62 * Some of these choices are arbitrary. */
64 case ERROR_ACCESS_DENIED:
66 case ERROR_ACTIVE_CONNECTIONS:
68 case ERROR_ALREADY_EXISTS:
70 case ERROR_BAD_DEVICE:
72 case ERROR_BAD_EXE_FORMAT:
74 case ERROR_BAD_NETPATH:
76 case ERROR_BAD_NET_NAME:
78 case ERROR_BAD_NET_RESP:
80 case ERROR_BAD_PATHNAME:
86 case ERROR_BAD_USERNAME:
88 case ERROR_BEGINNING_OF_MEDIA:
90 case ERROR_BROKEN_PIPE:
96 case ERROR_CALL_NOT_IMPLEMENTED:
98 case ERROR_CANNOT_MAKE:
100 case ERROR_CHILD_NOT_COMPLETE:
102 case ERROR_COMMITMENT_LIMIT:
106 case ERROR_DEVICE_DOOR_OPEN:
108 case ERROR_DEVICE_IN_USE:
110 case ERROR_DEVICE_REQUIRES_CLEANING:
112 case ERROR_DIRECTORY:
114 case ERROR_DIR_NOT_EMPTY:
116 case ERROR_DISK_CORRUPT:
118 case ERROR_DISK_FULL:
124 case ERROR_EAS_DIDNT_FIT:
127 case ERROR_EAS_NOT_SUPPORTED:
130 case ERROR_EA_LIST_INCONSISTENT:
132 case ERROR_EA_TABLE_FULL:
134 case ERROR_END_OF_MEDIA:
136 case ERROR_EOM_OVERFLOW:
138 case ERROR_EXE_MACHINE_TYPE_MISMATCH:
140 case ERROR_EXE_MARKED_INVALID:
142 case ERROR_FILEMARK_DETECTED:
144 case ERROR_FILENAME_EXCED_RANGE:
146 case ERROR_FILE_CORRUPT:
148 case ERROR_FILE_EXISTS:
150 case ERROR_FILE_INVALID:
152 case ERROR_FILE_NOT_FOUND:
154 case ERROR_HANDLE_DISK_FULL:
157 case ERROR_HANDLE_EOF:
160 case ERROR_INVALID_ADDRESS:
162 case ERROR_INVALID_AT_INTERRUPT_TIME:
164 case ERROR_INVALID_BLOCK_LENGTH:
166 case ERROR_INVALID_DATA:
168 case ERROR_INVALID_DRIVE:
170 case ERROR_INVALID_EA_NAME:
172 case ERROR_INVALID_EXE_SIGNATURE:
175 case ERROR_INVALID_FUNCTION:
178 case ERROR_INVALID_HANDLE:
180 case ERROR_INVALID_NAME:
182 case ERROR_INVALID_PARAMETER:
184 case ERROR_INVALID_SIGNAL_NUMBER:
186 case ERROR_IOPL_NOT_ENABLED:
188 case ERROR_IO_DEVICE:
190 case ERROR_IO_INCOMPLETE:
192 case ERROR_IO_PENDING:
194 case ERROR_LOCK_VIOLATION:
196 case ERROR_MAX_THRDS_REACHED:
198 case ERROR_META_EXPANSION_TOO_LONG:
200 case ERROR_MOD_NOT_FOUND:
203 case ERROR_MORE_DATA:
206 case ERROR_NEGATIVE_SEEK:
208 case ERROR_NETNAME_DELETED:
212 case ERROR_NONE_MAPPED:
214 case ERROR_NONPAGED_SYSTEM_RESOURCES:
217 case ERROR_NOT_CONNECTED:
220 case ERROR_NOT_ENOUGH_MEMORY:
222 case ERROR_NOT_OWNER:
225 case ERROR_NOT_READY:
228 case ERROR_NOT_SAME_DEVICE:
230 case ERROR_NOT_SUPPORTED:
234 case ERROR_NO_DATA_DETECTED:
237 case ERROR_NO_MEDIA_IN_DRIVE:
241 case ERROR_NO_MORE_FILES:
245 case ERROR_NO_MORE_ITEMS:
248 case ERROR_NO_MORE_SEARCH_HANDLES:
250 case ERROR_NO_PROC_SLOTS:
252 case ERROR_NO_SIGNAL_SENT:
254 case ERROR_NO_SYSTEM_RESOURCES:
258 case ERROR_OPEN_FAILED:
260 case ERROR_OPEN_FILES:
262 case ERROR_OUTOFMEMORY:
264 case ERROR_PAGED_SYSTEM_RESOURCES:
266 case ERROR_PAGEFILE_QUOTA:
268 case ERROR_PATH_NOT_FOUND:
270 case ERROR_PIPE_BUSY:
272 case ERROR_PIPE_CONNECTED:
275 case ERROR_PIPE_LISTENING:
277 case ERROR_PIPE_NOT_CONNECTED:
280 case ERROR_POSSIBLE_DEADLOCK:
282 case ERROR_PRIVILEGE_NOT_HELD:
284 case ERROR_PROCESS_ABORTED:
286 case ERROR_PROC_NOT_FOUND:
289 case ERROR_REM_NOT_LIST:
292 case ERROR_SECTOR_NOT_FOUND:
296 case ERROR_SETMARK_DETECTED:
298 case ERROR_SHARING_BUFFER_EXCEEDED:
300 case ERROR_SHARING_VIOLATION:
302 case ERROR_SIGNAL_PENDING:
304 case ERROR_SIGNAL_REFUSED:
307 case ERROR_SXS_CANT_GEN_ACTCTX:
310 case ERROR_THREAD_1_INACTIVE:
312 case ERROR_TOO_MANY_LINKS:
314 case ERROR_TOO_MANY_OPEN_FILES:
316 case ERROR_WAIT_NO_CHILDREN:
318 case ERROR_WORKING_SET_QUOTA:
320 case ERROR_WRITE_PROTECT:
328 set_errno_from_GetLastError(void)
330 errno = win32_error_to_errno(GetLastError());
333 /* Given a Windows-style path, return the number of characters of the prefix
334 * that specify the path to the root directory of a drive, or return 0 if the
335 * drive is relative (or at least on the current drive, in the case of
336 * absolute-but-not-really-absolute paths like \Windows\System32) */
338 win32_path_drive_spec_len(const wchar_t *path)
342 if (!wcsncmp(path, L"\\\\?\\", 4)) {
343 /* \\?\-prefixed path. Check for following drive letter and
345 if (path[4] != L'\0' && path[5] == L':' &&
346 is_any_path_separator(path[6]))
349 /* Not a \\?\-prefixed path. Check for an initial drive letter
350 * and path separator. */
351 if (path[0] != L'\0' && path[1] == L':' &&
352 is_any_path_separator(path[2]))
355 /* Include any additional path separators.*/
357 while (is_any_path_separator(path[n]))
363 win32_path_is_root_of_drive(const wchar_t *path)
365 size_t drive_spec_len;
366 wchar_t full_path[32768];
369 ret = GetFullPathName(path, ARRAY_LEN(full_path), full_path, NULL);
370 if (ret > 0 && ret < ARRAY_LEN(full_path))
373 /* Explicit drive letter and path separator? */
374 drive_spec_len = win32_path_drive_spec_len(path);
375 if (drive_spec_len > 0 && path[drive_spec_len] == L'\0')
378 /* All path separators? */
379 for (const wchar_t *p = path; *p != L'\0'; p++)
380 if (!is_any_path_separator(*p))
386 /* Given a path, which may not yet exist, get a set of flags that describe the
387 * features of the volume the path is on. */
389 win32_get_vol_flags(const wchar_t *path, unsigned *vol_flags_ret,
390 bool *supports_SetFileShortName_ret)
395 size_t drive_spec_len;
396 wchar_t filesystem_name[MAX_PATH + 1];
398 if (supports_SetFileShortName_ret)
399 *supports_SetFileShortName_ret = false;
401 drive_spec_len = win32_path_drive_spec_len(path);
403 if (drive_spec_len == 0)
404 if (path[0] != L'\0' && path[1] == L':') /* Drive-relative path? */
407 if (drive_spec_len == 0) {
408 /* Path does not start with a drive letter; use the volume of
409 * the current working directory. */
412 /* Path starts with a drive letter (or \\?\ followed by a drive
413 * letter); use it. */
414 volume = alloca((drive_spec_len + 2) * sizeof(wchar_t));
415 wmemcpy(volume, path, drive_spec_len);
416 /* Add trailing backslash in case this was a drive-relative
418 volume[drive_spec_len] = L'\\';
419 volume[drive_spec_len + 1] = L'\0';
421 bret = GetVolumeInformation(
422 volume, /* lpRootPathName */
423 NULL, /* lpVolumeNameBuffer */
424 0, /* nVolumeNameSize */
425 NULL, /* lpVolumeSerialNumber */
426 NULL, /* lpMaximumComponentLength */
427 &vol_flags, /* lpFileSystemFlags */
428 filesystem_name, /* lpFileSystemNameBuffer */
429 ARRAY_LEN(filesystem_name)); /* nFileSystemNameSize */
431 DWORD err = GetLastError();
432 WARNING("Failed to get volume information for path \"%ls\"", path);
434 vol_flags = 0xffffffff;
438 if (wcsstr(filesystem_name, L"NTFS")) {
439 /* FILE_SUPPORTS_HARD_LINKS is only supported on Windows 7 and later.
440 * Force it on anyway if filesystem is NTFS. */
441 vol_flags |= FILE_SUPPORTS_HARD_LINKS;
443 if (supports_SetFileShortName_ret)
444 *supports_SetFileShortName_ret = true;
448 DEBUG("using vol_flags = %x", vol_flags);
449 *vol_flags_ret = vol_flags;
454 win32_modify_privilege(const wchar_t *privilege, bool enable)
458 TOKEN_PRIVILEGES newState;
461 if (!OpenProcessToken(GetCurrentProcess(),
462 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
466 if (!LookupPrivilegeValue(NULL, privilege, &luid))
467 goto out_close_handle;
469 newState.PrivilegeCount = 1;
470 newState.Privileges[0].Luid = luid;
471 newState.Privileges[0].Attributes = (enable ? SE_PRIVILEGE_ENABLED : 0);
472 SetLastError(ERROR_SUCCESS);
473 ret = AdjustTokenPrivileges(hToken, FALSE, &newState, 0, NULL, NULL);
474 if (ret && GetLastError() == ERROR_NOT_ALL_ASSIGNED)
483 win32_modify_capture_privileges(bool enable)
485 return win32_modify_privilege(SE_BACKUP_NAME, enable)
486 && win32_modify_privilege(SE_SECURITY_NAME, enable);
490 win32_modify_apply_privileges(bool enable)
492 return win32_modify_privilege(SE_RESTORE_NAME, enable)
493 && win32_modify_privilege(SE_SECURITY_NAME, enable)
494 && win32_modify_privilege(SE_TAKE_OWNERSHIP_NAME, enable);
498 win32_release_capture_and_apply_privileges(void)
500 win32_modify_capture_privileges(false);
501 win32_modify_apply_privileges(false);
505 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
507 return CreateFileW(path,
510 NULL, /* lpSecurityAttributes */
512 FILE_FLAG_BACKUP_SEMANTICS |
513 FILE_FLAG_OPEN_REPARSE_POINT,
514 NULL /* hTemplateFile */);
518 win32_open_file_data_only(const wchar_t *path)
520 return win32_open_existing_file(path, FILE_READ_DATA);
524 /* Pointers to functions that are not available on all targetted versions of
525 * Windows (XP and later). NOTE: The WINAPI annotations seem to be important; I
526 * assume it specifies a certain calling convention. */
528 /* Vista and later */
529 HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
530 STREAM_INFO_LEVELS InfoLevel,
531 LPVOID lpFindStreamData,
532 DWORD dwFlags) = NULL;
534 /* Vista and later */
535 BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
536 LPVOID lpFindStreamData) = NULL;
537 #endif /* !WITH_NTDLL */
539 /* Vista and later */
540 BOOL (WINAPI *win32func_CreateSymbolicLinkW)(const wchar_t *lpSymlinkFileName,
541 const wchar_t *lpTargetFileName,
542 DWORD dwFlags) = NULL;
544 static OSVERSIONINFO windows_version_info = {
545 .dwOSVersionInfoSize = sizeof(OSVERSIONINFO),
548 static HMODULE hKernel32 = NULL;
550 static bool acquired_privileges = false;
553 windows_version_is_at_least(unsigned major, unsigned minor)
555 return windows_version_info.dwMajorVersion > major ||
556 (windows_version_info.dwMajorVersion == major &&
557 windows_version_info.dwMinorVersion >= minor);
560 /* One-time initialization for Windows capture/apply code. */
562 win32_global_init(int init_flags)
564 /* Try to acquire useful privileges. */
565 if (!(init_flags & WIMLIB_INIT_FLAG_DONT_ACQUIRE_PRIVILEGES)) {
566 if (!win32_modify_capture_privileges(true))
567 if (init_flags & WIMLIB_INIT_FLAG_STRICT_CAPTURE_PRIVILEGES)
568 goto insufficient_privileges;
569 if (!win32_modify_apply_privileges(true))
570 if (init_flags & WIMLIB_INIT_FLAG_STRICT_APPLY_PRIVILEGES)
571 goto insufficient_privileges;
572 acquired_privileges = true;
575 /* Get Windows version information. */
576 GetVersionEx(&windows_version_info);
578 /* Try to dynamically load some functions. */
579 if (hKernel32 == NULL)
580 hKernel32 = LoadLibrary(L"Kernel32.dll");
584 win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32,
586 if (win32func_FindFirstStreamW) {
587 win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32,
589 if (!win32func_FindNextStreamW)
590 win32func_FindFirstStreamW = NULL;
592 #endif /* !WITH_NTDLL */
593 win32func_CreateSymbolicLinkW = (void*)GetProcAddress(hKernel32,
594 "CreateSymbolicLinkW");
598 insufficient_privileges:
599 win32_release_capture_and_apply_privileges();
600 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES;
604 win32_global_cleanup(void)
606 if (acquired_privileges)
607 win32_release_capture_and_apply_privileges();
608 if (hKernel32 != NULL) {
609 FreeLibrary(hKernel32);
614 #endif /* __WIN32__ */