2 * win32_apply.c - Windows-specific code for applying files from a WIM image.
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/.
30 #include "wimlib/win32_common.h"
32 #include "wimlib/apply.h"
33 #include "wimlib/capture.h" /* for mangle_pat() and match_pattern_list() */
34 #include "wimlib/dentry.h"
35 #include "wimlib/error.h"
36 #include "wimlib/lookup_table.h"
37 #include "wimlib/resource.h"
38 #include "wimlib/textfile.h"
39 #include "wimlib/xml.h"
40 #include "wimlib/wim.h"
41 #include "wimlib/wimboot.h"
43 struct win32_apply_private_data {
45 struct string_set *prepopulate_pats;
46 void *mem_prepopulate_pats;
47 u8 wim_lookup_table_hash[SHA1_HASH_SIZE];
51 static struct win32_apply_private_data *
52 get_private_data(struct apply_ctx *ctx)
54 BUILD_BUG_ON(sizeof(ctx->private) < sizeof(struct win32_apply_private_data));
55 return (struct win32_apply_private_data *)(ctx->private);
59 free_prepopulate_pats(struct win32_apply_private_data *dat)
61 if (dat->prepopulate_pats) {
62 FREE(dat->prepopulate_pats->strings);
63 FREE(dat->prepopulate_pats);
64 dat->prepopulate_pats = NULL;
67 if (dat->mem_prepopulate_pats) {
68 FREE(dat->mem_prepopulate_pats);
69 dat->mem_prepopulate_pats = NULL;
74 load_prepopulate_pats(struct apply_ctx *ctx)
77 struct wim_dentry *dentry;
78 struct wim_lookup_table_entry *lte;
80 const tchar *path = WIMLIB_WIM_PATH_SEPARATOR_STRING T("Windows")
81 WIMLIB_WIM_PATH_SEPARATOR_STRING T("System32")
82 WIMLIB_WIM_PATH_SEPARATOR_STRING T("WimBootCompress.ini");
85 struct text_file_section sec;
86 struct win32_apply_private_data *dat = get_private_data(ctx);
88 dentry = get_dentry(ctx->wim, path, WIMLIB_CASE_INSENSITIVE);
90 (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
91 FILE_ATTRIBUTE_REPARSE_POINT |
92 FILE_ATTRIBUTE_ENCRYPTED)) ||
93 !(lte = inode_unnamed_lte(dentry->d_inode, ctx->wim->lookup_table)))
95 WARNING("%"TS" does not exist in WIM image!", path);
96 return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
99 ret = read_full_stream_into_alloc_buf(lte, &buf);
103 s = CALLOC(1, sizeof(struct string_set));
106 return WIMLIB_ERR_NOMEM;
109 sec.name = T("PrepopulateList");
112 ret = do_load_text_file(path, buf, lte->size, &mem, &sec, 1,
113 LOAD_TEXT_FILE_REMOVE_QUOTES |
114 LOAD_TEXT_FILE_NO_WARNINGS,
116 BUILD_BUG_ON(OS_PREFERRED_PATH_SEPARATOR != WIM_PATH_SEPARATOR);
122 dat->prepopulate_pats = s;
123 dat->mem_prepopulate_pats = mem;
128 in_prepopulate_list(struct wim_dentry *dentry, struct apply_ctx *ctx)
130 struct string_set *pats;
133 pats = get_private_data(ctx)->prepopulate_pats;
134 if (!pats || !pats->num_strings)
137 path = dentry_full_path(dentry);
141 return match_pattern_list(path, tstrlen(path), pats);
145 hash_lookup_table(WIMStruct *wim, u8 hash[SHA1_HASH_SIZE])
147 return wim_reshdr_to_hash(&wim->hdr.lookup_table_reshdr, wim, hash);
150 /* Given a Windows-style path, return the number of characters of the prefix
151 * that specify the path to the root directory of a drive, or return 0 if the
152 * drive is relative (or at least on the current drive, in the case of
153 * absolute-but-not-really-absolute paths like \Windows\System32) */
155 win32_path_drive_spec_len(const wchar_t *path)
159 if (!wcsncmp(path, L"\\\\?\\", 4)) {
160 /* \\?\-prefixed path. Check for following drive letter and
162 if (path[4] != L'\0' && path[5] == L':' &&
163 is_any_path_separator(path[6]))
166 /* Not a \\?\-prefixed path. Check for an initial drive letter
167 * and path separator. */
168 if (path[0] != L'\0' && path[1] == L':' &&
169 is_any_path_separator(path[2]))
172 /* Include any additional path separators.*/
174 while (is_any_path_separator(path[n]))
180 win32_path_is_root_of_drive(const wchar_t *path)
182 size_t drive_spec_len;
183 wchar_t full_path[32768];
186 ret = GetFullPathName(path, ARRAY_LEN(full_path), full_path, NULL);
187 if (ret > 0 && ret < ARRAY_LEN(full_path))
190 /* Explicit drive letter and path separator? */
191 drive_spec_len = win32_path_drive_spec_len(path);
192 if (drive_spec_len > 0 && path[drive_spec_len] == L'\0')
195 /* All path separators? */
196 for (const wchar_t *p = path; *p != L'\0'; p++)
197 if (!is_any_path_separator(*p))
202 /* Given a path, which may not yet exist, get a set of flags that describe the
203 * features of the volume the path is on. */
205 win32_get_vol_flags(const wchar_t *path, unsigned *vol_flags_ret,
206 bool *supports_SetFileShortName_ret)
211 size_t drive_spec_len;
212 wchar_t filesystem_name[MAX_PATH + 1];
214 if (supports_SetFileShortName_ret)
215 *supports_SetFileShortName_ret = false;
217 drive_spec_len = win32_path_drive_spec_len(path);
219 if (drive_spec_len == 0)
220 if (path[0] != L'\0' && path[1] == L':') /* Drive-relative path? */
223 if (drive_spec_len == 0) {
224 /* Path does not start with a drive letter; use the volume of
225 * the current working directory. */
228 /* Path starts with a drive letter (or \\?\ followed by a drive
229 * letter); use it. */
230 volume = alloca((drive_spec_len + 2) * sizeof(wchar_t));
231 wmemcpy(volume, path, drive_spec_len);
232 /* Add trailing backslash in case this was a drive-relative
234 volume[drive_spec_len] = L'\\';
235 volume[drive_spec_len + 1] = L'\0';
237 bret = GetVolumeInformation(
238 volume, /* lpRootPathName */
239 NULL, /* lpVolumeNameBuffer */
240 0, /* nVolumeNameSize */
241 NULL, /* lpVolumeSerialNumber */
242 NULL, /* lpMaximumComponentLength */
243 &vol_flags, /* lpFileSystemFlags */
244 filesystem_name, /* lpFileSystemNameBuffer */
245 ARRAY_LEN(filesystem_name)); /* nFileSystemNameSize */
247 set_errno_from_GetLastError();
248 WARNING_WITH_ERRNO("Failed to get volume information for "
249 "path \"%ls\"", path);
250 vol_flags = 0xffffffff;
254 if (wcsstr(filesystem_name, L"NTFS")) {
255 /* FILE_SUPPORTS_HARD_LINKS is only supported on Windows 7 and later.
256 * Force it on anyway if filesystem is NTFS. */
257 vol_flags |= FILE_SUPPORTS_HARD_LINKS;
259 if (supports_SetFileShortName_ret)
260 *supports_SetFileShortName_ret = true;
264 DEBUG("using vol_flags = %x", vol_flags);
265 *vol_flags_ret = vol_flags;
270 win32_start_extract(const wchar_t *path, struct apply_ctx *ctx)
274 bool supports_SetFileShortName;
275 struct win32_apply_private_data *dat = get_private_data(ctx);
277 ret = win32_get_vol_flags(path, &vol_flags, &supports_SetFileShortName);
281 ctx->supported_features.archive_files = 1;
282 ctx->supported_features.hidden_files = 1;
283 ctx->supported_features.system_files = 1;
285 if (vol_flags & FILE_FILE_COMPRESSION)
286 ctx->supported_features.compressed_files = 1;
288 if (vol_flags & FILE_SUPPORTS_ENCRYPTION) {
289 ctx->supported_features.encrypted_files = 1;
290 ctx->supported_features.encrypted_directories = 1;
293 ctx->supported_features.not_context_indexed_files = 1;
296 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES)
297 ctx->supported_features.sparse_files = 1;
300 if (vol_flags & FILE_NAMED_STREAMS)
301 ctx->supported_features.named_data_streams = 1;
303 if (vol_flags & FILE_SUPPORTS_HARD_LINKS)
304 ctx->supported_features.hard_links = 1;
306 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
307 ctx->supported_features.reparse_points = 1;
308 if (func_CreateSymbolicLinkW)
309 ctx->supported_features.symlink_reparse_points = 1;
312 if (vol_flags & FILE_PERSISTENT_ACLS)
313 ctx->supported_features.security_descriptors = 1;
315 if (supports_SetFileShortName)
316 ctx->supported_features.short_names = 1;
318 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT) {
320 ret = load_prepopulate_pats(ctx);
321 if (ret == WIMLIB_ERR_NOMEM)
324 if (!wim_info_get_wimboot(ctx->wim->wim_info,
325 ctx->wim->current_image))
326 WARNING("Image is not marked as WIMBoot compatible!");
329 ret = hash_lookup_table(ctx->wim, dat->wim_lookup_table_hash);
333 ret = wimboot_alloc_data_source_id(ctx->wim->filename,
335 ctx->wim->current_image,
337 &dat->data_source_id,
346 free_prepopulate_pats(dat);
351 win32_finish_extract(struct apply_ctx *ctx)
353 free_prepopulate_pats(get_private_data(ctx));
357 /* Delete a non-directory file, working around Windows quirks. */
359 win32_delete_file_wrapper(const wchar_t *path)
364 if (DeleteFile(path))
367 err = GetLastError();
368 attrib = GetFileAttributes(path);
369 if ((attrib != INVALID_FILE_ATTRIBUTES) &&
370 (attrib & FILE_ATTRIBUTE_READONLY))
372 /* Try again with FILE_ATTRIBUTE_READONLY cleared. */
373 attrib &= ~FILE_ATTRIBUTE_READONLY;
374 if (SetFileAttributes(path, attrib)) {
375 if (DeleteFile(path))
378 err = GetLastError();
387 /* Create a normal file, overwriting one already present. */
389 win32_create_file(const wchar_t *path, struct apply_ctx *ctx, u64 *cookie_ret)
395 * WRITE_OWNER and WRITE_DAC privileges are required for some reason,
396 * even through we're creating a new file.
398 * FILE_FLAG_OPEN_REPARSE_POINT is required to prevent an existing
399 * reparse point from redirecting the creation of the new file
400 * (potentially to an arbitrary location).
402 * CREATE_ALWAYS could be used instead of CREATE_NEW. However, there
403 * are quirks that would need to be handled (e.g. having to set
404 * FILE_ATTRIBUTE_HIDDEN and/or FILE_ATTRIBUTE_SYSTEM if the existing
405 * file had them specified, and/or having to clear
406 * FILE_ATTRIBUTE_READONLY on the existing file). It's simpler to just
407 * call win32_delete_file_wrapper() to delete the existing file in such
408 * a way that already handles the FILE_ATTRIBUTE_READONLY quirk.
411 h = CreateFile(path, WRITE_OWNER | WRITE_DAC, 0, NULL, CREATE_NEW,
412 FILE_FLAG_BACKUP_SEMANTICS |
413 FILE_FLAG_OPEN_REPARSE_POINT, NULL);
414 if (h == INVALID_HANDLE_VALUE) {
415 DWORD err = GetLastError();
417 if (err == ERROR_FILE_EXISTS && win32_delete_file_wrapper(path))
419 set_errno_from_win32_error(err);
420 return WIMLIB_ERR_OPEN;
427 win32_create_directory(const wchar_t *path, struct apply_ctx *ctx,
430 if (!CreateDirectory(path, NULL))
431 if (GetLastError() != ERROR_ALREADY_EXISTS)
436 set_errno_from_GetLastError();
437 return WIMLIB_ERR_MKDIR;
441 win32_create_hardlink(const wchar_t *oldpath, const wchar_t *newpath,
442 struct apply_ctx *ctx)
444 if (!CreateHardLink(newpath, oldpath, NULL)) {
445 if (GetLastError() != ERROR_ALREADY_EXISTS)
447 if (!win32_delete_file_wrapper(newpath))
449 if (!CreateHardLink(newpath, oldpath, NULL))
455 set_errno_from_GetLastError();
456 return WIMLIB_ERR_LINK;
460 win32_create_symlink(const wchar_t *oldpath, const wchar_t *newpath,
461 struct apply_ctx *ctx)
463 if (!(*func_CreateSymbolicLinkW)(newpath, oldpath, 0)) {
464 if (GetLastError() != ERROR_ALREADY_EXISTS)
466 if (!win32_delete_file_wrapper(newpath))
468 if (!(*func_CreateSymbolicLinkW)(newpath, oldpath, 0))
474 set_errno_from_GetLastError();
475 return WIMLIB_ERR_LINK;
479 win32_extract_wim_chunk(const void *buf, size_t len, void *arg)
481 HANDLE h = (HANDLE)arg;
482 DWORD nbytes_written;
484 if (unlikely(!WriteFile(h, buf, len, &nbytes_written, NULL)))
486 if (unlikely(nbytes_written != len))
491 set_errno_from_GetLastError();
492 return WIMLIB_ERR_WRITE;
496 win32_extract_stream(const wchar_t *path, const wchar_t *stream_name,
497 size_t stream_name_nchars,
498 struct wim_lookup_table_entry *lte, struct apply_ctx *ctx)
500 DWORD creationDisposition = OPEN_EXISTING;
501 wchar_t *stream_path = (wchar_t*)path;
505 if (stream_name_nchars) {
506 creationDisposition = CREATE_ALWAYS;
507 stream_path = alloca(sizeof(wchar_t) *
509 wcslen(stream_name) + 1));
510 tsprintf(stream_path, L"%ls:%ls", path, stream_name);
513 h = CreateFile(stream_path, FILE_WRITE_DATA, 0, NULL,
514 creationDisposition, FILE_FLAG_BACKUP_SEMANTICS |
515 FILE_FLAG_OPEN_REPARSE_POINT,
517 if (h == INVALID_HANDLE_VALUE) {
518 set_errno_from_GetLastError();
519 ret = WIMLIB_ERR_OPEN;
525 goto out_close_handle;
528 if (!SetFilePointerEx(h,
529 (LARGE_INTEGER) { .QuadPart = lte->size},
534 if (!SetEndOfFile(h))
537 if (!SetFilePointerEx(h,
538 (LARGE_INTEGER) { .QuadPart = 0},
543 ret = extract_stream(lte, lte->size, win32_extract_wim_chunk, h);
544 goto out_close_handle;
547 set_errno_from_GetLastError();
548 ret = WIMLIB_ERR_WRITE;
551 if (!CloseHandle(h)) {
553 set_errno_from_GetLastError();
554 ret = WIMLIB_ERR_WRITE;
562 win32_extract_unnamed_stream(file_spec_t file,
563 struct wim_lookup_table_entry *lte,
564 struct apply_ctx *ctx,
565 struct wim_dentry *dentry)
567 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT
569 && lte->resource_location == RESOURCE_IN_WIM
570 && lte->rspec->wim == ctx->wim
571 && lte->size == lte->rspec->uncompressed_size)
573 if (in_prepopulate_list(dentry, ctx)) {
574 if (ctx->progress_func) {
575 union wimlib_progress_info info;
577 info.wimboot_exclude.path_in_wim = dentry->_full_path;
578 info.wimboot_exclude.extraction_path = file.path;
580 ctx->progress_func(WIMLIB_PROGRESS_MSG_WIMBOOT_EXCLUDE,
584 const struct win32_apply_private_data *dat;
586 dat = get_private_data(ctx);
587 return wimboot_set_pointer(file.path, lte,
589 dat->wim_lookup_table_hash,
594 return win32_extract_stream(file.path, NULL, 0, lte, ctx);
598 win32_extract_named_stream(file_spec_t file, const wchar_t *stream_name,
599 size_t stream_name_nchars,
600 struct wim_lookup_table_entry *lte, struct apply_ctx *ctx)
602 return win32_extract_stream(file.path, stream_name,
603 stream_name_nchars, lte, ctx);
606 struct win32_encrypted_extract_ctx {
607 const struct wim_lookup_table_entry *lte;
612 win32_encrypted_import_cb(unsigned char *data, void *_import_ctx,
613 unsigned long *len_p)
615 struct win32_encrypted_extract_ctx *import_ctx = _import_ctx;
616 unsigned long len = *len_p;
617 const struct wim_lookup_table_entry *lte = import_ctx->lte;
619 len = min(len, lte->size - import_ctx->offset);
621 if (read_partial_wim_stream_into_buf(lte, len, import_ctx->offset, data))
622 return ERROR_READ_FAULT;
624 import_ctx->offset += len;
626 return ERROR_SUCCESS;
630 win32_extract_encrypted_stream(const wchar_t *path,
631 struct wim_lookup_table_entry *lte,
632 struct apply_ctx *ctx)
637 struct win32_encrypted_extract_ctx extract_ctx;
639 err = OpenEncryptedFileRaw(path, CREATE_FOR_IMPORT, &file_ctx);
640 if (err != ERROR_SUCCESS) {
641 set_errno_from_win32_error(err);
642 ret = WIMLIB_ERR_OPEN;
646 extract_ctx.lte = lte;
647 extract_ctx.offset = 0;
648 err = WriteEncryptedFileRaw(win32_encrypted_import_cb, &extract_ctx,
650 if (err != ERROR_SUCCESS) {
651 set_errno_from_win32_error(err);
652 ret = WIMLIB_ERR_WRITE;
658 CloseEncryptedFileRaw(file_ctx);
664 win32_set_special_file_attributes(const wchar_t *path, u32 attributes)
668 USHORT compression_format = COMPRESSION_FORMAT_DEFAULT;
669 DWORD bytes_returned;
671 h = win32_open_existing_file(path, GENERIC_READ | GENERIC_WRITE);
672 if (h == INVALID_HANDLE_VALUE)
675 /* Don't make extracted files sparse. It is pointless without also
676 * skipping over runs of zeroes when writing the file, and in fact
677 * increases disk usage --- apparently, allocation sizes in sparse files
678 * are rounded up to multiples of 131072 bytes rather than 4096 bytes.
679 * And in some Windows 7 images, *all* files are set as sparse for some
680 * reason, which causes 1 GB+ of disk space to be wasted on the target
681 * drive of a full extraction.
683 * WIMGAPI seemingly does not make extracted files sparse either.
685 * XXX: We really ought to do a proper sparse extraction anyway if the
686 * file meets some heuristic that indicates this would be beneficial.
689 if (attributes & FILE_ATTRIBUTE_SPARSE_FILE)
690 if (!DeviceIoControl(h, FSCTL_SET_SPARSE,
693 &bytes_returned, NULL))
694 goto error_close_handle;
697 if (attributes & FILE_ATTRIBUTE_COMPRESSED)
698 if (!DeviceIoControl(h, FSCTL_SET_COMPRESSION,
699 &compression_format, sizeof(USHORT),
701 &bytes_returned, NULL))
702 goto error_close_handle;
707 if (attributes & FILE_ATTRIBUTE_ENCRYPTED)
708 if (!EncryptFile(path))
714 err = GetLastError();
722 win32_set_file_attributes(const wchar_t *path, u32 attributes,
723 struct apply_ctx *ctx, unsigned pass)
725 u32 special_attributes =
726 FILE_ATTRIBUTE_REPARSE_POINT |
727 FILE_ATTRIBUTE_DIRECTORY |
728 FILE_ATTRIBUTE_SPARSE_FILE |
729 FILE_ATTRIBUTE_COMPRESSED |
730 FILE_ATTRIBUTE_ENCRYPTED;
731 u32 actual_attributes;
733 /* Delay setting FILE_ATTRIBUTE_READONLY on the initial pass (when files
734 * are created, but data not extracted); otherwise the system will
735 * refuse access to the file even if the process has SeRestorePrivilege.
738 attributes &= ~FILE_ATTRIBUTE_READONLY;
740 if (!SetFileAttributes(path, attributes & ~special_attributes))
746 if (attributes & (FILE_ATTRIBUTE_SPARSE_FILE |
747 FILE_ATTRIBUTE_ENCRYPTED |
748 FILE_ATTRIBUTE_COMPRESSED))
749 if (!win32_set_special_file_attributes(path, attributes))
752 /* If file is not supposed to be encrypted or compressed, remove
753 * defaulted encrypted or compressed attributes (from creating file in
754 * encrypted or compressed directory). */
755 actual_attributes = GetFileAttributes(path);
756 if (actual_attributes == INVALID_FILE_ATTRIBUTES)
759 if ((actual_attributes & FILE_ATTRIBUTE_ENCRYPTED) &&
760 !(attributes & FILE_ATTRIBUTE_ENCRYPTED))
761 if (!DecryptFile(path, 0))
763 if ((actual_attributes & FILE_ATTRIBUTE_COMPRESSED) &&
764 !(attributes & FILE_ATTRIBUTE_COMPRESSED))
767 DWORD bytes_returned;
768 USHORT compression_format = COMPRESSION_FORMAT_NONE;
770 h = win32_open_existing_file(path, GENERIC_READ | GENERIC_WRITE);
771 if (h == INVALID_HANDLE_VALUE)
774 if (!DeviceIoControl(h, FSCTL_SET_COMPRESSION,
775 &compression_format, sizeof(USHORT),
777 &bytes_returned, NULL))
779 DWORD err = GetLastError();
792 set_errno_from_GetLastError();
793 return WIMLIB_ERR_SET_ATTRIBUTES;
797 win32_set_reparse_data(const wchar_t *path, const u8 *rpbuf, u16 rpbuflen,
798 struct apply_ctx *ctx)
802 DWORD bytes_returned;
804 h = win32_open_existing_file(path, GENERIC_WRITE);
805 if (h == INVALID_HANDLE_VALUE)
808 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT,
809 (void*)rpbuf, rpbuflen,
810 NULL, 0, &bytes_returned, NULL))
811 goto error_close_handle;
819 err = GetLastError();
823 set_errno_from_GetLastError();
824 return WIMLIB_ERR_WRITE; /* XXX: need better error code */
828 win32_set_short_name(const wchar_t *path, const wchar_t *short_name,
829 size_t short_name_nchars, struct apply_ctx *ctx)
834 h = win32_open_existing_file(path, GENERIC_WRITE | DELETE);
835 if (h == INVALID_HANDLE_VALUE)
838 if (short_name_nchars) {
839 if (!SetFileShortName(h, short_name))
840 goto error_close_handle;
841 } else if (running_on_windows_7_or_later()) {
842 if (!SetFileShortName(h, L""))
843 goto error_close_handle;
852 err = GetLastError();
856 set_errno_from_GetLastError();
857 return WIMLIB_ERR_WRITE; /* XXX: need better error code */
861 * Set an arbitrary security descriptor on an arbitrary file (or directory),
862 * working around bugs and design flaws in the Windows operating system.
864 * On success, return 0. On failure, return WIMLIB_ERR_SET_SECURITY and set
865 * errno. Note: if WIMLIB_EXTRACT_FLAG_STRICT_ACLS is not set in
866 * ctx->extract_flags, this function succeeds iff any part of the security
867 * descriptor was successfully set.
870 win32_set_security_descriptor(const wchar_t *path, const u8 *desc,
871 size_t desc_size, struct apply_ctx *ctx)
873 SECURITY_INFORMATION info;
874 DWORD dwDesiredAccess;
879 /* We really just want to set entire the security descriptor as-is, but
880 * all available APIs require specifying the specific parts of the
881 * descriptor being set. Start out by requesting all parts be set. If
882 * permissions problems are encountered, fall back to omitting some
883 * parts (first the SACL, then the DACL, then the owner), unless the
884 * WIMLIB_EXTRACT_FLAG_STRICT_ACLS flag has been enabled. */
885 info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
886 DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION;
888 /* Prefer NtSetSecurityObject() to SetFileSecurity(). SetFileSecurity()
889 * itself necessarily uses NtSetSecurityObject() as the latter is the
890 * underlying system call for setting security information, but
891 * SetFileSecurity() opens the handle with NtCreateFile() without
892 * FILE_OPEN_FILE_BACKUP_INTENT. Hence, access checks are done and due
893 * to the Windows security model, even a process running as the
894 * Administrator can have access denied. (Of course, this not mentioned
895 * in the MS "documentation".) */
897 /* Open a handle for NtSetSecurityObject() with as many relevant
898 * access rights as possible.
900 * We don't know which rights will be actually granted. It
901 * could be less than what is needed to actually assign the full
902 * security descriptor, especially if the process is running as
903 * a non-Administrator. However, by default we just do the best
904 * we can, unless WIMLIB_EXTRACT_FLAG_STRICT_ACLS has been
905 * enabled. The MAXIMUM_ALLOWED access right is seemingly
906 * designed for this use case; however, it does not work
907 * properly in all cases: it can cause CreateFile() to fail with
908 * ERROR_ACCESS_DENIED, even though by definition
909 * MAXIMUM_ALLOWED access only requests access rights that are
910 * *not* denied. (Needless to say, MS does not document this
913 dwDesiredAccess = WRITE_DAC | WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
914 while ((h = win32_open_existing_file(path,
915 dwDesiredAccess)) == INVALID_HANDLE_VALUE)
919 err = GetLastError();
920 if (err == ERROR_ACCESS_DENIED ||
921 err == ERROR_PRIVILEGE_NOT_HELD)
923 /* Don't increment partial_security_descriptors
924 * here or check WIMLIB_EXTRACT_FLAG_STRICT_ACLS
925 * here. It will be done later if needed; here
926 * we are just trying to get as many relevant
927 * access rights as possible. */
928 if (dwDesiredAccess & ACCESS_SYSTEM_SECURITY) {
929 dwDesiredAccess &= ~ACCESS_SYSTEM_SECURITY;
932 if (dwDesiredAccess & WRITE_DAC) {
933 dwDesiredAccess &= ~WRITE_DAC;
936 if (dwDesiredAccess & WRITE_OWNER) {
937 dwDesiredAccess &= ~WRITE_OWNER;
941 /* Other error, or couldn't open the file even with no
942 * access rights specified. Something else must be
944 set_errno_from_win32_error(err);
945 return WIMLIB_ERR_SET_SECURITY;
948 /* Try setting the security descriptor. */
950 while (!(NT_SUCCESS(status = (*func_NtSetSecurityObject)(h,
952 (PSECURITY_DESCRIPTOR)desc))))
954 /* Failed to set the requested parts of the security descriptor.
955 * If the error was permissions-related, try to set fewer parts
956 * of the security descriptor, unless
957 * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled. */
958 if ((status == STATUS_PRIVILEGE_NOT_HELD ||
959 status == STATUS_ACCESS_DENIED) &&
960 !(ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
962 if (info & SACL_SECURITY_INFORMATION) {
963 info &= ~SACL_SECURITY_INFORMATION;
964 ctx->partial_security_descriptors++;
967 if (info & DACL_SECURITY_INFORMATION) {
968 info &= ~DACL_SECURITY_INFORMATION;
971 if (info & OWNER_SECURITY_INFORMATION) {
972 info &= ~OWNER_SECURITY_INFORMATION;
975 /* Nothing left except GROUP, and if we removed it we
976 * wouldn't have anything at all. */
978 /* No part of the security descriptor could be set, or
979 * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled and the full
980 * security descriptor could not be set. */
981 if (!(info & SACL_SECURITY_INFORMATION))
982 ctx->partial_security_descriptors--;
983 set_errno_from_nt_status(status);
984 ret = WIMLIB_ERR_SET_SECURITY;
988 /* Close handle opened for NtSetSecurityObject(). */
994 win32_set_timestamps(const wchar_t *path, u64 creation_time,
995 u64 last_write_time, u64 last_access_time,
996 struct apply_ctx *ctx)
1000 FILETIME creationTime = {.dwLowDateTime = creation_time & 0xffffffff,
1001 .dwHighDateTime = creation_time >> 32};
1002 FILETIME lastAccessTime = {.dwLowDateTime = last_access_time & 0xffffffff,
1003 .dwHighDateTime = last_access_time >> 32};
1004 FILETIME lastWriteTime = {.dwLowDateTime = last_write_time & 0xffffffff,
1005 .dwHighDateTime = last_write_time >> 32};
1007 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1008 if (h == INVALID_HANDLE_VALUE)
1011 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime))
1012 goto error_close_handle;
1014 if (!CloseHandle(h))
1020 err = GetLastError();
1024 set_errno_from_GetLastError();
1025 return WIMLIB_ERR_SET_TIMESTAMPS;
1028 const struct apply_operations win32_apply_ops = {
1031 .target_is_root = win32_path_is_root_of_drive,
1032 .start_extract = win32_start_extract,
1033 .finish_extract = win32_finish_extract,
1034 .abort_extract = win32_finish_extract,
1035 .create_file = win32_create_file,
1036 .create_directory = win32_create_directory,
1037 .create_hardlink = win32_create_hardlink,
1038 .create_symlink = win32_create_symlink,
1039 .extract_unnamed_stream = win32_extract_unnamed_stream,
1040 .extract_named_stream = win32_extract_named_stream,
1041 .extract_encrypted_stream = win32_extract_encrypted_stream,
1042 .set_file_attributes = win32_set_file_attributes,
1043 .set_reparse_data = win32_set_reparse_data,
1044 .set_short_name = win32_set_short_name,
1045 .set_security_descriptor = win32_set_security_descriptor,
1046 .set_timestamps = win32_set_timestamps,
1048 .path_prefix = L"\\\\?\\",
1049 .path_prefix_nchars = 4,
1050 .path_separator = L'\\',
1053 .requires_realtarget_in_paths = 1,
1054 .realpath_works_on_nonexisting_files = 1,
1055 .root_directory_is_special = 1,
1056 .requires_final_set_attributes_pass = 1,
1057 .extract_encrypted_stream_creates_file = 1,
1058 .requires_short_name_reordering = 1, /* TODO: check if this is really needed */
1061 #endif /* __WIN32__ */