2 * win32_common.c - Windows code common to applying and capturing images.
6 * Copyright (C) 2013-2016 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/assert.h"
31 #include "wimlib/error.h"
32 #include "wimlib/util.h"
33 #include "wimlib/win32_vss.h"
36 win32_modify_privilege(const wchar_t *privilege, bool enable)
40 TOKEN_PRIVILEGES newState;
43 if (!OpenProcessToken(GetCurrentProcess(),
44 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
48 if (!LookupPrivilegeValue(NULL, privilege, &luid))
49 goto out_close_handle;
51 newState.PrivilegeCount = 1;
52 newState.Privileges[0].Luid = luid;
53 newState.Privileges[0].Attributes = (enable ? SE_PRIVILEGE_ENABLED : 0);
54 SetLastError(ERROR_SUCCESS);
55 ret = AdjustTokenPrivileges(hToken, FALSE, &newState, 0, NULL, NULL);
56 if (ret && GetLastError() == ERROR_NOT_ALL_ASSIGNED)
65 win32_modify_capture_privileges(bool enable)
68 ok &= win32_modify_privilege(SE_BACKUP_NAME, enable);
69 ok &= win32_modify_privilege(SE_SECURITY_NAME, enable);
74 win32_modify_apply_privileges(bool enable)
77 ok &= win32_modify_privilege(SE_RESTORE_NAME, enable);
78 ok &= win32_modify_privilege(SE_SECURITY_NAME, enable);
79 ok &= win32_modify_privilege(SE_TAKE_OWNERSHIP_NAME, enable);
80 ok &= win32_modify_privilege(SE_MANAGE_VOLUME_NAME, enable);
85 win32_release_capture_and_apply_privileges(void)
87 win32_modify_capture_privileges(false);
88 win32_modify_apply_privileges(false);
91 /* Pointers to dynamically loaded functions */
95 NTSTATUS (WINAPI *func_RtlDosPathNameToNtPathName_U_WithStatus)
97 OUT PUNICODE_STRING NtName,
99 OUT PRTL_RELATIVE_NAME_U RelativeName);
101 NTSTATUS (WINAPI *func_RtlCreateSystemVolumeInformationFolder)
102 (PCUNICODE_STRING VolumeRootPath);
104 static bool acquired_privileges = false;
112 #define DLL_SYM(name, required) { (void **)&func_##name, #name, required }
114 #define for_each_sym(sym, spec) \
115 for ((sym) = (spec)->syms; (sym)->name; (sym)++)
120 const struct dll_sym syms[];
123 struct dll_spec ntdll_spec = {
124 .name = L"ntdll.dll",
126 DLL_SYM(RtlCreateSystemVolumeInformationFolder, false),
127 DLL_SYM(RtlDosPathNameToNtPathName_U_WithStatus, false), /* Not present on XP */
133 init_dll(struct dll_spec *spec)
135 const struct dll_sym *sym;
139 spec->handle = LoadLibrary(spec->name);
141 for_each_sym(sym, spec) {
143 ERROR("%ls could not be loaded!", spec->name);
144 return WIMLIB_ERR_UNSUPPORTED;
149 for_each_sym(sym, spec) {
150 addr = (void *)GetProcAddress(spec->handle, sym->name);
152 *(sym->func_ptr) = addr;
153 } else if (sym->required) {
154 ERROR("Can't find %s in %ls", sym->name, spec->name);
155 return WIMLIB_ERR_UNSUPPORTED;
162 cleanup_dll(struct dll_spec *spec)
164 const struct dll_sym *sym;
167 FreeLibrary(spec->handle);
170 for_each_sym(sym, spec)
171 *(sym->func_ptr) = NULL;
175 /* One-time initialization for Windows capture/apply code. */
177 win32_global_init(int init_flags)
181 /* Try to acquire useful privileges. */
182 if (!(init_flags & WIMLIB_INIT_FLAG_DONT_ACQUIRE_PRIVILEGES)) {
183 ret = WIMLIB_ERR_INSUFFICIENT_PRIVILEGES;
184 if (!win32_modify_capture_privileges(true))
185 if (init_flags & WIMLIB_INIT_FLAG_STRICT_CAPTURE_PRIVILEGES)
187 if (!win32_modify_apply_privileges(true))
188 if (init_flags & WIMLIB_INIT_FLAG_STRICT_APPLY_PRIVILEGES)
190 acquired_privileges = true;
193 ret = init_dll(&ntdll_spec);
200 win32_release_capture_and_apply_privileges();
205 win32_global_cleanup(void)
207 vss_global_cleanup();
209 if (acquired_privileges)
210 win32_release_capture_and_apply_privileges();
212 cleanup_dll(&ntdll_spec);
216 * Translates a Win32-namespace path into an NT-namespace path.
218 * On success, returns 0. The NT-namespace path will be stored in the
219 * UNICODE_STRING structure pointed to by nt_path. nt_path->Buffer will be set
220 * to a new buffer that must later be freed with HeapFree(). (Really
221 * RtlHeapFree(), but HeapFree() seems to be the same thing.)
223 * On failure, returns WIMLIB_ERR_NOMEM or WIMLIB_ERR_INVALID_PARAM.
226 win32_path_to_nt_path(const wchar_t *win32_path, UNICODE_STRING *nt_path)
230 if (func_RtlDosPathNameToNtPathName_U_WithStatus) {
231 status = (*func_RtlDosPathNameToNtPathName_U_WithStatus)(win32_path,
235 if (RtlDosPathNameToNtPathName_U(win32_path, nt_path, NULL, NULL))
236 status = STATUS_SUCCESS;
238 status = STATUS_NO_MEMORY;
241 if (likely(NT_SUCCESS(status)))
244 if (status == STATUS_NO_MEMORY)
245 return WIMLIB_ERR_NOMEM;
247 winnt_error(status, L"\"%ls\": invalid path name", win32_path);
248 return WIMLIB_ERR_INVALID_PARAM;
252 win32_get_drive_path(const wchar_t *file_path, wchar_t drive_path[7])
256 file_abspath = realpath(file_path, NULL);
258 return WIMLIB_ERR_NOMEM;
260 if (file_abspath[0] == L'\0' || file_abspath[1] != L':') {
261 ERROR("\"%ls\": Path format not recognized", file_abspath);
263 return WIMLIB_ERR_UNSUPPORTED;
266 wsprintf(drive_path, L"\\\\.\\%lc:", file_abspath[0]);
271 /* Try to attach an instance of the Windows Overlay File System Filter Driver to
272 * the specified drive (such as C:) */
274 win32_try_to_attach_wof(const wchar_t *drive)
279 /* Use FilterAttach() from Fltlib.dll. */
281 fltlib = LoadLibrary(L"Fltlib.dll");
284 WARNING("Failed to load Fltlib.dll");
288 HRESULT (WINAPI *func_FilterAttach)(LPCWSTR lpFilterName,
289 LPCWSTR lpVolumeName,
290 LPCWSTR lpInstanceName,
291 DWORD dwCreatedInstanceNameLength,
292 LPWSTR lpCreatedInstanceName);
294 func_FilterAttach = (void *)GetProcAddress(fltlib, "FilterAttach");
296 if (func_FilterAttach) {
299 res = (*func_FilterAttach)(L"wof", drive, NULL, 0, NULL);
302 res = (*func_FilterAttach)(L"wofadk", drive, NULL, 0, NULL);
307 WARNING("FilterAttach() does not exist in Fltlib.dll");
317 windows_msg(u32 code, const wchar_t *format, va_list va,
318 bool is_ntstatus, bool is_error)
320 wchar_t _buf[STACK_MAX / 8];
322 size_t buflen = ARRAY_LEN(_buf);
327 n = vsnwprintf(buf, buflen, format, va);
332 n += snwprintf(&buf[n], buflen - n,
334 L" (status=%08"PRIx32"): " :
335 L" (err=%"PRIu32"): "),
341 ret = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
342 FORMAT_MESSAGE_IGNORE_INSERTS |
343 (is_ntstatus ? FORMAT_MESSAGE_FROM_HMODULE : 0),
344 (is_ntstatus ? ntdll_spec.handle : NULL),
346 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
352 if (n >= buflen || (ret == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER))
355 if (buf[n - 1] == L'\n')
357 if (buf[n - 1] == L'\r')
359 if (buf[n - 1] == L'.')
374 buf = MALLOC(buflen * sizeof(buf[0]));
377 ERROR("Ran out of memory while building error message!!!");
381 win32_warning(DWORD err, const wchar_t *format, ...)
385 va_start(va, format);
386 windows_msg(err, format, va, false, false);
391 win32_error(DWORD err, const wchar_t *format, ...)
395 va_start(va, format);
396 windows_msg(err, format, va, false, true);
401 winnt_warning(NTSTATUS status, const wchar_t *format, ...)
405 va_start(va, format);
406 windows_msg(status, format, va, true, false);
411 winnt_error(NTSTATUS status, const wchar_t *format, ...)
415 va_start(va, format);
416 windows_msg(status, format, va, true, true);
421 * Synchronously execute a filesystem control method. This is a wrapper around
422 * NtFsControlFile() that handles STATUS_PENDING. Note that SYNCHRONIZE
423 * permission is, in general, required on the handle.
426 winnt_fsctl(HANDLE h, u32 code, const void *in, u32 in_size,
427 void *out, u32 out_size_avail, u32 *actual_out_size_ret)
429 IO_STATUS_BLOCK iosb;
432 status = NtFsControlFile(h, NULL, NULL, NULL, &iosb, code,
433 (void *)in, in_size, out, out_size_avail);
434 if (status == STATUS_PENDING) {
435 /* Beware: this case is often encountered with remote
436 * filesystems, but rarely with local filesystems. */
438 status = NtWaitForSingleObject(h, FALSE, NULL);
439 if (NT_SUCCESS(status)) {
440 status = iosb.Status;
442 /* We shouldn't be issuing ioctls on a handle to which
443 * we don't have SYNCHRONIZE access. Otherwise we have
444 * no way to wait for them to complete. */
445 wimlib_assert(status != STATUS_ACCESS_DENIED);
449 if (NT_SUCCESS(status) && actual_out_size_ret != NULL)
450 *actual_out_size_ret = (u32)iosb.Information;
455 #endif /* __WIN32__ */