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"
34 win32_modify_privilege(const wchar_t *privilege, bool enable)
38 TOKEN_PRIVILEGES newState;
41 if (!OpenProcessToken(GetCurrentProcess(),
42 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
46 if (!LookupPrivilegeValue(NULL, privilege, &luid))
47 goto out_close_handle;
49 newState.PrivilegeCount = 1;
50 newState.Privileges[0].Luid = luid;
51 newState.Privileges[0].Attributes = (enable ? SE_PRIVILEGE_ENABLED : 0);
52 SetLastError(ERROR_SUCCESS);
53 ret = AdjustTokenPrivileges(hToken, FALSE, &newState, 0, NULL, NULL);
54 if (ret && GetLastError() == ERROR_NOT_ALL_ASSIGNED)
63 win32_modify_capture_privileges(bool enable)
65 return win32_modify_privilege(SE_BACKUP_NAME, enable)
66 && win32_modify_privilege(SE_SECURITY_NAME, enable);
70 win32_modify_apply_privileges(bool enable)
72 return win32_modify_privilege(SE_RESTORE_NAME, enable)
73 && win32_modify_privilege(SE_SECURITY_NAME, enable)
74 && win32_modify_privilege(SE_TAKE_OWNERSHIP_NAME, enable);
78 win32_release_capture_and_apply_privileges(void)
80 win32_modify_capture_privileges(false);
81 win32_modify_apply_privileges(false);
84 /* Pointers to dynamically loaded functions */
88 NTSTATUS (WINAPI *func_NtCreateFile)(PHANDLE FileHandle,
89 ACCESS_MASK DesiredAccess,
90 POBJECT_ATTRIBUTES ObjectAttributes,
91 PIO_STATUS_BLOCK IoStatusBlock,
92 PLARGE_INTEGER AllocationSize,
95 ULONG CreateDisposition,
100 NTSTATUS (WINAPI *func_NtOpenFile) (PHANDLE FileHandle,
101 ACCESS_MASK DesiredAccess,
102 POBJECT_ATTRIBUTES ObjectAttributes,
103 PIO_STATUS_BLOCK IoStatusBlock,
107 NTSTATUS (WINAPI *func_NtReadFile) (HANDLE FileHandle,
109 PIO_APC_ROUTINE ApcRoutine,
111 PIO_STATUS_BLOCK IoStatusBlock,
114 PLARGE_INTEGER ByteOffset,
117 NTSTATUS (WINAPI *func_NtWriteFile) (HANDLE FileHandle,
119 PIO_APC_ROUTINE ApcRoutine,
121 PIO_STATUS_BLOCK IoStatusBlock,
124 PLARGE_INTEGER ByteOffset,
127 NTSTATUS (WINAPI *func_NtQueryInformationFile)(HANDLE FileHandle,
128 PIO_STATUS_BLOCK IoStatusBlock,
129 PVOID FileInformation,
131 FILE_INFORMATION_CLASS FileInformationClass);
133 NTSTATUS (WINAPI *func_NtQuerySecurityObject)(HANDLE handle,
134 SECURITY_INFORMATION SecurityInformation,
135 PSECURITY_DESCRIPTOR SecurityDescriptor,
137 PULONG LengthNeeded);
139 NTSTATUS (WINAPI *func_NtQueryDirectoryFile) (HANDLE FileHandle,
141 PIO_APC_ROUTINE ApcRoutine,
143 PIO_STATUS_BLOCK IoStatusBlock,
144 PVOID FileInformation,
146 FILE_INFORMATION_CLASS FileInformationClass,
147 BOOLEAN ReturnSingleEntry,
148 PUNICODE_STRING FileName,
149 BOOLEAN RestartScan);
151 NTSTATUS (WINAPI *func_NtQueryVolumeInformationFile) (HANDLE FileHandle,
152 PIO_STATUS_BLOCK IoStatusBlock,
155 FS_INFORMATION_CLASS FsInformationClass);
157 NTSTATUS (WINAPI *func_NtSetInformationFile)(HANDLE FileHandle,
158 PIO_STATUS_BLOCK IoStatusBlock,
159 PVOID FileInformation,
161 FILE_INFORMATION_CLASS FileInformationClass);
163 NTSTATUS (WINAPI *func_NtSetSecurityObject)(HANDLE Handle,
164 SECURITY_INFORMATION SecurityInformation,
165 PSECURITY_DESCRIPTOR SecurityDescriptor);
167 NTSTATUS (WINAPI *func_NtFsControlFile) (HANDLE FileHandle,
169 PIO_APC_ROUTINE ApcRoutine,
171 PIO_STATUS_BLOCK IoStatusBlock,
174 ULONG InputBufferLength,
176 ULONG OutputBufferLength);
178 NTSTATUS (WINAPI *func_NtClose) (HANDLE Handle);
180 DWORD (WINAPI *func_RtlNtStatusToDosError)(NTSTATUS status);
182 BOOLEAN (WINAPI *func_RtlDosPathNameToNtPathName_U)
184 OUT PUNICODE_STRING NtName,
185 OUT PCWSTR *PartName,
186 OUT PRTL_RELATIVE_NAME_U RelativeName);
188 NTSTATUS (WINAPI *func_RtlDosPathNameToNtPathName_U_WithStatus)
190 OUT PUNICODE_STRING NtName,
191 OUT PCWSTR *PartName,
192 OUT PRTL_RELATIVE_NAME_U RelativeName);
194 NTSTATUS (WINAPI *func_RtlCreateSystemVolumeInformationFolder)
195 (PCUNICODE_STRING VolumeRootPath);
197 static bool acquired_privileges = false;
205 #define DLL_SYM(name, required) { (void **)&func_##name, #name, required }
207 #define for_each_sym(sym, spec) \
208 for ((sym) = (spec)->syms; (sym)->name; (sym)++)
213 const struct dll_sym syms[];
216 struct dll_spec ntdll_spec = {
217 .name = L"ntdll.dll",
219 DLL_SYM(NtCreateFile, true),
220 DLL_SYM(NtOpenFile, true),
221 DLL_SYM(NtReadFile, true),
222 DLL_SYM(NtWriteFile, true),
223 DLL_SYM(NtQueryInformationFile, true),
224 DLL_SYM(NtQuerySecurityObject, true),
225 DLL_SYM(NtQueryDirectoryFile, true),
226 DLL_SYM(NtQueryVolumeInformationFile, true),
227 DLL_SYM(NtSetInformationFile, true),
228 DLL_SYM(NtSetSecurityObject, true),
229 DLL_SYM(NtFsControlFile, true),
230 DLL_SYM(NtClose, true),
231 DLL_SYM(RtlNtStatusToDosError, true),
232 DLL_SYM(RtlCreateSystemVolumeInformationFolder, false),
233 DLL_SYM(RtlDosPathNameToNtPathName_U, true),
234 DLL_SYM(RtlDosPathNameToNtPathName_U_WithStatus, false), /* Not present on XP */
240 init_dll(struct dll_spec *spec)
242 const struct dll_sym *sym;
246 spec->handle = LoadLibrary(spec->name);
248 for_each_sym(sym, spec) {
250 ERROR("%ls could not be loaded!", spec->name);
251 return WIMLIB_ERR_UNSUPPORTED;
256 for_each_sym(sym, spec) {
257 addr = (void *)GetProcAddress(spec->handle, sym->name);
259 *(sym->func_ptr) = addr;
260 } else if (sym->required) {
261 ERROR("Can't find %s in %ls", sym->name, spec->name);
262 return WIMLIB_ERR_UNSUPPORTED;
269 cleanup_dll(struct dll_spec *spec)
271 const struct dll_sym *sym;
274 FreeLibrary(spec->handle);
277 for_each_sym(sym, spec)
278 *(sym->func_ptr) = NULL;
282 /* One-time initialization for Windows capture/apply code. */
284 win32_global_init(int init_flags)
288 /* Try to acquire useful privileges. */
289 if (!(init_flags & WIMLIB_INIT_FLAG_DONT_ACQUIRE_PRIVILEGES)) {
290 ret = WIMLIB_ERR_INSUFFICIENT_PRIVILEGES;
291 if (!win32_modify_capture_privileges(true))
292 if (init_flags & WIMLIB_INIT_FLAG_STRICT_CAPTURE_PRIVILEGES)
294 if (!win32_modify_apply_privileges(true))
295 if (init_flags & WIMLIB_INIT_FLAG_STRICT_APPLY_PRIVILEGES)
297 acquired_privileges = true;
300 ret = init_dll(&ntdll_spec);
307 win32_release_capture_and_apply_privileges();
312 win32_global_cleanup(void)
314 if (acquired_privileges)
315 win32_release_capture_and_apply_privileges();
317 cleanup_dll(&ntdll_spec);
321 * Translates a Win32-namespace path into an NT-namespace path.
323 * On success, returns 0. The NT-namespace path will be stored in the
324 * UNICODE_STRING structure pointed to by nt_path. nt_path->Buffer will be set
325 * to a new buffer that must later be freed with HeapFree(). (Really
326 * RtlHeapFree(), but HeapFree() seems to be the same thing.)
328 * On failure, returns WIMLIB_ERR_NOMEM or WIMLIB_ERR_INVALID_PARAM.
331 win32_path_to_nt_path(const wchar_t *win32_path, UNICODE_STRING *nt_path)
335 if (func_RtlDosPathNameToNtPathName_U_WithStatus) {
336 status = (*func_RtlDosPathNameToNtPathName_U_WithStatus)(win32_path,
340 if ((*func_RtlDosPathNameToNtPathName_U)(win32_path, nt_path,
342 status = STATUS_SUCCESS;
344 status = STATUS_NO_MEMORY;
347 if (likely(NT_SUCCESS(status)))
350 if (status == STATUS_NO_MEMORY)
351 return WIMLIB_ERR_NOMEM;
353 ERROR("\"%ls\": invalid path name (status=0x%08"PRIx32")",
354 win32_path, (u32)status);
355 return WIMLIB_ERR_INVALID_PARAM;
359 win32_get_drive_path(const wchar_t *file_path, wchar_t drive_path[7])
363 file_abspath = realpath(file_path, NULL);
365 return WIMLIB_ERR_NOMEM;
367 if (file_abspath[0] == L'\0' || file_abspath[1] != L':') {
368 ERROR("\"%ls\": Path format not recognized", file_abspath);
370 return WIMLIB_ERR_UNSUPPORTED;
373 wsprintf(drive_path, L"\\\\.\\%lc:", file_abspath[0]);
379 windows_msg(u32 code, const wchar_t *format, va_list va,
380 bool is_ntstatus, bool is_error)
382 wchar_t _buf[STACK_MAX / 8];
384 size_t buflen = ARRAY_LEN(_buf);
389 n = vsnwprintf(buf, buflen, format, va);
394 n += snwprintf(&buf[n], buflen - n,
396 L" (status=%08"PRIx32"): " :
397 L" (err=%"PRIu32"): "),
403 ret = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
405 is_ntstatus ? (*func_RtlNtStatusToDosError)(code) : code,
406 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
412 if (n >= buflen || (ret == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER))
415 if (buf[n - 1] == L'\n')
417 if (buf[n - 1] == L'\r')
419 if (buf[n - 1] == L'.')
434 buf = MALLOC(buflen * sizeof(buf[0]));
437 ERROR("Ran out of memory while building error message!!!");
441 win32_warning(DWORD err, const wchar_t *format, ...)
445 va_start(va, format);
446 windows_msg(err, format, va, false, false);
451 win32_error(DWORD err, const wchar_t *format, ...)
455 va_start(va, format);
456 windows_msg(err, format, va, false, true);
461 winnt_warning(NTSTATUS status, const wchar_t *format, ...)
465 va_start(va, format);
466 windows_msg(status, format, va, true, false);
471 winnt_error(NTSTATUS status, const wchar_t *format, ...)
475 va_start(va, format);
476 windows_msg(status, format, va, true, true);
480 #endif /* __WIN32__ */