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)
75 && win32_modify_privilege(SE_MANAGE_VOLUME_NAME, enable);
79 win32_release_capture_and_apply_privileges(void)
81 win32_modify_capture_privileges(false);
82 win32_modify_apply_privileges(false);
85 /* Pointers to dynamically loaded functions */
89 NTSTATUS (WINAPI *func_NtCreateFile)(PHANDLE FileHandle,
90 ACCESS_MASK DesiredAccess,
91 POBJECT_ATTRIBUTES ObjectAttributes,
92 PIO_STATUS_BLOCK IoStatusBlock,
93 PLARGE_INTEGER AllocationSize,
96 ULONG CreateDisposition,
101 NTSTATUS (WINAPI *func_NtOpenFile) (PHANDLE FileHandle,
102 ACCESS_MASK DesiredAccess,
103 POBJECT_ATTRIBUTES ObjectAttributes,
104 PIO_STATUS_BLOCK IoStatusBlock,
108 NTSTATUS (WINAPI *func_NtReadFile) (HANDLE FileHandle,
110 PIO_APC_ROUTINE ApcRoutine,
112 PIO_STATUS_BLOCK IoStatusBlock,
115 PLARGE_INTEGER ByteOffset,
118 NTSTATUS (WINAPI *func_NtWriteFile) (HANDLE FileHandle,
120 PIO_APC_ROUTINE ApcRoutine,
122 PIO_STATUS_BLOCK IoStatusBlock,
125 PLARGE_INTEGER ByteOffset,
128 NTSTATUS (WINAPI *func_NtQueryInformationFile)(HANDLE FileHandle,
129 PIO_STATUS_BLOCK IoStatusBlock,
130 PVOID FileInformation,
132 FILE_INFORMATION_CLASS FileInformationClass);
134 NTSTATUS (WINAPI *func_NtQuerySecurityObject)(HANDLE handle,
135 SECURITY_INFORMATION SecurityInformation,
136 PSECURITY_DESCRIPTOR SecurityDescriptor,
138 PULONG LengthNeeded);
140 NTSTATUS (WINAPI *func_NtQueryDirectoryFile) (HANDLE FileHandle,
142 PIO_APC_ROUTINE ApcRoutine,
144 PIO_STATUS_BLOCK IoStatusBlock,
145 PVOID FileInformation,
147 FILE_INFORMATION_CLASS FileInformationClass,
148 BOOLEAN ReturnSingleEntry,
149 PUNICODE_STRING FileName,
150 BOOLEAN RestartScan);
152 NTSTATUS (WINAPI *func_NtQueryVolumeInformationFile) (HANDLE FileHandle,
153 PIO_STATUS_BLOCK IoStatusBlock,
156 FS_INFORMATION_CLASS FsInformationClass);
158 NTSTATUS (WINAPI *func_NtSetInformationFile)(HANDLE FileHandle,
159 PIO_STATUS_BLOCK IoStatusBlock,
160 PVOID FileInformation,
162 FILE_INFORMATION_CLASS FileInformationClass);
164 NTSTATUS (WINAPI *func_NtSetSecurityObject)(HANDLE Handle,
165 SECURITY_INFORMATION SecurityInformation,
166 PSECURITY_DESCRIPTOR SecurityDescriptor);
168 NTSTATUS (WINAPI *func_NtFsControlFile) (HANDLE FileHandle,
170 PIO_APC_ROUTINE ApcRoutine,
172 PIO_STATUS_BLOCK IoStatusBlock,
175 ULONG InputBufferLength,
177 ULONG OutputBufferLength);
179 NTSTATUS (WINAPI *func_NtClose) (HANDLE Handle);
181 DWORD (WINAPI *func_RtlNtStatusToDosError)(NTSTATUS status);
183 BOOLEAN (WINAPI *func_RtlDosPathNameToNtPathName_U)
185 OUT PUNICODE_STRING NtName,
186 OUT PCWSTR *PartName,
187 OUT PRTL_RELATIVE_NAME_U RelativeName);
189 NTSTATUS (WINAPI *func_RtlDosPathNameToNtPathName_U_WithStatus)
191 OUT PUNICODE_STRING NtName,
192 OUT PCWSTR *PartName,
193 OUT PRTL_RELATIVE_NAME_U RelativeName);
195 NTSTATUS (WINAPI *func_RtlCreateSystemVolumeInformationFolder)
196 (PCUNICODE_STRING VolumeRootPath);
198 static bool acquired_privileges = false;
206 #define DLL_SYM(name, required) { (void **)&func_##name, #name, required }
208 #define for_each_sym(sym, spec) \
209 for ((sym) = (spec)->syms; (sym)->name; (sym)++)
214 const struct dll_sym syms[];
217 struct dll_spec ntdll_spec = {
218 .name = L"ntdll.dll",
220 DLL_SYM(NtCreateFile, true),
221 DLL_SYM(NtOpenFile, true),
222 DLL_SYM(NtReadFile, true),
223 DLL_SYM(NtWriteFile, true),
224 DLL_SYM(NtQueryInformationFile, true),
225 DLL_SYM(NtQuerySecurityObject, true),
226 DLL_SYM(NtQueryDirectoryFile, true),
227 DLL_SYM(NtQueryVolumeInformationFile, true),
228 DLL_SYM(NtSetInformationFile, true),
229 DLL_SYM(NtSetSecurityObject, true),
230 DLL_SYM(NtFsControlFile, true),
231 DLL_SYM(NtClose, true),
232 DLL_SYM(RtlNtStatusToDosError, true),
233 DLL_SYM(RtlCreateSystemVolumeInformationFolder, false),
234 DLL_SYM(RtlDosPathNameToNtPathName_U, true),
235 DLL_SYM(RtlDosPathNameToNtPathName_U_WithStatus, false), /* Not present on XP */
241 init_dll(struct dll_spec *spec)
243 const struct dll_sym *sym;
247 spec->handle = LoadLibrary(spec->name);
249 for_each_sym(sym, spec) {
251 ERROR("%ls could not be loaded!", spec->name);
252 return WIMLIB_ERR_UNSUPPORTED;
257 for_each_sym(sym, spec) {
258 addr = (void *)GetProcAddress(spec->handle, sym->name);
260 *(sym->func_ptr) = addr;
261 } else if (sym->required) {
262 ERROR("Can't find %s in %ls", sym->name, spec->name);
263 return WIMLIB_ERR_UNSUPPORTED;
270 cleanup_dll(struct dll_spec *spec)
272 const struct dll_sym *sym;
275 FreeLibrary(spec->handle);
278 for_each_sym(sym, spec)
279 *(sym->func_ptr) = NULL;
283 /* One-time initialization for Windows capture/apply code. */
285 win32_global_init(int init_flags)
289 /* Try to acquire useful privileges. */
290 if (!(init_flags & WIMLIB_INIT_FLAG_DONT_ACQUIRE_PRIVILEGES)) {
291 ret = WIMLIB_ERR_INSUFFICIENT_PRIVILEGES;
292 if (!win32_modify_capture_privileges(true))
293 if (init_flags & WIMLIB_INIT_FLAG_STRICT_CAPTURE_PRIVILEGES)
295 if (!win32_modify_apply_privileges(true))
296 if (init_flags & WIMLIB_INIT_FLAG_STRICT_APPLY_PRIVILEGES)
298 acquired_privileges = true;
301 ret = init_dll(&ntdll_spec);
308 win32_release_capture_and_apply_privileges();
313 win32_global_cleanup(void)
315 if (acquired_privileges)
316 win32_release_capture_and_apply_privileges();
318 cleanup_dll(&ntdll_spec);
322 * Translates a Win32-namespace path into an NT-namespace path.
324 * On success, returns 0. The NT-namespace path will be stored in the
325 * UNICODE_STRING structure pointed to by nt_path. nt_path->Buffer will be set
326 * to a new buffer that must later be freed with HeapFree(). (Really
327 * RtlHeapFree(), but HeapFree() seems to be the same thing.)
329 * On failure, returns WIMLIB_ERR_NOMEM or WIMLIB_ERR_INVALID_PARAM.
332 win32_path_to_nt_path(const wchar_t *win32_path, UNICODE_STRING *nt_path)
336 if (func_RtlDosPathNameToNtPathName_U_WithStatus) {
337 status = (*func_RtlDosPathNameToNtPathName_U_WithStatus)(win32_path,
341 if ((*func_RtlDosPathNameToNtPathName_U)(win32_path, nt_path,
343 status = STATUS_SUCCESS;
345 status = STATUS_NO_MEMORY;
348 if (likely(NT_SUCCESS(status)))
351 if (status == STATUS_NO_MEMORY)
352 return WIMLIB_ERR_NOMEM;
354 winnt_error(status, L"\"%ls\": invalid path name", win32_path);
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__ */