2 * win32_common.c - Windows code common to applying and capturing images.
6 * Copyright (C) 2013, 2014 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"
33 #include "wimlib/error.h"
34 #include "wimlib/util.h"
37 win32_error_to_errno(DWORD err_code)
39 /* This mapping is that used in Cygwin.
40 * Some of these choices are arbitrary. */
42 case ERROR_ACCESS_DENIED:
44 case ERROR_ACTIVE_CONNECTIONS:
46 case ERROR_ALREADY_EXISTS:
48 case ERROR_BAD_DEVICE:
50 case ERROR_BAD_EXE_FORMAT:
52 case ERROR_BAD_NETPATH:
54 case ERROR_BAD_NET_NAME:
56 case ERROR_BAD_NET_RESP:
58 case ERROR_BAD_PATHNAME:
64 case ERROR_BAD_USERNAME:
66 case ERROR_BEGINNING_OF_MEDIA:
68 case ERROR_BROKEN_PIPE:
74 case ERROR_CALL_NOT_IMPLEMENTED:
76 case ERROR_CANNOT_MAKE:
78 case ERROR_CHILD_NOT_COMPLETE:
80 case ERROR_COMMITMENT_LIMIT:
84 case ERROR_DEVICE_DOOR_OPEN:
86 case ERROR_DEVICE_IN_USE:
88 case ERROR_DEVICE_REQUIRES_CLEANING:
92 case ERROR_DIR_NOT_EMPTY:
94 case ERROR_DISK_CORRUPT:
102 case ERROR_EAS_DIDNT_FIT:
105 case ERROR_EAS_NOT_SUPPORTED:
108 case ERROR_EA_LIST_INCONSISTENT:
110 case ERROR_EA_TABLE_FULL:
112 case ERROR_END_OF_MEDIA:
114 case ERROR_EOM_OVERFLOW:
116 case ERROR_EXE_MACHINE_TYPE_MISMATCH:
118 case ERROR_EXE_MARKED_INVALID:
120 case ERROR_FILEMARK_DETECTED:
122 case ERROR_FILENAME_EXCED_RANGE:
124 case ERROR_FILE_CORRUPT:
126 case ERROR_FILE_EXISTS:
128 case ERROR_FILE_INVALID:
130 case ERROR_FILE_NOT_FOUND:
132 case ERROR_HANDLE_DISK_FULL:
135 case ERROR_HANDLE_EOF:
138 case ERROR_INVALID_ADDRESS:
140 case ERROR_INVALID_AT_INTERRUPT_TIME:
142 case ERROR_INVALID_BLOCK_LENGTH:
144 case ERROR_INVALID_DATA:
146 case ERROR_INVALID_DRIVE:
148 case ERROR_INVALID_EA_NAME:
150 case ERROR_INVALID_EXE_SIGNATURE:
153 case ERROR_INVALID_FUNCTION:
156 case ERROR_INVALID_HANDLE:
158 case ERROR_INVALID_NAME:
160 case ERROR_INVALID_PARAMETER:
162 case ERROR_INVALID_SIGNAL_NUMBER:
164 case ERROR_IOPL_NOT_ENABLED:
166 case ERROR_IO_DEVICE:
168 case ERROR_IO_INCOMPLETE:
170 case ERROR_IO_PENDING:
172 case ERROR_LOCK_VIOLATION:
174 case ERROR_MAX_THRDS_REACHED:
176 case ERROR_META_EXPANSION_TOO_LONG:
178 case ERROR_MOD_NOT_FOUND:
181 case ERROR_MORE_DATA:
184 case ERROR_NEGATIVE_SEEK:
186 case ERROR_NETNAME_DELETED:
190 case ERROR_NONE_MAPPED:
192 case ERROR_NONPAGED_SYSTEM_RESOURCES:
195 case ERROR_NOT_CONNECTED:
198 case ERROR_NOT_ENOUGH_MEMORY:
200 case ERROR_NOT_OWNER:
203 case ERROR_NOT_READY:
206 case ERROR_NOT_SAME_DEVICE:
208 case ERROR_NOT_SUPPORTED:
212 case ERROR_NO_DATA_DETECTED:
215 case ERROR_NO_MEDIA_IN_DRIVE:
219 case ERROR_NO_MORE_FILES:
223 case ERROR_NO_MORE_ITEMS:
226 case ERROR_NO_MORE_SEARCH_HANDLES:
228 case ERROR_NO_PROC_SLOTS:
230 case ERROR_NO_SIGNAL_SENT:
232 case ERROR_NO_SYSTEM_RESOURCES:
236 case ERROR_OPEN_FAILED:
238 case ERROR_OPEN_FILES:
240 case ERROR_OUTOFMEMORY:
242 case ERROR_PAGED_SYSTEM_RESOURCES:
244 case ERROR_PAGEFILE_QUOTA:
246 case ERROR_PATH_NOT_FOUND:
248 case ERROR_PIPE_BUSY:
250 case ERROR_PIPE_CONNECTED:
253 case ERROR_PIPE_LISTENING:
255 case ERROR_PIPE_NOT_CONNECTED:
258 case ERROR_POSSIBLE_DEADLOCK:
260 case ERROR_PRIVILEGE_NOT_HELD:
262 case ERROR_PROCESS_ABORTED:
264 case ERROR_PROC_NOT_FOUND:
267 case ERROR_REM_NOT_LIST:
270 case ERROR_SECTOR_NOT_FOUND:
274 case ERROR_SETMARK_DETECTED:
276 case ERROR_SHARING_BUFFER_EXCEEDED:
278 case ERROR_SHARING_VIOLATION:
280 case ERROR_SIGNAL_PENDING:
282 case ERROR_SIGNAL_REFUSED:
285 case ERROR_SXS_CANT_GEN_ACTCTX:
288 case ERROR_THREAD_1_INACTIVE:
290 case ERROR_TOO_MANY_LINKS:
292 case ERROR_TOO_MANY_OPEN_FILES:
294 case ERROR_WAIT_NO_CHILDREN:
296 case ERROR_WORKING_SET_QUOTA:
298 case ERROR_WRITE_PROTECT:
307 set_errno_from_win32_error(DWORD err)
309 errno = win32_error_to_errno(err);
313 set_errno_from_GetLastError(void)
315 set_errno_from_win32_error(GetLastError());
319 set_errno_from_nt_status(NTSTATUS status)
321 set_errno_from_win32_error((*func_RtlNtStatusToDosError)(status));
324 /* Given a Windows-style path, return the number of characters of the prefix
325 * that specify the path to the root directory of a drive, or return 0 if the
326 * drive is relative (or at least on the current drive, in the case of
327 * absolute-but-not-really-absolute paths like \Windows\System32) */
329 win32_path_drive_spec_len(const wchar_t *path)
333 if (!wcsncmp(path, L"\\\\?\\", 4)) {
334 /* \\?\-prefixed path. Check for following drive letter and
336 if (path[4] != L'\0' && path[5] == L':' &&
337 is_any_path_separator(path[6]))
340 /* Not a \\?\-prefixed path. Check for an initial drive letter
341 * and path separator. */
342 if (path[0] != L'\0' && path[1] == L':' &&
343 is_any_path_separator(path[2]))
346 /* Include any additional path separators.*/
348 while (is_any_path_separator(path[n]))
354 win32_path_is_root_of_drive(const wchar_t *path)
356 size_t drive_spec_len;
357 wchar_t full_path[32768];
360 ret = GetFullPathName(path, ARRAY_LEN(full_path), full_path, NULL);
361 if (ret > 0 && ret < ARRAY_LEN(full_path))
364 /* Explicit drive letter and path separator? */
365 drive_spec_len = win32_path_drive_spec_len(path);
366 if (drive_spec_len > 0 && path[drive_spec_len] == L'\0')
369 /* All path separators? */
370 for (const wchar_t *p = path; *p != L'\0'; p++)
371 if (!is_any_path_separator(*p))
377 /* Given a path, which may not yet exist, get a set of flags that describe the
378 * features of the volume the path is on. */
380 win32_get_vol_flags(const wchar_t *path, unsigned *vol_flags_ret,
381 bool *supports_SetFileShortName_ret)
386 size_t drive_spec_len;
387 wchar_t filesystem_name[MAX_PATH + 1];
389 if (supports_SetFileShortName_ret)
390 *supports_SetFileShortName_ret = false;
392 drive_spec_len = win32_path_drive_spec_len(path);
394 if (drive_spec_len == 0)
395 if (path[0] != L'\0' && path[1] == L':') /* Drive-relative path? */
398 if (drive_spec_len == 0) {
399 /* Path does not start with a drive letter; use the volume of
400 * the current working directory. */
403 /* Path starts with a drive letter (or \\?\ followed by a drive
404 * letter); use it. */
405 volume = alloca((drive_spec_len + 2) * sizeof(wchar_t));
406 wmemcpy(volume, path, drive_spec_len);
407 /* Add trailing backslash in case this was a drive-relative
409 volume[drive_spec_len] = L'\\';
410 volume[drive_spec_len + 1] = L'\0';
412 bret = GetVolumeInformation(
413 volume, /* lpRootPathName */
414 NULL, /* lpVolumeNameBuffer */
415 0, /* nVolumeNameSize */
416 NULL, /* lpVolumeSerialNumber */
417 NULL, /* lpMaximumComponentLength */
418 &vol_flags, /* lpFileSystemFlags */
419 filesystem_name, /* lpFileSystemNameBuffer */
420 ARRAY_LEN(filesystem_name)); /* nFileSystemNameSize */
422 set_errno_from_GetLastError();
423 WARNING_WITH_ERRNO("Failed to get volume information for "
424 "path \"%ls\"", path);
425 vol_flags = 0xffffffff;
429 if (wcsstr(filesystem_name, L"NTFS")) {
430 /* FILE_SUPPORTS_HARD_LINKS is only supported on Windows 7 and later.
431 * Force it on anyway if filesystem is NTFS. */
432 vol_flags |= FILE_SUPPORTS_HARD_LINKS;
434 if (supports_SetFileShortName_ret)
435 *supports_SetFileShortName_ret = true;
439 DEBUG("using vol_flags = %x", vol_flags);
440 *vol_flags_ret = vol_flags;
445 win32_modify_privilege(const wchar_t *privilege, bool enable)
449 TOKEN_PRIVILEGES newState;
452 if (!OpenProcessToken(GetCurrentProcess(),
453 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
457 if (!LookupPrivilegeValue(NULL, privilege, &luid))
458 goto out_close_handle;
460 newState.PrivilegeCount = 1;
461 newState.Privileges[0].Luid = luid;
462 newState.Privileges[0].Attributes = (enable ? SE_PRIVILEGE_ENABLED : 0);
463 SetLastError(ERROR_SUCCESS);
464 ret = AdjustTokenPrivileges(hToken, FALSE, &newState, 0, NULL, NULL);
465 if (ret && GetLastError() == ERROR_NOT_ALL_ASSIGNED)
474 win32_modify_capture_privileges(bool enable)
476 return win32_modify_privilege(SE_BACKUP_NAME, enable)
477 && win32_modify_privilege(SE_SECURITY_NAME, enable);
481 win32_modify_apply_privileges(bool enable)
483 return win32_modify_privilege(SE_RESTORE_NAME, enable)
484 && win32_modify_privilege(SE_SECURITY_NAME, enable)
485 && win32_modify_privilege(SE_TAKE_OWNERSHIP_NAME, enable);
489 win32_release_capture_and_apply_privileges(void)
491 win32_modify_capture_privileges(false);
492 win32_modify_apply_privileges(false);
496 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
498 return CreateFile(path,
501 NULL, /* lpSecurityAttributes */
503 FILE_FLAG_BACKUP_SEMANTICS |
504 FILE_FLAG_OPEN_REPARSE_POINT,
505 NULL /* hTemplateFile */);
508 /* Pointers to dynamically loaded functions */
510 /* kernel32.dll: Vista and later */
511 BOOL (WINAPI *func_CreateSymbolicLinkW)(const wchar_t *lpSymlinkFileName,
512 const wchar_t *lpTargetFileName,
517 NTSTATUS (WINAPI *func_NtOpenFile) (PHANDLE FileHandle,
518 ACCESS_MASK DesiredAccess,
519 POBJECT_ATTRIBUTES ObjectAttributes,
520 PIO_STATUS_BLOCK IoStatusBlock,
524 NTSTATUS (WINAPI *func_NtReadFile) (HANDLE FileHandle,
526 PIO_APC_ROUTINE ApcRoutine,
528 PIO_STATUS_BLOCK IoStatusBlock,
531 PLARGE_INTEGER ByteOffset,
534 NTSTATUS (WINAPI *func_NtOpenFile) (PHANDLE FileHandle,
535 ACCESS_MASK DesiredAccess,
536 POBJECT_ATTRIBUTES ObjectAttributes,
537 PIO_STATUS_BLOCK IoStatusBlock,
541 NTSTATUS (WINAPI *func_NtQueryInformationFile)(HANDLE FileHandle,
542 PIO_STATUS_BLOCK IoStatusBlock,
543 PVOID FileInformation,
545 FILE_INFORMATION_CLASS FileInformationClass);
547 NTSTATUS (WINAPI *func_NtQuerySecurityObject)(HANDLE handle,
548 SECURITY_INFORMATION SecurityInformation,
549 PSECURITY_DESCRIPTOR SecurityDescriptor,
551 PULONG LengthNeeded);
553 NTSTATUS (WINAPI *func_NtQueryDirectoryFile) (HANDLE FileHandle,
555 PIO_APC_ROUTINE ApcRoutine,
557 PIO_STATUS_BLOCK IoStatusBlock,
558 PVOID FileInformation,
560 FILE_INFORMATION_CLASS FileInformationClass,
561 BOOLEAN ReturnSingleEntry,
562 PUNICODE_STRING FileName,
563 BOOLEAN RestartScan);
565 NTSTATUS (WINAPI *func_NtQueryVolumeInformationFile) (HANDLE FileHandle,
566 PIO_STATUS_BLOCK IoStatusBlock,
569 FS_INFORMATION_CLASS FsInformationClass);
571 NTSTATUS (WINAPI *func_NtSetSecurityObject)(HANDLE Handle,
572 SECURITY_INFORMATION SecurityInformation,
573 PSECURITY_DESCRIPTOR SecurityDescriptor);
575 NTSTATUS (WINAPI *func_NtClose) (HANDLE Handle);
577 DWORD (WINAPI *func_RtlNtStatusToDosError)(NTSTATUS status);
579 NTSTATUS (WINAPI *func_RtlCreateSystemVolumeInformationFolder)
580 (PCUNICODE_STRING VolumeRootPath);
582 static OSVERSIONINFO windows_version_info = {
583 .dwOSVersionInfoSize = sizeof(OSVERSIONINFO),
586 static bool acquired_privileges = false;
589 windows_version_is_at_least(unsigned major, unsigned minor)
591 return windows_version_info.dwMajorVersion > major ||
592 (windows_version_info.dwMajorVersion == major &&
593 windows_version_info.dwMinorVersion >= minor);
602 #define DLL_SYM(name, required) { (void **)&func_##name, #name, required }
604 #define for_each_sym(sym, spec) \
605 for ((sym) = (spec)->syms; (sym)->name; (sym)++)
610 const struct dll_sym syms[];
613 struct dll_spec ntdll_spec = {
614 .name = L"ntdll.dll",
616 DLL_SYM(NtOpenFile, true),
617 DLL_SYM(NtReadFile, true),
618 DLL_SYM(NtQueryInformationFile, true),
619 DLL_SYM(NtQuerySecurityObject, true),
620 DLL_SYM(NtQueryDirectoryFile, true),
621 DLL_SYM(NtQueryVolumeInformationFile, true),
622 DLL_SYM(NtSetSecurityObject, true),
623 DLL_SYM(NtClose, true),
624 DLL_SYM(RtlNtStatusToDosError, true),
625 DLL_SYM(RtlCreateSystemVolumeInformationFolder, false),
630 struct dll_spec kernel32_spec = {
631 .name = L"kernel32.dll",
633 DLL_SYM(CreateSymbolicLinkW, false),
639 init_dll(struct dll_spec *spec)
641 const struct dll_sym *sym;
645 spec->handle = LoadLibrary(spec->name);
647 for_each_sym(sym, spec) {
649 ERROR("%ls could not be loaded!", spec->name);
650 return WIMLIB_ERR_UNSUPPORTED;
655 for_each_sym(sym, spec) {
656 addr = (void *)GetProcAddress(spec->handle, sym->name);
658 *(sym->func_ptr) = addr;
659 } else if (sym->required) {
660 ERROR("Can't find %s in %ls", sym->name, spec->name);
661 return WIMLIB_ERR_UNSUPPORTED;
668 cleanup_dll(struct dll_spec *spec)
670 const struct dll_sym *sym;
673 FreeLibrary(spec->handle);
676 for_each_sym(sym, spec)
677 *(sym->func_ptr) = NULL;
681 /* One-time initialization for Windows capture/apply code. */
683 win32_global_init(int init_flags)
687 /* Try to acquire useful privileges. */
688 if (!(init_flags & WIMLIB_INIT_FLAG_DONT_ACQUIRE_PRIVILEGES)) {
689 ret = WIMLIB_ERR_INSUFFICIENT_PRIVILEGES;
690 if (!win32_modify_capture_privileges(true))
691 if (init_flags & WIMLIB_INIT_FLAG_STRICT_CAPTURE_PRIVILEGES)
693 if (!win32_modify_apply_privileges(true))
694 if (init_flags & WIMLIB_INIT_FLAG_STRICT_APPLY_PRIVILEGES)
696 acquired_privileges = true;
699 /* Get Windows version information. */
700 GetVersionEx(&windows_version_info);
702 /* Try to dynamically load some functions. */
703 ret = init_dll(&kernel32_spec);
707 ret = init_dll(&ntdll_spec);
709 goto out_cleanup_kernel32;
713 out_cleanup_kernel32:
714 cleanup_dll(&kernel32_spec);
716 win32_release_capture_and_apply_privileges();
721 win32_global_cleanup(void)
723 if (acquired_privileges)
724 win32_release_capture_and_apply_privileges();
726 cleanup_dll(&kernel32_spec);
727 cleanup_dll(&ntdll_spec);
730 #endif /* __WIN32__ */