2 * win32_common.c - Windows code common to applying and capturing images.
6 * Copyright (C) 2013, 2014, 2015 Eric Biggers
8 * This file is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU Lesser General Public License as published by the Free
10 * Software Foundation; either version 3 of the License, or (at your option) any
13 * This file is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this file; if not, see http://www.gnu.org/licenses/.
28 #include "wimlib/win32_common.h"
30 #include "wimlib/error.h"
31 #include "wimlib/util.h"
32 #include "wimlib/win32_vss.h"
35 win32_modify_privilege(const wchar_t *privilege, bool enable)
39 TOKEN_PRIVILEGES newState;
42 if (!OpenProcessToken(GetCurrentProcess(),
43 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
47 if (!LookupPrivilegeValue(NULL, privilege, &luid))
48 goto out_close_handle;
50 newState.PrivilegeCount = 1;
51 newState.Privileges[0].Luid = luid;
52 newState.Privileges[0].Attributes = (enable ? SE_PRIVILEGE_ENABLED : 0);
53 SetLastError(ERROR_SUCCESS);
54 ret = AdjustTokenPrivileges(hToken, FALSE, &newState, 0, NULL, NULL);
55 if (ret && GetLastError() == ERROR_NOT_ALL_ASSIGNED)
64 win32_modify_capture_privileges(bool enable)
67 ok &= win32_modify_privilege(SE_BACKUP_NAME, enable);
68 ok &= win32_modify_privilege(SE_SECURITY_NAME, enable);
73 win32_modify_apply_privileges(bool enable)
76 ok &= win32_modify_privilege(SE_RESTORE_NAME, enable);
77 ok &= win32_modify_privilege(SE_SECURITY_NAME, enable);
78 ok &= win32_modify_privilege(SE_TAKE_OWNERSHIP_NAME, enable);
79 ok &= win32_modify_privilege(SE_MANAGE_VOLUME_NAME, enable);
84 win32_release_capture_and_apply_privileges(void)
86 win32_modify_capture_privileges(false);
87 win32_modify_apply_privileges(false);
90 /* Pointers to dynamically loaded functions */
94 NTSTATUS (WINAPI *func_NtCreateFile)(PHANDLE FileHandle,
95 ACCESS_MASK DesiredAccess,
96 POBJECT_ATTRIBUTES ObjectAttributes,
97 PIO_STATUS_BLOCK IoStatusBlock,
98 PLARGE_INTEGER AllocationSize,
101 ULONG CreateDisposition,
106 NTSTATUS (WINAPI *func_NtOpenFile) (PHANDLE FileHandle,
107 ACCESS_MASK DesiredAccess,
108 POBJECT_ATTRIBUTES ObjectAttributes,
109 PIO_STATUS_BLOCK IoStatusBlock,
113 NTSTATUS (WINAPI *func_NtReadFile) (HANDLE FileHandle,
115 PIO_APC_ROUTINE ApcRoutine,
117 PIO_STATUS_BLOCK IoStatusBlock,
120 PLARGE_INTEGER ByteOffset,
123 NTSTATUS (WINAPI *func_NtWriteFile) (HANDLE FileHandle,
125 PIO_APC_ROUTINE ApcRoutine,
127 PIO_STATUS_BLOCK IoStatusBlock,
130 PLARGE_INTEGER ByteOffset,
133 NTSTATUS (WINAPI *func_NtQueryInformationFile)(HANDLE FileHandle,
134 PIO_STATUS_BLOCK IoStatusBlock,
135 PVOID FileInformation,
137 FILE_INFORMATION_CLASS FileInformationClass);
139 NTSTATUS (WINAPI *func_NtQuerySecurityObject)(HANDLE handle,
140 SECURITY_INFORMATION SecurityInformation,
141 PSECURITY_DESCRIPTOR SecurityDescriptor,
143 PULONG LengthNeeded);
145 NTSTATUS (WINAPI *func_NtQueryDirectoryFile) (HANDLE FileHandle,
147 PIO_APC_ROUTINE ApcRoutine,
149 PIO_STATUS_BLOCK IoStatusBlock,
150 PVOID FileInformation,
152 FILE_INFORMATION_CLASS FileInformationClass,
153 BOOLEAN ReturnSingleEntry,
154 PUNICODE_STRING FileName,
155 BOOLEAN RestartScan);
157 NTSTATUS (WINAPI *func_NtQueryVolumeInformationFile) (HANDLE FileHandle,
158 PIO_STATUS_BLOCK IoStatusBlock,
161 FS_INFORMATION_CLASS FsInformationClass);
163 NTSTATUS (WINAPI *func_NtSetInformationFile)(HANDLE FileHandle,
164 PIO_STATUS_BLOCK IoStatusBlock,
165 PVOID FileInformation,
167 FILE_INFORMATION_CLASS FileInformationClass);
169 NTSTATUS (WINAPI *func_NtSetSecurityObject)(HANDLE Handle,
170 SECURITY_INFORMATION SecurityInformation,
171 PSECURITY_DESCRIPTOR SecurityDescriptor);
173 NTSTATUS (WINAPI *func_NtFsControlFile) (HANDLE FileHandle,
175 PIO_APC_ROUTINE ApcRoutine,
177 PIO_STATUS_BLOCK IoStatusBlock,
180 ULONG InputBufferLength,
182 ULONG OutputBufferLength);
184 NTSTATUS (WINAPI *func_NtClose) (HANDLE Handle);
186 DWORD (WINAPI *func_RtlNtStatusToDosError)(NTSTATUS status);
188 BOOLEAN (WINAPI *func_RtlDosPathNameToNtPathName_U)
190 OUT PUNICODE_STRING NtName,
191 OUT PCWSTR *PartName,
192 OUT PRTL_RELATIVE_NAME_U RelativeName);
194 NTSTATUS (WINAPI *func_RtlDosPathNameToNtPathName_U_WithStatus)
196 OUT PUNICODE_STRING NtName,
197 OUT PCWSTR *PartName,
198 OUT PRTL_RELATIVE_NAME_U RelativeName);
200 NTSTATUS (WINAPI *func_RtlCreateSystemVolumeInformationFolder)
201 (PCUNICODE_STRING VolumeRootPath);
203 static bool acquired_privileges = false;
211 #define DLL_SYM(name, required) { (void **)&func_##name, #name, required }
213 #define for_each_sym(sym, spec) \
214 for ((sym) = (spec)->syms; (sym)->name; (sym)++)
219 const struct dll_sym syms[];
222 struct dll_spec ntdll_spec = {
223 .name = L"ntdll.dll",
225 DLL_SYM(NtCreateFile, true),
226 DLL_SYM(NtOpenFile, true),
227 DLL_SYM(NtReadFile, true),
228 DLL_SYM(NtWriteFile, true),
229 DLL_SYM(NtQueryInformationFile, true),
230 DLL_SYM(NtQuerySecurityObject, true),
231 DLL_SYM(NtQueryDirectoryFile, true),
232 DLL_SYM(NtQueryVolumeInformationFile, true),
233 DLL_SYM(NtSetInformationFile, true),
234 DLL_SYM(NtSetSecurityObject, true),
235 DLL_SYM(NtFsControlFile, true),
236 DLL_SYM(NtClose, true),
237 DLL_SYM(RtlNtStatusToDosError, true),
238 DLL_SYM(RtlCreateSystemVolumeInformationFolder, false),
239 DLL_SYM(RtlDosPathNameToNtPathName_U, true),
240 DLL_SYM(RtlDosPathNameToNtPathName_U_WithStatus, false), /* Not present on XP */
246 init_dll(struct dll_spec *spec)
248 const struct dll_sym *sym;
252 spec->handle = LoadLibrary(spec->name);
254 for_each_sym(sym, spec) {
256 ERROR("%ls could not be loaded!", spec->name);
257 return WIMLIB_ERR_UNSUPPORTED;
262 for_each_sym(sym, spec) {
263 addr = (void *)GetProcAddress(spec->handle, sym->name);
265 *(sym->func_ptr) = addr;
266 } else if (sym->required) {
267 ERROR("Can't find %s in %ls", sym->name, spec->name);
268 return WIMLIB_ERR_UNSUPPORTED;
275 cleanup_dll(struct dll_spec *spec)
277 const struct dll_sym *sym;
280 FreeLibrary(spec->handle);
283 for_each_sym(sym, spec)
284 *(sym->func_ptr) = NULL;
288 /* One-time initialization for Windows capture/apply code. */
290 win32_global_init(int init_flags)
294 /* Try to acquire useful privileges. */
295 if (!(init_flags & WIMLIB_INIT_FLAG_DONT_ACQUIRE_PRIVILEGES)) {
296 ret = WIMLIB_ERR_INSUFFICIENT_PRIVILEGES;
297 if (!win32_modify_capture_privileges(true))
298 if (init_flags & WIMLIB_INIT_FLAG_STRICT_CAPTURE_PRIVILEGES)
300 if (!win32_modify_apply_privileges(true))
301 if (init_flags & WIMLIB_INIT_FLAG_STRICT_APPLY_PRIVILEGES)
303 acquired_privileges = true;
306 ret = init_dll(&ntdll_spec);
313 win32_release_capture_and_apply_privileges();
318 win32_global_cleanup(void)
320 vss_global_cleanup();
322 if (acquired_privileges)
323 win32_release_capture_and_apply_privileges();
325 cleanup_dll(&ntdll_spec);
329 * Translates a Win32-namespace path into an NT-namespace path.
331 * On success, returns 0. The NT-namespace path will be stored in the
332 * UNICODE_STRING structure pointed to by nt_path. nt_path->Buffer will be set
333 * to a new buffer that must later be freed with HeapFree(). (Really
334 * RtlHeapFree(), but HeapFree() seems to be the same thing.)
336 * On failure, returns WIMLIB_ERR_NOMEM or WIMLIB_ERR_INVALID_PARAM.
339 win32_path_to_nt_path(const wchar_t *win32_path, UNICODE_STRING *nt_path)
343 if (func_RtlDosPathNameToNtPathName_U_WithStatus) {
344 status = (*func_RtlDosPathNameToNtPathName_U_WithStatus)(win32_path,
348 if ((*func_RtlDosPathNameToNtPathName_U)(win32_path, nt_path,
350 status = STATUS_SUCCESS;
352 status = STATUS_NO_MEMORY;
355 if (likely(NT_SUCCESS(status)))
358 if (status == STATUS_NO_MEMORY)
359 return WIMLIB_ERR_NOMEM;
361 winnt_error(status, L"\"%ls\": invalid path name", win32_path);
362 return WIMLIB_ERR_INVALID_PARAM;
366 win32_get_drive_path(const wchar_t *file_path, wchar_t drive_path[7])
370 file_abspath = realpath(file_path, NULL);
372 return WIMLIB_ERR_NOMEM;
374 if (file_abspath[0] == L'\0' || file_abspath[1] != L':') {
375 ERROR("\"%ls\": Path format not recognized", file_abspath);
377 return WIMLIB_ERR_UNSUPPORTED;
380 wsprintf(drive_path, L"\\\\.\\%lc:", file_abspath[0]);
385 /* Try to attach an instance of the Windows Overlay File System Filter Driver to
386 * the specified drive (such as C:) */
388 win32_try_to_attach_wof(const wchar_t *drive)
393 /* Use FilterAttach() from Fltlib.dll. */
395 fltlib = LoadLibrary(L"Fltlib.dll");
398 WARNING("Failed to load Fltlib.dll");
402 HRESULT (WINAPI *func_FilterAttach)(LPCWSTR lpFilterName,
403 LPCWSTR lpVolumeName,
404 LPCWSTR lpInstanceName,
405 DWORD dwCreatedInstanceNameLength,
406 LPWSTR lpCreatedInstanceName);
408 func_FilterAttach = (void *)GetProcAddress(fltlib, "FilterAttach");
410 if (func_FilterAttach) {
413 res = (*func_FilterAttach)(L"wof", drive, NULL, 0, NULL);
416 res = (*func_FilterAttach)(L"wofadk", drive, NULL, 0, NULL);
421 WARNING("FilterAttach() does not exist in Fltlib.dll");
431 windows_msg(u32 code, const wchar_t *format, va_list va,
432 bool is_ntstatus, bool is_error)
434 wchar_t _buf[STACK_MAX / 8];
436 size_t buflen = ARRAY_LEN(_buf);
441 n = vsnwprintf(buf, buflen, format, va);
446 n += snwprintf(&buf[n], buflen - n,
448 L" (status=%08"PRIx32"): " :
449 L" (err=%"PRIu32"): "),
455 ret = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
456 FORMAT_MESSAGE_IGNORE_INSERTS |
457 (is_ntstatus ? FORMAT_MESSAGE_FROM_HMODULE : 0),
458 (is_ntstatus ? ntdll_spec.handle : NULL),
460 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
466 if (n >= buflen || (ret == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER))
469 if (buf[n - 1] == L'\n')
471 if (buf[n - 1] == L'\r')
473 if (buf[n - 1] == L'.')
488 buf = MALLOC(buflen * sizeof(buf[0]));
491 ERROR("Ran out of memory while building error message!!!");
495 win32_warning(DWORD err, const wchar_t *format, ...)
499 va_start(va, format);
500 windows_msg(err, format, va, false, false);
505 win32_error(DWORD err, const wchar_t *format, ...)
509 va_start(va, format);
510 windows_msg(err, format, va, false, true);
515 winnt_warning(NTSTATUS status, const wchar_t *format, ...)
519 va_start(va, format);
520 windows_msg(status, format, va, true, false);
525 winnt_error(NTSTATUS status, const wchar_t *format, ...)
529 va_start(va, format);
530 windows_msg(status, format, va, true, true);
534 #endif /* __WIN32__ */