2 * win32_apply.c - Windows-specific code for applying files from a WIM image.
6 * Copyright (C) 2013-2018 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/apply.h"
31 #include "wimlib/assert.h"
32 #include "wimlib/blob_table.h"
33 #include "wimlib/dentry.h"
34 #include "wimlib/encoding.h"
35 #include "wimlib/error.h"
36 #include "wimlib/metadata.h"
37 #include "wimlib/object_id.h"
38 #include "wimlib/paths.h"
39 #include "wimlib/pattern.h"
40 #include "wimlib/reparse.h"
41 #include "wimlib/scan.h" /* for mangle_pat() and match_pattern_list() */
42 #include "wimlib/textfile.h"
43 #include "wimlib/wimboot.h"
44 #include "wimlib/wof.h"
45 #include "wimlib/xattr.h"
46 #include "wimlib/xml.h"
48 struct win32_apply_ctx {
50 /* Extract flags, the pointer to the WIMStruct, etc. */
51 struct apply_ctx common;
53 /* WIMBoot information, only filled in if WIMLIB_EXTRACT_FLAG_WIMBOOT
56 /* This array contains the WIM files registered with WOF on the
57 * target volume for this extraction operation. All WIMStructs
58 * in this array are distinct and have ->filename != NULL. */
62 u8 blob_table_hash[SHA1_HASH_SIZE];
66 bool have_wrong_version_wims;
67 bool have_uncompressed_wims;
68 bool have_unsupported_compressed_resources;
69 bool have_huge_resources;
72 /* External backing information */
73 struct string_list *prepopulate_pats;
74 void *mem_prepopulate_pats;
75 bool tried_to_load_prepopulate_list;
77 /* Open handle to the target directory */
80 /* NT namespace path to the target directory (buffer allocated) */
81 UNICODE_STRING target_ntpath;
83 /* Temporary buffer for building paths (buffer allocated) */
84 UNICODE_STRING pathbuf;
86 /* Object attributes to reuse for opening files in the target directory.
87 * (attr.ObjectName == &pathbuf) and (attr.RootDirectory == h_target).
89 OBJECT_ATTRIBUTES attr;
91 /* Temporary I/O status block for system calls */
94 /* Allocated buffer for creating "printable" paths from our
95 * target-relative NT paths */
96 wchar_t *print_buffer;
98 /* Allocated buffer for reading blob data when it cannot be extracted
102 /* Pointer to the next byte in @data_buffer to fill */
105 /* Size allocated in @data_buffer */
106 size_t data_buffer_size;
108 /* Current offset in the raw encrypted file being written */
109 size_t encrypted_offset;
111 /* Current size of the raw encrypted file being written */
112 size_t encrypted_size;
114 /* Temporary buffer for reparse data */
115 struct reparse_buffer_disk rpbuf;
117 /* Temporary buffer for reparse data of "fixed" absolute symbolic links
119 struct reparse_buffer_disk rpfixbuf;
121 /* Array of open handles to filesystem streams currently being written
123 HANDLE open_handles[MAX_OPEN_FILES];
125 /* Number of handles in @open_handles currently open (filled in from the
126 * beginning of the array) */
127 unsigned num_open_handles;
129 /* For each currently open stream, whether we're writing to it in
130 * "sparse" mode or not. */
131 bool is_sparse_stream[MAX_OPEN_FILES];
133 /* Whether is_sparse_stream[] is true for any currently open stream */
134 bool any_sparse_streams;
136 /* List of dentries, joined by @d_tmp_list, that need to have reparse
137 * data extracted as soon as the whole blob has been read into
139 struct list_head reparse_dentries;
141 /* List of dentries, joined by @d_tmp_list, that need to have raw
142 * encrypted data extracted as soon as the whole blob has been read into
144 struct list_head encrypted_dentries;
146 /* Number of files for which we didn't have permission to set the full
147 * security descriptor. */
148 unsigned long partial_security_descriptors;
150 /* Number of files for which we didn't have permission to set any part
151 * of the security descriptor. */
152 unsigned long no_security_descriptors;
154 /* Number of files for which we couldn't set the short name. */
155 unsigned long num_set_short_name_failures;
157 /* Number of files for which we couldn't remove the short name. */
158 unsigned long num_remove_short_name_failures;
160 /* Number of files on which we couldn't set System Compression. */
161 unsigned long num_system_compression_failures;
163 /* The number of files which, for compatibility with the Windows
164 * bootloader, were not compressed using the requested system
165 * compression format. This includes matches with the hardcoded pattern
166 * list only; it does not include matches with patterns in
167 * [PrepopulateList]. */
168 unsigned long num_system_compression_exclusions;
170 /* Number of files for which we couldn't set the object ID. */
171 unsigned long num_object_id_failures;
173 /* Number of files for which we couldn't set extended attributes. */
174 unsigned long num_xattr_failures;
176 /* The Windows build number of the image being applied, or 0 if unknown.
178 u64 windows_build_number;
180 /* Have we tried to enable short name support on the target volume yet?
182 bool tried_to_enable_short_names;
185 /* Get the drive letter from a Windows path, or return the null character if the
186 * path is relative. */
188 get_drive_letter(const wchar_t *path)
190 /* Skip \\?\ prefix */
191 if (!wcsncmp(path, L"\\\\?\\", 4))
194 /* Return drive letter if valid */
195 if (((path[0] >= L'a' && path[0] <= L'z') ||
196 (path[0] >= L'A' && path[0] <= L'Z')) && path[1] == L':')
203 get_vol_flags(const wchar_t *target, DWORD *vol_flags_ret,
204 bool *short_names_supported_ret)
206 wchar_t filesystem_name[MAX_PATH + 1];
208 wchar_t *volume = NULL;
211 *short_names_supported_ret = false;
213 drive[0] = get_drive_letter(target);
221 if (!GetVolumeInformation(volume, NULL, 0, NULL, NULL,
222 vol_flags_ret, filesystem_name,
223 ARRAY_LEN(filesystem_name)))
225 win32_warning(GetLastError(),
226 L"Failed to get volume information for \"%ls\"",
231 if (wcsstr(filesystem_name, L"NTFS")) {
233 * FILE_SUPPORTS_HARD_LINKS and
234 * FILE_SUPPORTS_EXTENDED_ATTRIBUTES are only supported on
235 * Windows 7 and later. Force them on anyway if the filesystem
238 *vol_flags_ret |= FILE_SUPPORTS_HARD_LINKS;
239 *vol_flags_ret |= FILE_SUPPORTS_EXTENDED_ATTRIBUTES;
241 /* There's no volume flag for short names, but according to the
242 * MS documentation they are only user-settable on NTFS. */
243 *short_names_supported_ret = true;
247 /* Is the image being extracted an OS image for Windows 10 or later? */
249 is_image_windows_10_or_later(struct win32_apply_ctx *ctx)
251 /* Note: if no build number is available, this returns false. */
252 return ctx->windows_build_number >= 10240;
255 static const wchar_t *
256 current_path(struct win32_apply_ctx *ctx);
259 build_extraction_path(const struct wim_dentry *dentry,
260 struct win32_apply_ctx *ctx);
263 report_dentry_apply_error(const struct wim_dentry *dentry,
264 struct win32_apply_ctx *ctx, int ret)
266 build_extraction_path(dentry, ctx);
267 return report_apply_error(&ctx->common, ret, current_path(ctx));
271 check_apply_error(const struct wim_dentry *dentry,
272 struct win32_apply_ctx *ctx, int ret)
275 ret = report_dentry_apply_error(dentry, ctx, ret);
280 win32_get_supported_features(const wchar_t *target,
281 struct wim_features *supported_features)
284 bool short_names_supported;
286 /* Query the features of the target volume. */
288 get_vol_flags(target, &vol_flags, &short_names_supported);
290 supported_features->readonly_files = 1;
291 supported_features->hidden_files = 1;
292 supported_features->system_files = 1;
293 supported_features->archive_files = 1;
295 if (vol_flags & FILE_FILE_COMPRESSION)
296 supported_features->compressed_files = 1;
298 if (vol_flags & FILE_SUPPORTS_ENCRYPTION) {
299 supported_features->encrypted_files = 1;
300 supported_features->encrypted_directories = 1;
303 supported_features->not_context_indexed_files = 1;
305 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES)
306 supported_features->sparse_files = 1;
308 if (vol_flags & FILE_NAMED_STREAMS)
309 supported_features->named_data_streams = 1;
311 if (vol_flags & FILE_SUPPORTS_HARD_LINKS)
312 supported_features->hard_links = 1;
314 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS)
315 supported_features->reparse_points = 1;
317 if (vol_flags & FILE_PERSISTENT_ACLS)
318 supported_features->security_descriptors = 1;
320 if (short_names_supported)
321 supported_features->short_names = 1;
323 if (vol_flags & FILE_SUPPORTS_OBJECT_IDS)
324 supported_features->object_ids = 1;
326 supported_features->timestamps = 1;
328 if (vol_flags & FILE_CASE_SENSITIVE_SEARCH) {
330 * The filesystem supports case-sensitive filenames. But does
331 * the operating system as well? This normally requires the
332 * registry setting ObCaseInsensitive=0. We can test it
333 * indirectly by attempting to open the "\SystemRoot" symbolic
334 * link using a name with the wrong case. If we get
335 * STATUS_OBJECT_NAME_NOT_FOUND instead of STATUS_ACCESS_DENIED,
336 * then case-sensitive names must be enabled.
339 OBJECT_ATTRIBUTES attr;
343 RtlInitUnicodeString(&path, L"\\systemroot");
344 InitializeObjectAttributes(&attr, &path, 0, NULL, NULL);
346 status = NtOpenSymbolicLinkObject(&h, 0, &attr);
347 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
348 supported_features->case_sensitive_filenames = 1;
351 if (vol_flags & FILE_SUPPORTS_EXTENDED_ATTRIBUTES)
352 supported_features->xattrs = 1;
357 #define COMPACT_FLAGS (WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS4K | \
358 WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS8K | \
359 WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS16K | \
360 WIMLIB_EXTRACT_FLAG_COMPACT_LZX)
365 * If not done already, load the patterns from the [PrepopulateList] section of
366 * WimBootCompress.ini in the WIM image being extracted.
368 * Note: WimBootCompress.ini applies to both types of "external backing":
370 * - WIM backing ("WIMBoot" - Windows 8.1 and later)
371 * - File backing ("System Compression" - Windows 10 and later)
374 load_prepopulate_pats(struct win32_apply_ctx *ctx)
376 const wchar_t *path = L"\\Windows\\System32\\WimBootCompress.ini";
377 struct wim_dentry *dentry;
378 const struct blob_descriptor *blob;
381 struct string_list *strings;
383 struct text_file_section sec;
385 if (ctx->tried_to_load_prepopulate_list)
388 ctx->tried_to_load_prepopulate_list = true;
390 dentry = get_dentry(ctx->common.wim, path, WIMLIB_CASE_INSENSITIVE);
392 (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
393 FILE_ATTRIBUTE_REPARSE_POINT |
394 FILE_ATTRIBUTE_ENCRYPTED)) ||
395 !(blob = inode_get_blob_for_unnamed_data_stream(dentry->d_inode,
396 ctx->common.wim->blob_table)))
398 WARNING("%ls does not exist in the WIM image.\n"
399 " The default configuration will be used instead; it assumes that all\n"
400 " files are valid for external backing regardless of path, equivalent\n"
401 " to an empty [PrepopulateList] section.", path);
402 return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
405 ret = read_blob_into_alloc_buf(blob, &buf);
409 strings = CALLOC(1, sizeof(struct string_list));
412 return WIMLIB_ERR_NOMEM;
415 sec.name = T("PrepopulateList");
416 sec.strings = strings;
418 ret = do_load_text_file(path, buf, blob->size, &mem, &sec, 1,
419 LOAD_TEXT_FILE_REMOVE_QUOTES |
420 LOAD_TEXT_FILE_NO_WARNINGS,
422 STATIC_ASSERT(OS_PREFERRED_PATH_SEPARATOR == WIM_PATH_SEPARATOR);
428 ctx->prepopulate_pats = strings;
429 ctx->mem_prepopulate_pats = mem;
433 /* Returns %true if the specified absolute path to a file in the WIM image can
434 * be subject to external backing when extracted. Otherwise returns %false. */
436 can_externally_back_path(const wchar_t *path, const struct win32_apply_ctx *ctx)
438 /* Does the path match a pattern given in the [PrepopulateList] section
439 * of WimBootCompress.ini? */
440 if (ctx->prepopulate_pats && match_pattern_list(path, ctx->prepopulate_pats))
443 /* Since we attempt to modify the SYSTEM registry after it's extracted
444 * (see end_wimboot_extraction()), it can't be extracted as externally
445 * backed. This extends to associated files such as SYSTEM.LOG that
446 * also must be writable in order to write to the registry. Normally,
447 * SYSTEM is in [PrepopulateList], and the SYSTEM.* files match patterns
448 * in [ExclusionList] and therefore are not captured in the WIM at all.
449 * However, a WIM that wasn't specifically captured in "WIMBoot mode"
450 * may contain SYSTEM.* files. So to make things "just work", hard-code
452 if (match_path(path, L"\\Windows\\System32\\config\\SYSTEM*", false))
458 /* Can the specified WIM resource be used as the source of an external backing
459 * for the wof.sys WIM provider? */
461 is_resource_valid_for_external_backing(const struct wim_resource_descriptor *rdesc,
462 struct win32_apply_ctx *ctx)
464 /* Must be the original WIM file format. This check excludes pipable
465 * resources and solid resources. It also excludes other resources
466 * contained in such files even if they would be otherwise compatible.
468 if (rdesc->wim->hdr.magic != WIM_MAGIC ||
469 rdesc->wim->hdr.wim_version != WIM_VERSION_DEFAULT)
471 ctx->wimboot.have_wrong_version_wims = true;
476 * Whitelist of compression types and chunk sizes supported by
477 * Microsoft's WOF driver.
480 * - Uncompressed WIMs result in BSOD. However, this only applies to
481 * the WIM file itself, not to uncompressed resources in a WIM file
482 * that is otherwise compressed.
483 * - XPRESS 64K sometimes appears to work, but sometimes it causes
484 * reads to fail with STATUS_UNSUCCESSFUL.
486 switch (rdesc->compression_type) {
487 case WIMLIB_COMPRESSION_TYPE_NONE:
488 if (rdesc->wim->compression_type == WIMLIB_COMPRESSION_TYPE_NONE) {
489 ctx->wimboot.have_uncompressed_wims = true;
493 case WIMLIB_COMPRESSION_TYPE_XPRESS:
494 switch (rdesc->chunk_size) {
501 ctx->wimboot.have_unsupported_compressed_resources = true;
505 case WIMLIB_COMPRESSION_TYPE_LZX:
506 switch (rdesc->chunk_size) {
510 ctx->wimboot.have_unsupported_compressed_resources = true;
515 ctx->wimboot.have_unsupported_compressed_resources = true;
519 /* Microsoft's WoF driver errors out if it tries to satisfy a read with
520 * ending offset >= 4 GiB from an externally backed file. */
521 if (rdesc->uncompressed_size > 4200000000) {
522 ctx->wimboot.have_huge_resources = true;
529 #define EXTERNAL_BACKING_NOT_ENABLED -1
530 #define EXTERNAL_BACKING_NOT_POSSIBLE -2
531 #define EXTERNAL_BACKING_EXCLUDED -3
534 * Determines whether the specified file will be externally backed. Returns a
535 * negative status code if no, 0 if yes, or a positive wimlib error code on
536 * error. If the file is excluded from external backing based on its path, then
537 * *excluded_dentry_ret is set to the dentry for the path that matched the
540 * Note that this logic applies to both types of "external backing":
542 * - WIM backing ("WIMBoot" - Windows 8.1 and later)
543 * - File backing ("System Compression" - Windows 10 and later)
545 * However, in the case of WIM backing we also need to validate that the WIM
546 * resource that would be the source of the backing is supported by the wof.sys
550 will_externally_back_inode(struct wim_inode *inode, struct win32_apply_ctx *ctx,
551 const struct wim_dentry **excluded_dentry_ret,
554 struct wim_dentry *dentry;
555 struct blob_descriptor *blob;
558 if (load_prepopulate_pats(ctx) == WIMLIB_ERR_NOMEM)
559 return WIMLIB_ERR_NOMEM;
561 if (inode->i_can_externally_back)
564 /* This may do redundant checks because the cached value
565 * i_can_externally_back is 2-state (as opposed to 3-state:
566 * unknown/no/yes). But most files can be externally backed, so this
569 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
570 FILE_ATTRIBUTE_REPARSE_POINT |
571 FILE_ATTRIBUTE_ENCRYPTED))
572 return EXTERNAL_BACKING_NOT_POSSIBLE;
574 blob = inode_get_blob_for_unnamed_data_stream_resolved(inode);
577 return EXTERNAL_BACKING_NOT_POSSIBLE;
580 (blob->blob_location != BLOB_IN_WIM ||
581 !is_resource_valid_for_external_backing(blob->rdesc, ctx)))
582 return EXTERNAL_BACKING_NOT_POSSIBLE;
585 * We need to check the patterns in [PrepopulateList] against every name
586 * of the inode, in case any of them match.
589 inode_for_each_extraction_alias(dentry, inode) {
591 ret = calculate_dentry_full_path(dentry);
595 if (!can_externally_back_path(dentry->d_full_path, ctx)) {
596 if (excluded_dentry_ret)
597 *excluded_dentry_ret = dentry;
598 return EXTERNAL_BACKING_EXCLUDED;
602 inode->i_can_externally_back = 1;
607 * Determines if the unnamed data stream of a file will be created as a WIM
608 * external backing (a "WIMBoot pointer file"), as opposed to a standard
612 win32_will_back_from_wim(struct wim_dentry *dentry, struct apply_ctx *_ctx)
614 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
616 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
617 return EXTERNAL_BACKING_NOT_ENABLED;
619 return will_externally_back_inode(dentry->d_inode, ctx, NULL, true);
622 /* Find the WOF registration information for the specified WIM file. */
623 static struct wimboot_wim *
624 find_wimboot_wim(WIMStruct *wim_to_find, struct win32_apply_ctx *ctx)
626 for (size_t i = 0; i < ctx->wimboot.num_wims; i++)
627 if (wim_to_find == ctx->wimboot.wims[i].wim)
628 return &ctx->wimboot.wims[i];
635 set_backed_from_wim(HANDLE h, struct wim_inode *inode, struct win32_apply_ctx *ctx)
638 const struct wim_dentry *excluded_dentry;
639 const struct blob_descriptor *blob;
640 const struct wimboot_wim *wimboot_wim;
642 ret = will_externally_back_inode(inode, ctx, &excluded_dentry, true);
643 if (ret > 0) /* Error. */
646 if (ret < 0 && ret != EXTERNAL_BACKING_EXCLUDED)
647 return 0; /* Not externally backing, other than due to exclusion. */
649 if (unlikely(ret == EXTERNAL_BACKING_EXCLUDED)) {
650 /* Not externally backing due to exclusion. */
651 union wimlib_progress_info info;
653 build_extraction_path(excluded_dentry, ctx);
655 info.wimboot_exclude.path_in_wim = excluded_dentry->d_full_path;
656 info.wimboot_exclude.extraction_path = current_path(ctx);
658 return call_progress(ctx->common.progfunc,
659 WIMLIB_PROGRESS_MSG_WIMBOOT_EXCLUDE,
660 &info, ctx->common.progctx);
663 /* Externally backing. */
665 blob = inode_get_blob_for_unnamed_data_stream_resolved(inode);
666 wimboot_wim = find_wimboot_wim(blob->rdesc->wim, ctx);
668 if (unlikely(!wimboot_set_pointer(h,
670 wimboot_wim->data_source_id,
671 wimboot_wim->blob_table_hash,
672 ctx->wimboot.wof_running)))
674 const DWORD err = GetLastError();
676 build_extraction_path(inode_first_extraction_dentry(inode), ctx);
677 win32_error(err, L"\"%ls\": Couldn't set WIMBoot pointer data",
679 return WIMLIB_ERR_WIMBOOT;
684 /* Calculates the SHA-1 message digest of the WIM's blob table. */
686 hash_blob_table(WIMStruct *wim, u8 hash[SHA1_HASH_SIZE])
688 return wim_reshdr_to_hash(&wim->hdr.blob_table_reshdr, wim, hash);
692 register_wim_with_wof(WIMStruct *wim, struct win32_apply_ctx *ctx)
694 struct wimboot_wim *p;
697 /* Check if already registered */
698 for (size_t i = 0; i < ctx->wimboot.num_wims; i++)
699 if (wim == ctx->wimboot.wims[i].wim)
702 /* Not yet registered */
704 p = REALLOC(ctx->wimboot.wims,
705 (ctx->wimboot.num_wims + 1) * sizeof(ctx->wimboot.wims[0]));
707 return WIMLIB_ERR_NOMEM;
708 ctx->wimboot.wims = p;
710 ctx->wimboot.wims[ctx->wimboot.num_wims].wim = wim;
712 ret = hash_blob_table(wim, ctx->wimboot.wims[ctx->wimboot.num_wims].blob_table_hash);
716 ret = wimboot_alloc_data_source_id(wim->filename,
718 ctx->common.wim->current_image,
720 &ctx->wimboot.wims[ctx->wimboot.num_wims].data_source_id,
721 &ctx->wimboot.wof_running);
725 ctx->wimboot.num_wims++;
729 /* Prepare for doing a "WIMBoot" extraction by registering each source WIM file
730 * with WOF on the target volume. */
732 start_wimboot_extraction(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
735 struct wim_dentry *dentry;
737 if (!xml_get_wimboot(ctx->common.wim->xml_info,
738 ctx->common.wim->current_image))
739 WARNING("The WIM image is not marked as WIMBoot compatible. This usually\n"
740 " means it is not intended to be used to back a Windows operating\n"
741 " system. Proceeding anyway.");
743 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
744 struct blob_descriptor *blob;
746 ret = win32_will_back_from_wim(dentry, &ctx->common);
747 if (ret > 0) /* Error */
749 if (ret < 0) /* Won't externally back */
752 blob = inode_get_blob_for_unnamed_data_stream_resolved(dentry->d_inode);
753 ret = register_wim_with_wof(blob->rdesc->wim, ctx);
758 if (ctx->wimboot.have_wrong_version_wims) {
759 WARNING("At least one of the source WIM files uses a version of the WIM\n"
760 " file format that not supported by Microsoft's wof.sys driver.\n"
761 " Files whose data is contained in one of these WIM files will be\n"
762 " extracted as full files rather than externally backed.");
765 if (ctx->wimboot.have_uncompressed_wims) {
766 WARNING("At least one of the source WIM files is uncompressed. Files whose\n"
767 " data is contained in an uncompressed WIM file will be extracted as\n"
768 " full files rather than externally backed, since uncompressed WIM\n"
769 " files are not supported by Microsoft's wof.sys driver.");
772 if (ctx->wimboot.have_unsupported_compressed_resources) {
773 WARNING("At least one of the source WIM files uses a compression format that\n"
774 " is not supported by Microsoft's wof.sys driver. Files whose data is\n"
775 " contained in a compressed resource in one of these WIM files will be\n"
776 " extracted as full files rather than externally backed. (The\n"
777 " compression formats supported by wof.sys are: XPRESS 4K, XPRESS 8K,\n"
778 " XPRESS 16K, XPRESS 32K, and LZX 32K.)");
781 if (ctx->wimboot.have_huge_resources) {
782 WARNING("Some files exceeded 4.2 GB in size. Such files will be extracted\n"
783 " as full files rather than externally backed, since very large files\n"
784 " are not supported by Microsoft's wof.sys driver.");
791 build_win32_extraction_path(const struct wim_dentry *dentry,
792 struct win32_apply_ctx *ctx);
794 /* Sets WimBoot=1 in the extracted SYSTEM registry hive.
796 * WIMGAPI does this, and it's possible that it's important.
797 * But I don't know exactly what this value means to Windows. */
799 end_wimboot_extraction(struct win32_apply_ctx *ctx)
801 struct wim_dentry *dentry;
802 wchar_t subkeyname[32];
808 dentry = get_dentry(ctx->common.wim, L"\\Windows\\System32\\config\\SYSTEM",
809 WIMLIB_CASE_INSENSITIVE);
811 if (!dentry || !will_extract_dentry(dentry))
814 if (!will_extract_dentry(wim_get_current_root_dentry(ctx->common.wim)))
817 /* Not bothering to use the native routines (e.g. NtLoadKey()) for this.
818 * If this doesn't work, you probably also have many other problems. */
820 build_win32_extraction_path(dentry, ctx);
822 get_random_alnum_chars(subkeyname, 20);
823 subkeyname[20] = L'\0';
825 res = RegLoadKey(HKEY_LOCAL_MACHINE, subkeyname, ctx->pathbuf.Buffer);
829 wcscpy(&subkeyname[20], L"\\Setup");
831 res = RegCreateKeyEx(HKEY_LOCAL_MACHINE, subkeyname, 0, NULL,
832 REG_OPTION_BACKUP_RESTORE, 0, NULL, &key, NULL);
838 res = RegSetValueEx(key, L"WimBoot", 0, REG_DWORD,
839 (const BYTE *)&value, sizeof(DWORD));
843 res = RegFlushKey(key);
846 res2 = RegCloseKey(key);
850 subkeyname[20] = L'\0';
851 RegUnLoadKey(HKEY_LOCAL_MACHINE, subkeyname);
855 win32_warning(res, L"Failed to set \\Setup: dword \"WimBoot\"=1 "
856 "value in registry hive \"%ls\"",
857 ctx->pathbuf.Buffer);
863 /* Returns the number of wide characters needed to represent the path to the
864 * specified @dentry, relative to the target directory, when extracted.
866 * Does not include null terminator (not needed for NtCreateFile). */
868 dentry_extraction_path_length(const struct wim_dentry *dentry)
871 const struct wim_dentry *d;
875 len += d->d_extraction_name_nchars + 1;
877 } while (!dentry_is_root(d) && will_extract_dentry(d));
879 return --len; /* No leading slash */
882 /* Returns the length of the longest string that might need to be appended to
883 * the path to an alias of an inode to open or create a named data stream.
885 * If the inode has no named data streams, this will be 0. Otherwise, this will
886 * be 1 plus the length of the longest-named data stream, since the data stream
887 * name must be separated from the path by the ':' character. */
889 inode_longest_named_data_stream_spec(const struct wim_inode *inode)
892 for (unsigned i = 0; i < inode->i_num_streams; i++) {
893 const struct wim_inode_stream *strm = &inode->i_streams[i];
894 if (!stream_is_named_data_stream(strm))
896 size_t len = utf16le_len_chars(strm->stream_name);
905 /* Find the length, in wide characters, of the longest path needed for
906 * extraction of any file in @dentry_list relative to the target directory.
908 * Accounts for named data streams, but does not include null terminator (not
909 * needed for NtCreateFile). */
911 compute_path_max(struct list_head *dentry_list)
914 const struct wim_dentry *dentry;
916 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
919 len = dentry_extraction_path_length(dentry);
921 /* Account for named data streams */
922 len += inode_longest_named_data_stream_spec(dentry->d_inode);
931 /* Build the path at which to extract the @dentry, relative to the target
934 * The path is saved in ctx->pathbuf. */
936 build_extraction_path(const struct wim_dentry *dentry,
937 struct win32_apply_ctx *ctx)
941 const struct wim_dentry *d;
943 len = dentry_extraction_path_length(dentry);
945 ctx->pathbuf.Length = len * sizeof(wchar_t);
946 p = ctx->pathbuf.Buffer + len;
948 !dentry_is_root(d->d_parent) && will_extract_dentry(d->d_parent);
951 p -= d->d_extraction_name_nchars;
952 if (d->d_extraction_name_nchars)
953 wmemcpy(p, d->d_extraction_name,
954 d->d_extraction_name_nchars);
957 /* No leading slash */
958 p -= d->d_extraction_name_nchars;
959 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
962 /* Build the path at which to extract the @dentry, relative to the target
963 * directory, adding the suffix for a named data stream.
965 * The path is saved in ctx->pathbuf. */
967 build_extraction_path_with_ads(const struct wim_dentry *dentry,
968 struct win32_apply_ctx *ctx,
969 const wchar_t *stream_name,
970 size_t stream_name_nchars)
974 build_extraction_path(dentry, ctx);
976 /* Add :NAME for named data stream */
977 p = ctx->pathbuf.Buffer + (ctx->pathbuf.Length / sizeof(wchar_t));
979 wmemcpy(p, stream_name, stream_name_nchars);
980 ctx->pathbuf.Length += (1 + stream_name_nchars) * sizeof(wchar_t);
983 /* Build the Win32 namespace path to the specified @dentry when extracted.
985 * The path is saved in ctx->pathbuf and will be null terminated.
987 * XXX: We could get rid of this if it wasn't needed for the file encryption
988 * APIs, and the registry manipulation in WIMBoot mode. */
990 build_win32_extraction_path(const struct wim_dentry *dentry,
991 struct win32_apply_ctx *ctx)
993 build_extraction_path(dentry, ctx);
995 /* Prepend target_ntpath to our relative path, then change \??\ into \\?\ */
997 memmove(ctx->pathbuf.Buffer +
998 (ctx->target_ntpath.Length / sizeof(wchar_t)) + 1,
999 ctx->pathbuf.Buffer, ctx->pathbuf.Length);
1000 memcpy(ctx->pathbuf.Buffer, ctx->target_ntpath.Buffer,
1001 ctx->target_ntpath.Length);
1002 ctx->pathbuf.Buffer[ctx->target_ntpath.Length / sizeof(wchar_t)] = L'\\';
1003 ctx->pathbuf.Length += ctx->target_ntpath.Length + sizeof(wchar_t);
1004 ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)] = L'\0';
1006 wimlib_assert(ctx->pathbuf.Length >= 4 * sizeof(wchar_t) &&
1007 !wmemcmp(ctx->pathbuf.Buffer, L"\\??\\", 4));
1009 ctx->pathbuf.Buffer[1] = L'\\';
1013 /* Returns a "printable" representation of the last relative NT path that was
1014 * constructed with build_extraction_path() or build_extraction_path_with_ads().
1016 * This will be overwritten by the next call to this function. */
1017 static const wchar_t *
1018 current_path(struct win32_apply_ctx *ctx)
1020 wchar_t *p = ctx->print_buffer;
1022 p = wmempcpy(p, ctx->common.target, ctx->common.target_nchars);
1024 p = wmempcpy(p, ctx->pathbuf.Buffer, ctx->pathbuf.Length / sizeof(wchar_t));
1026 return ctx->print_buffer;
1029 /* Open handle to the target directory if it is not already open. If the target
1030 * directory does not exist, this creates it. */
1032 open_target_directory(struct win32_apply_ctx *ctx)
1039 ctx->attr.Length = sizeof(ctx->attr);
1040 ctx->attr.RootDirectory = NULL;
1041 ctx->attr.ObjectName = &ctx->target_ntpath;
1043 /* Don't use FILE_OPEN_REPARSE_POINT here; we want the extraction to
1044 * happen at the directory "pointed to" by the reparse point. */
1045 status = NtCreateFile(&ctx->h_target,
1051 FILE_SHARE_VALID_FLAGS,
1053 FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT,
1056 if (!NT_SUCCESS(status)) {
1057 winnt_error(status, L"Can't open or create directory \"%ls\"",
1058 ctx->common.target);
1059 return WIMLIB_ERR_OPENDIR;
1061 ctx->attr.RootDirectory = ctx->h_target;
1062 ctx->attr.ObjectName = &ctx->pathbuf;
1067 close_target_directory(struct win32_apply_ctx *ctx)
1069 if (ctx->h_target) {
1070 NtClose(ctx->h_target);
1071 ctx->h_target = NULL;
1072 ctx->attr.RootDirectory = NULL;
1077 * Ensures the target directory exists and opens a handle to it, in preparation
1078 * of using paths relative to it.
1081 prepare_target(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1086 ret = win32_path_to_nt_path(ctx->common.target, &ctx->target_ntpath);
1090 ret = open_target_directory(ctx);
1094 path_max = compute_path_max(dentry_list);
1095 /* Add some extra for building Win32 paths for the file encryption APIs,
1096 * and ensure we have at least enough to potentially use a 8.3 name for
1097 * the last component. */
1098 path_max += max(2 + (ctx->target_ntpath.Length / sizeof(wchar_t)),
1101 ctx->pathbuf.MaximumLength = path_max * sizeof(wchar_t);
1102 if (ctx->pathbuf.MaximumLength != path_max * sizeof(wchar_t)) {
1103 /* Paths are too long for a UNICODE_STRING! */
1104 ERROR("Some paths are too long to extract (> 32768 characters)!");
1105 return WIMLIB_ERR_UNSUPPORTED;
1108 ctx->pathbuf.Buffer = MALLOC(ctx->pathbuf.MaximumLength);
1109 if (!ctx->pathbuf.Buffer)
1110 return WIMLIB_ERR_NOMEM;
1112 ctx->print_buffer = MALLOC((ctx->common.target_nchars + 1 + path_max + 1) *
1114 if (!ctx->print_buffer)
1115 return WIMLIB_ERR_NOMEM;
1120 /* When creating an inode that will have a short (DOS) name, we create it using
1121 * the long name associated with the short name. This ensures that the short
1122 * name gets associated with the correct long name. */
1123 static struct wim_dentry *
1124 first_extraction_alias(const struct wim_inode *inode)
1126 struct wim_dentry *dentry;
1128 inode_for_each_extraction_alias(dentry, inode)
1129 if (dentry_has_short_name(dentry))
1131 return inode_first_extraction_dentry(inode);
1135 * Set or clear FILE_ATTRIBUTE_COMPRESSED if the inherited value is different
1136 * from the desired value.
1138 * Note that you can NOT override the inherited value of
1139 * FILE_ATTRIBUTE_COMPRESSED directly with NtCreateFile().
1142 adjust_compression_attribute(HANDLE h, const struct wim_dentry *dentry,
1143 struct win32_apply_ctx *ctx)
1145 const bool compressed = (dentry->d_inode->i_attributes &
1146 FILE_ATTRIBUTE_COMPRESSED);
1147 FILE_BASIC_INFORMATION info;
1148 USHORT compression_state;
1151 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
1154 if (!ctx->common.supported_features.compressed_files)
1158 /* Get current attributes */
1159 status = NtQueryInformationFile(h, &ctx->iosb, &info, sizeof(info),
1160 FileBasicInformation);
1161 if (NT_SUCCESS(status) &&
1162 compressed == !!(info.FileAttributes & FILE_ATTRIBUTE_COMPRESSED))
1164 /* Nothing needs to be done. */
1168 /* Set the new compression state */
1171 compression_state = COMPRESSION_FORMAT_DEFAULT;
1173 compression_state = COMPRESSION_FORMAT_NONE;
1175 status = winnt_fsctl(h, FSCTL_SET_COMPRESSION,
1176 &compression_state, sizeof(USHORT), NULL, 0, NULL);
1177 if (NT_SUCCESS(status))
1180 winnt_error(status, L"Can't %s compression attribute on \"%ls\"",
1181 (compressed ? "set" : "clear"), current_path(ctx));
1182 return WIMLIB_ERR_SET_ATTRIBUTES;
1186 need_sparse_flag(const struct wim_inode *inode,
1187 const struct win32_apply_ctx *ctx)
1189 return (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) &&
1190 ctx->common.supported_features.sparse_files;
1194 set_sparse_flag(HANDLE h, struct win32_apply_ctx *ctx)
1198 status = winnt_fsctl(h, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, NULL);
1199 if (NT_SUCCESS(status))
1202 winnt_error(status, L"Can't set sparse flag on \"%ls\"",
1204 return WIMLIB_ERR_SET_ATTRIBUTES;
1207 /* Try to enable short name support on the target volume. If successful, return
1208 * true. If unsuccessful, issue a warning and return false. */
1210 try_to_enable_short_names(const wchar_t *volume)
1213 FILE_FS_PERSISTENT_VOLUME_INFORMATION info;
1215 DWORD bytesReturned;
1217 h = CreateFile(volume, GENERIC_WRITE,
1218 FILE_SHARE_VALID_FLAGS, NULL, OPEN_EXISTING,
1219 FILE_FLAG_BACKUP_SEMANTICS, NULL);
1220 if (h == INVALID_HANDLE_VALUE)
1223 info.VolumeFlags = 0;
1224 info.FlagMask = PERSISTENT_VOLUME_STATE_SHORT_NAME_CREATION_DISABLED;
1228 bret = DeviceIoControl(h, FSCTL_SET_PERSISTENT_VOLUME_STATE,
1229 &info, sizeof(info), NULL, 0,
1230 &bytesReturned, NULL);
1239 win32_warning(GetLastError(),
1240 L"Failed to enable short name support on %ls",
1246 remove_conflicting_short_name(const struct wim_dentry *dentry, struct win32_apply_ctx *ctx)
1252 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1253 (13 * sizeof(wchar_t));
1254 u8 buf[bufsize] _aligned_attribute(8);
1255 bool retried = false;
1256 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1258 memset(buf, 0, bufsize);
1260 /* Build the path with the short name. */
1261 name = &ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)];
1262 while (name != ctx->pathbuf.Buffer && *(name - 1) != L'\\')
1264 end = mempcpy(name, dentry->d_short_name, dentry->d_short_name_nbytes);
1265 ctx->pathbuf.Length = ((u8 *)end - (u8 *)ctx->pathbuf.Buffer);
1267 /* Open the conflicting file (by short name). */
1268 status = NtOpenFile(&h, GENERIC_WRITE | DELETE,
1269 &ctx->attr, &ctx->iosb,
1270 FILE_SHARE_VALID_FLAGS,
1271 FILE_OPEN_REPARSE_POINT | FILE_OPEN_FOR_BACKUP_INTENT);
1272 if (!NT_SUCCESS(status)) {
1273 winnt_warning(status, L"Can't open \"%ls\"", current_path(ctx));
1278 WARNING("Overriding conflicting short name; path=\"%ls\"",
1282 /* Try to remove the short name on the conflicting file. */
1285 status = NtSetInformationFile(h, &ctx->iosb, info, bufsize,
1286 FileShortNameInformation);
1288 if (status == STATUS_INVALID_PARAMETER && !retried) {
1289 /* Microsoft forgot to make it possible to remove short names
1290 * until Windows 7. Oops. Use a random short name instead. */
1291 get_random_alnum_chars(info->FileName, 8);
1292 wcscpy(&info->FileName[8], L".WLB");
1293 info->FileNameLength = 12 * sizeof(wchar_t);
1299 build_extraction_path(dentry, ctx);
1303 /* Set the short name on the open file @h which has been created at the location
1304 * indicated by @dentry.
1306 * Note that this may add, change, or remove the short name.
1308 * @h must be opened with DELETE access.
1310 * Returns 0 or WIMLIB_ERR_SET_SHORT_NAME. The latter only happens in
1311 * STRICT_SHORT_NAMES mode.
1314 set_short_name(HANDLE h, const struct wim_dentry *dentry,
1315 struct win32_apply_ctx *ctx)
1318 if (!ctx->common.supported_features.short_names)
1322 * Note: The size of the FILE_NAME_INFORMATION buffer must be such that
1323 * FileName contains at least 2 wide characters (4 bytes). Otherwise,
1324 * NtSetInformationFile() will return STATUS_INFO_LENGTH_MISMATCH. This
1325 * is despite the fact that FileNameLength can validly be 0 or 2 bytes,
1326 * with the former case being removing the existing short name if
1327 * present, rather than setting one.
1329 * The null terminator is seemingly optional, but to be safe we include
1330 * space for it and zero all unused space.
1333 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1334 max(dentry->d_short_name_nbytes, sizeof(wchar_t)) +
1336 u8 buf[bufsize] _aligned_attribute(8);
1337 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1339 bool tried_to_remove_existing = false;
1341 memset(buf, 0, bufsize);
1343 info->FileNameLength = dentry->d_short_name_nbytes;
1344 memcpy(info->FileName, dentry->d_short_name, dentry->d_short_name_nbytes);
1347 status = NtSetInformationFile(h, &ctx->iosb, info, bufsize,
1348 FileShortNameInformation);
1349 if (NT_SUCCESS(status))
1352 if (status == STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME) {
1353 if (dentry->d_short_name_nbytes == 0)
1355 if (!ctx->tried_to_enable_short_names) {
1359 ctx->tried_to_enable_short_names = true;
1361 ret = win32_get_drive_path(ctx->common.target,
1365 if (try_to_enable_short_names(volume))
1371 * Short names can conflict in several cases:
1373 * - a file being extracted has a short name conflicting with an
1376 * - a file being extracted has a short name conflicting with another
1377 * file being extracted (possible, but shouldn't happen)
1379 * - a file being extracted has a short name that conflicts with the
1380 * automatically generated short name of a file we previously
1381 * extracted, but failed to set the short name for. Sounds unlikely,
1382 * but this actually does happen fairly often on versions of Windows
1383 * prior to Windows 7 because they do not support removing short names
1386 if (unlikely(status == STATUS_OBJECT_NAME_COLLISION) &&
1387 dentry->d_short_name_nbytes && !tried_to_remove_existing)
1389 tried_to_remove_existing = true;
1390 status = remove_conflicting_short_name(dentry, ctx);
1391 if (NT_SUCCESS(status))
1395 /* By default, failure to set short names is not an error (since short
1396 * names aren't too important anymore...). */
1397 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES)) {
1398 if (dentry->d_short_name_nbytes)
1399 ctx->num_set_short_name_failures++;
1401 ctx->num_remove_short_name_failures++;
1405 winnt_error(status, L"Can't set short name on \"%ls\"", current_path(ctx));
1406 return WIMLIB_ERR_SET_SHORT_NAME;
1410 * A wrapper around NtCreateFile() to make it slightly more usable...
1411 * This uses the path currently constructed in ctx->pathbuf.
1413 * Also, we always specify SYNCHRONIZE access, FILE_OPEN_FOR_BACKUP_INTENT, and
1414 * FILE_OPEN_REPARSE_POINT.
1417 do_create_file(PHANDLE FileHandle,
1418 ACCESS_MASK DesiredAccess,
1419 PLARGE_INTEGER AllocationSize,
1420 ULONG FileAttributes,
1421 ULONG CreateDisposition,
1422 ULONG CreateOptions,
1423 struct win32_apply_ctx *ctx)
1425 return NtCreateFile(FileHandle,
1426 DesiredAccess | SYNCHRONIZE,
1431 FILE_SHARE_VALID_FLAGS,
1434 FILE_OPEN_FOR_BACKUP_INTENT |
1435 FILE_OPEN_REPARSE_POINT,
1440 /* Like do_create_file(), but builds the extraction path of the @dentry first.
1443 create_file(PHANDLE FileHandle,
1444 ACCESS_MASK DesiredAccess,
1445 PLARGE_INTEGER AllocationSize,
1446 ULONG FileAttributes,
1447 ULONG CreateDisposition,
1448 ULONG CreateOptions,
1449 const struct wim_dentry *dentry,
1450 struct win32_apply_ctx *ctx)
1452 build_extraction_path(dentry, ctx);
1453 return do_create_file(FileHandle,
1463 delete_file_or_stream(struct win32_apply_ctx *ctx)
1467 ULONG perms = DELETE;
1468 ULONG flags = FILE_NON_DIRECTORY_FILE | FILE_DELETE_ON_CLOSE;
1470 /* First try opening the file with FILE_DELETE_ON_CLOSE. In most cases,
1471 * all we have to do is that plus close the file handle. */
1473 status = do_create_file(&h, perms, NULL, 0, FILE_OPEN, flags, ctx);
1475 if (unlikely(status == STATUS_CANNOT_DELETE)) {
1476 /* This error occurs for files with FILE_ATTRIBUTE_READONLY set.
1477 * Try an alternate approach: first open the file without
1478 * FILE_DELETE_ON_CLOSE, then reset the file attributes, then
1479 * set the "delete" disposition on the handle. */
1480 if (flags & FILE_DELETE_ON_CLOSE) {
1481 flags &= ~FILE_DELETE_ON_CLOSE;
1482 perms |= FILE_WRITE_ATTRIBUTES;
1487 if (unlikely(!NT_SUCCESS(status))) {
1488 winnt_error(status, L"Can't open \"%ls\" for deletion "
1489 "(perms=%x, flags=%x)",
1490 current_path(ctx), perms, flags);
1491 return WIMLIB_ERR_OPEN;
1494 if (unlikely(!(flags & FILE_DELETE_ON_CLOSE))) {
1496 FILE_BASIC_INFORMATION basic_info =
1497 { .FileAttributes = FILE_ATTRIBUTE_NORMAL };
1498 status = NtSetInformationFile(h, &ctx->iosb, &basic_info,
1500 FileBasicInformation);
1502 if (!NT_SUCCESS(status)) {
1503 winnt_error(status, L"Can't reset attributes of \"%ls\" "
1504 "to prepare for deletion", current_path(ctx));
1506 return WIMLIB_ERR_SET_ATTRIBUTES;
1509 FILE_DISPOSITION_INFORMATION disp_info =
1510 { .DoDeleteFile = TRUE };
1511 status = NtSetInformationFile(h, &ctx->iosb, &disp_info,
1513 FileDispositionInformation);
1514 if (!NT_SUCCESS(status)) {
1515 winnt_error(status, L"Can't set delete-on-close "
1516 "disposition on \"%ls\"", current_path(ctx));
1518 return WIMLIB_ERR_SET_ATTRIBUTES;
1522 status = NtClose(h);
1523 if (unlikely(!NT_SUCCESS(status))) {
1524 winnt_error(status, L"Error closing \"%ls\" after setting "
1525 "delete-on-close disposition", current_path(ctx));
1526 return WIMLIB_ERR_OPEN;
1533 * Create a nondirectory file or named data stream at the current path,
1534 * superseding any that already exists at that path. If successful, return an
1535 * open handle to the file or named data stream with the requested permissions.
1538 supersede_file_or_stream(struct win32_apply_ctx *ctx, DWORD perms,
1542 bool retried = false;
1544 /* FILE_ATTRIBUTE_SYSTEM is needed to ensure that
1545 * FILE_ATTRIBUTE_ENCRYPTED doesn't get set before we want it to be. */
1547 status = do_create_file(h_ret,
1550 FILE_ATTRIBUTE_SYSTEM,
1552 FILE_NON_DIRECTORY_FILE,
1554 if (likely(NT_SUCCESS(status)))
1557 /* STATUS_OBJECT_NAME_COLLISION means that the file or stream already
1558 * exists. Delete the existing file or stream, then try again.
1560 * Note: we don't use FILE_OVERWRITE_IF or FILE_SUPERSEDE because of
1561 * problems with certain file attributes, especially
1562 * FILE_ATTRIBUTE_ENCRYPTED. FILE_SUPERSEDE is also broken in the
1563 * Windows PE ramdisk. */
1564 if (status == STATUS_OBJECT_NAME_COLLISION && !retried) {
1565 int ret = delete_file_or_stream(ctx);
1571 winnt_error(status, L"Can't create \"%ls\"", current_path(ctx));
1572 return WIMLIB_ERR_OPEN;
1575 /* Set the reparse point @rpbuf of length @rpbuflen on the extracted file
1576 * corresponding to the WIM dentry @dentry. */
1578 do_set_reparse_point(const struct wim_dentry *dentry,
1579 const struct reparse_buffer_disk *rpbuf, u16 rpbuflen,
1580 struct win32_apply_ctx *ctx)
1585 status = create_file(&h, GENERIC_WRITE, NULL,
1586 0, FILE_OPEN, 0, dentry, ctx);
1587 if (!NT_SUCCESS(status))
1590 status = winnt_fsctl(h, FSCTL_SET_REPARSE_POINT,
1591 rpbuf, rpbuflen, NULL, 0, NULL);
1594 if (NT_SUCCESS(status))
1597 /* On Windows, by default only the Administrator can create symbolic
1598 * links for some reason. By default we just issue a warning if this
1599 * appears to be the problem. Use WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS
1600 * to get a hard error. */
1601 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS)
1602 && (status == STATUS_PRIVILEGE_NOT_HELD ||
1603 status == STATUS_ACCESS_DENIED)
1604 && (dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1605 dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1607 WARNING("Can't create symbolic link \"%ls\"! \n"
1608 " (Need Administrator rights, or at least "
1610 " SeCreateSymbolicLink privilege.)",
1616 winnt_error(status, L"Can't set reparse data on \"%ls\"",
1618 return WIMLIB_ERR_SET_REPARSE_DATA;
1622 * Create empty named data streams and potentially a reparse point for the
1623 * specified file, if any.
1625 * Since these won't have blob descriptors, they won't show up in the call to
1626 * extract_blob_list(). Hence the need for the special case.
1629 create_empty_streams(const struct wim_dentry *dentry,
1630 struct win32_apply_ctx *ctx)
1632 const struct wim_inode *inode = dentry->d_inode;
1635 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1636 const struct wim_inode_stream *strm = &inode->i_streams[i];
1638 if (stream_blob_resolved(strm) != NULL)
1641 if (strm->stream_type == STREAM_TYPE_REPARSE_POINT &&
1642 ctx->common.supported_features.reparse_points)
1644 u8 buf[REPARSE_DATA_OFFSET] _aligned_attribute(8);
1645 struct reparse_buffer_disk *rpbuf =
1646 (struct reparse_buffer_disk *)buf;
1647 complete_reparse_point(rpbuf, inode, 0);
1648 ret = do_set_reparse_point(dentry, rpbuf,
1649 REPARSE_DATA_OFFSET, ctx);
1652 } else if (stream_is_named_data_stream(strm) &&
1653 ctx->common.supported_features.named_data_streams)
1657 build_extraction_path_with_ads(dentry, ctx,
1659 utf16le_len_chars(strm->stream_name));
1661 * Note: do not request any permissions on the handle.
1662 * Otherwise, we may encounter a Windows bug where the
1663 * parent directory DACL denies read access to the new
1664 * named data stream, even when using backup semantics!
1666 ret = supersede_file_or_stream(ctx, 0, &h);
1668 build_extraction_path(dentry, ctx);
1680 * Creates the directory named by @dentry, or uses an existing directory at that
1681 * location. If necessary, sets the short name and/or fixes compression and
1682 * encryption attributes.
1684 * Returns 0, WIMLIB_ERR_MKDIR, or WIMLIB_ERR_SET_SHORT_NAME.
1687 create_directory(const struct wim_dentry *dentry, struct win32_apply_ctx *ctx)
1694 /* DELETE is needed for set_short_name(); GENERIC_READ and GENERIC_WRITE
1695 * are needed for adjust_compression_attribute(). */
1696 perms = GENERIC_READ | GENERIC_WRITE;
1697 if (!dentry_is_root(dentry))
1700 /* FILE_ATTRIBUTE_SYSTEM is needed to ensure that
1701 * FILE_ATTRIBUTE_ENCRYPTED doesn't get set before we want it to be. */
1702 status = create_file(&h, perms, NULL, FILE_ATTRIBUTE_SYSTEM,
1703 FILE_OPEN_IF, FILE_DIRECTORY_FILE, dentry, ctx);
1704 if (unlikely(!NT_SUCCESS(status))) {
1705 const wchar_t *path = current_path(ctx);
1706 winnt_error(status, L"Can't create directory \"%ls\"", path);
1708 /* Check for known issue with WindowsApps directory. */
1709 if (status == STATUS_ACCESS_DENIED &&
1710 (wcsstr(path, L"\\WindowsApps\\") ||
1711 wcsstr(path, L"\\InfusedApps\\"))) {
1713 "You seem to be trying to extract files to the WindowsApps directory.\n"
1714 " Windows 8.1 and later use new file permissions in this directory that\n"
1715 " cannot be overridden, even by backup/restore programs. To extract your\n"
1716 " files anyway, you need to choose a different target directory, delete\n"
1717 " the WindowsApps directory entirely, reformat the volume, do the\n"
1718 " extraction from a non-broken operating system such as Windows 7 or\n"
1719 " Linux, or wait for Microsoft to fix the design flaw in their operating\n"
1720 " system. This is *not* a bug in wimlib. See this thread for more\n"
1721 " information: https://wimlib.net/forums/viewtopic.php?f=1&t=261");
1723 return WIMLIB_ERR_MKDIR;
1726 if (ctx->iosb.Information == FILE_OPENED) {
1727 /* If we opened an existing directory, try to clear its file
1728 * attributes. As far as I know, this only actually makes a
1729 * difference in the case where a FILE_ATTRIBUTE_READONLY
1730 * directory has a named data stream which needs to be
1731 * extracted. You cannot create a named data stream of such a
1732 * directory, even though this contradicts Microsoft's
1733 * documentation for FILE_ATTRIBUTE_READONLY which states it is
1734 * not honored for directories! */
1735 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)) {
1736 FILE_BASIC_INFORMATION basic_info =
1737 { .FileAttributes = FILE_ATTRIBUTE_NORMAL };
1738 NtSetInformationFile(h, &ctx->iosb, &basic_info,
1740 FileBasicInformation);
1744 if (!dentry_is_root(dentry)) {
1745 ret = set_short_name(h, dentry, ctx);
1750 ret = adjust_compression_attribute(h, dentry, ctx);
1757 * Create all the directories being extracted, other than the target directory
1760 * Note: we don't honor directory hard links. However, we don't allow them to
1761 * exist in WIM images anyway (see inode_fixup.c).
1764 create_directories(struct list_head *dentry_list,
1765 struct win32_apply_ctx *ctx)
1767 const struct wim_dentry *dentry;
1770 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1772 if (!(dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY))
1775 /* Note: Here we include files with
1776 * FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT, but we
1777 * wait until later to actually set the reparse data. */
1779 ret = create_directory(dentry, ctx);
1782 ret = create_empty_streams(dentry, ctx);
1784 ret = check_apply_error(dentry, ctx, ret);
1788 ret = report_file_created(&ctx->common);
1796 * Creates the nondirectory file named by @dentry.
1798 * On success, returns an open handle to the file in @h_ret, with GENERIC_READ,
1799 * GENERIC_WRITE, and DELETE access. Also, the path to the file will be saved
1800 * in ctx->pathbuf. On failure, returns an error code.
1803 create_nondirectory_inode(HANDLE *h_ret, const struct wim_dentry *dentry,
1804 struct win32_apply_ctx *ctx)
1809 build_extraction_path(dentry, ctx);
1811 ret = supersede_file_or_stream(ctx,
1812 GENERIC_READ | GENERIC_WRITE | DELETE,
1817 ret = adjust_compression_attribute(h, dentry, ctx);
1821 if (need_sparse_flag(dentry->d_inode, ctx)) {
1822 ret = set_sparse_flag(h, ctx);
1827 ret = create_empty_streams(dentry, ctx);
1840 /* Creates a hard link at the location named by @dentry to the file represented
1841 * by the open handle @h. Or, if the target volume does not support hard links,
1842 * create a separate file instead. */
1844 create_link(HANDLE h, const struct wim_dentry *dentry,
1845 struct win32_apply_ctx *ctx)
1847 if (ctx->common.supported_features.hard_links) {
1849 build_extraction_path(dentry, ctx);
1851 size_t bufsize = offsetof(FILE_LINK_INFORMATION, FileName) +
1852 ctx->pathbuf.Length + sizeof(wchar_t);
1853 u8 buf[bufsize] _aligned_attribute(8);
1854 FILE_LINK_INFORMATION *info = (FILE_LINK_INFORMATION *)buf;
1857 info->ReplaceIfExists = TRUE;
1858 info->RootDirectory = ctx->attr.RootDirectory;
1859 info->FileNameLength = ctx->pathbuf.Length;
1860 memcpy(info->FileName, ctx->pathbuf.Buffer, ctx->pathbuf.Length);
1861 info->FileName[info->FileNameLength / 2] = L'\0';
1863 /* Note: the null terminator isn't actually necessary,
1864 * but if you don't add the extra character, you get
1865 * STATUS_INFO_LENGTH_MISMATCH when FileNameLength
1866 * happens to be 2 */
1868 status = NtSetInformationFile(h, &ctx->iosb, info, bufsize,
1869 FileLinkInformation);
1870 if (NT_SUCCESS(status))
1872 winnt_error(status, L"Failed to create link \"%ls\"",
1874 return WIMLIB_ERR_LINK;
1879 ret = create_nondirectory_inode(&h2, dentry, ctx);
1888 /* Given an inode (represented by the open handle @h) for which one link has
1889 * been created (named by @first_dentry), create the other links.
1891 * Or, if the target volume does not support hard links, create separate files.
1893 * Note: This uses ctx->pathbuf and does not reset it.
1896 create_links(HANDLE h, const struct wim_dentry *first_dentry,
1897 struct win32_apply_ctx *ctx)
1899 const struct wim_inode *inode = first_dentry->d_inode;
1900 const struct wim_dentry *dentry;
1903 inode_for_each_extraction_alias(dentry, inode) {
1904 if (dentry != first_dentry) {
1905 ret = create_link(h, dentry, ctx);
1913 /* Create a nondirectory file, including all links. */
1915 create_nondirectory(struct wim_inode *inode, struct win32_apply_ctx *ctx)
1917 struct wim_dentry *first_dentry;
1921 first_dentry = first_extraction_alias(inode);
1923 /* Create first link. */
1924 ret = create_nondirectory_inode(&h, first_dentry, ctx);
1928 /* Set short name. */
1929 ret = set_short_name(h, first_dentry, ctx);
1931 /* Create additional links, OR if hard links are not supported just
1932 * create more files. */
1934 ret = create_links(h, first_dentry, ctx);
1936 /* "WIMBoot" extraction: set external backing by the WIM file if needed. */
1937 if (!ret && unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
1938 ret = set_backed_from_wim(h, inode, ctx);
1944 /* Create all the nondirectory files being extracted, including all aliases
1947 create_nondirectories(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1949 struct wim_dentry *dentry;
1950 struct wim_inode *inode;
1953 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1954 inode = dentry->d_inode;
1955 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1957 /* Call create_nondirectory() only once per inode */
1958 if (dentry == inode_first_extraction_dentry(inode)) {
1959 ret = create_nondirectory(inode, ctx);
1960 ret = check_apply_error(dentry, ctx, ret);
1964 ret = report_file_created(&ctx->common);
1972 close_handles(struct win32_apply_ctx *ctx)
1974 for (unsigned i = 0; i < ctx->num_open_handles; i++)
1975 NtClose(ctx->open_handles[i]);
1978 /* Prepare to read the next blob, which has size @blob_size, into an in-memory
1981 prepare_data_buffer(struct win32_apply_ctx *ctx, u64 blob_size)
1983 if (blob_size > ctx->data_buffer_size) {
1984 /* Larger buffer needed. */
1986 if ((size_t)blob_size != blob_size)
1988 new_buffer = REALLOC(ctx->data_buffer, blob_size);
1991 ctx->data_buffer = new_buffer;
1992 ctx->data_buffer_size = blob_size;
1994 /* On the first call this changes data_buffer_ptr from NULL, which tells
1995 * extract_chunk() that the data buffer needs to be filled while reading
1996 * the stream data. */
1997 ctx->data_buffer_ptr = ctx->data_buffer;
2002 begin_extract_blob_instance(const struct blob_descriptor *blob,
2003 struct wim_dentry *dentry,
2004 const struct wim_inode_stream *strm,
2005 struct win32_apply_ctx *ctx)
2010 if (unlikely(strm->stream_type == STREAM_TYPE_REPARSE_POINT)) {
2011 /* We can't write the reparse point stream directly; we must set
2012 * it with FSCTL_SET_REPARSE_POINT, which requires that all the
2013 * data be available. So, stage the data in a buffer. */
2014 if (!prepare_data_buffer(ctx, blob->size))
2015 return WIMLIB_ERR_NOMEM;
2016 list_add_tail(&dentry->d_tmp_list, &ctx->reparse_dentries);
2020 if (unlikely(strm->stream_type == STREAM_TYPE_EFSRPC_RAW_DATA)) {
2021 /* We can't write encrypted files directly; we must use
2022 * WriteEncryptedFileRaw(), which requires providing the data
2023 * through a callback function. This can't easily be combined
2024 * with our own callback-based approach.
2026 * The current workaround is to simply read the blob into memory
2027 * and write the encrypted file from that.
2029 * TODO: This isn't sufficient for extremely large encrypted
2030 * files. Perhaps we should create an extra thread to write
2032 if (!prepare_data_buffer(ctx, blob->size))
2033 return WIMLIB_ERR_NOMEM;
2034 list_add_tail(&dentry->d_tmp_list, &ctx->encrypted_dentries);
2038 /* It's a data stream (may be unnamed or named). */
2039 wimlib_assert(strm->stream_type == STREAM_TYPE_DATA);
2041 if (ctx->num_open_handles == MAX_OPEN_FILES) {
2042 /* XXX: Fix this. But because of the checks in
2043 * extract_blob_list(), this can now only happen on a filesystem
2044 * that does not support hard links. */
2045 ERROR("Can't extract data: too many open files!");
2046 return WIMLIB_ERR_UNSUPPORTED;
2050 if (unlikely(stream_is_named(strm))) {
2051 build_extraction_path_with_ads(dentry, ctx,
2053 utf16le_len_chars(strm->stream_name));
2055 build_extraction_path(dentry, ctx);
2059 /* Open a new handle */
2060 status = do_create_file(&h,
2061 FILE_WRITE_DATA | SYNCHRONIZE,
2062 NULL, 0, FILE_OPEN_IF,
2063 FILE_SEQUENTIAL_ONLY |
2064 FILE_SYNCHRONOUS_IO_NONALERT,
2066 if (!NT_SUCCESS(status)) {
2067 winnt_error(status, L"Can't open \"%ls\" for writing",
2069 return WIMLIB_ERR_OPEN;
2072 ctx->is_sparse_stream[ctx->num_open_handles] = false;
2073 if (need_sparse_flag(dentry->d_inode, ctx)) {
2074 /* If the stream is unnamed, then the sparse flag was already
2075 * set when the file was created. But if the stream is named,
2076 * then we need to set the sparse flag here. */
2077 if (unlikely(stream_is_named(strm))) {
2078 int ret = set_sparse_flag(h, ctx);
2084 ctx->is_sparse_stream[ctx->num_open_handles] = true;
2085 ctx->any_sparse_streams = true;
2087 /* Allocate space for the data. */
2088 FILE_ALLOCATION_INFORMATION info =
2089 { .AllocationSize = { .QuadPart = blob->size }};
2090 NtSetInformationFile(h, &ctx->iosb, &info, sizeof(info),
2091 FileAllocationInformation);
2093 ctx->open_handles[ctx->num_open_handles++] = h;
2097 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
2098 * pointer to the suffix of the path that begins with the device directly, such
2099 * as e:\Windows\System32. */
2100 static const wchar_t *
2101 skip_nt_toplevel_component(const wchar_t *path, size_t path_nchars)
2103 static const wchar_t * const dirs[] = {
2108 const wchar_t * const end = path + path_nchars;
2110 for (size_t i = 0; i < ARRAY_LEN(dirs); i++) {
2111 size_t len = wcslen(dirs[i]);
2112 if (len <= (end - path) && !wmemcmp(path, dirs[i], len)) {
2114 while (path != end && *path == L'\\')
2123 * Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
2124 * pointer to the suffix of the path that is device-relative but possibly with
2125 * leading slashes, such as \Windows\System32.
2127 * The path has an explicit length and is not necessarily null terminated.
2129 static const wchar_t *
2130 get_device_relative_path(const wchar_t *path, size_t path_nchars)
2132 const wchar_t * const orig_path = path;
2133 const wchar_t * const end = path + path_nchars;
2135 path = skip_nt_toplevel_component(path, path_nchars);
2136 if (path == orig_path)
2139 while (path != end && *path != L'\\')
2146 * Given a reparse point buffer for an inode for which the absolute link target
2147 * was relativized when it was archived, de-relative the link target to be
2148 * consistent with the actual extraction location.
2151 try_rpfix(struct reparse_buffer_disk *rpbuf, u16 *rpbuflen_p,
2152 struct win32_apply_ctx *ctx)
2154 struct link_reparse_point link;
2155 size_t orig_subst_name_nchars;
2156 const wchar_t *relpath;
2157 size_t relpath_nchars;
2158 size_t target_ntpath_nchars;
2159 size_t fixed_subst_name_nchars;
2160 const wchar_t *fixed_print_name;
2161 size_t fixed_print_name_nchars;
2163 /* Do nothing if the reparse data is invalid. */
2164 if (parse_link_reparse_point(rpbuf, *rpbuflen_p, &link))
2167 /* Do nothing if the reparse point is a relative symbolic link. */
2168 if (link_is_relative_symlink(&link))
2171 /* Build the new substitute name from the NT namespace path to the
2172 * target directory, then a path separator, then the "device relative"
2173 * part of the old substitute name. */
2175 orig_subst_name_nchars = link.substitute_name_nbytes / sizeof(wchar_t);
2177 relpath = get_device_relative_path(link.substitute_name,
2178 orig_subst_name_nchars);
2179 relpath_nchars = orig_subst_name_nchars -
2180 (relpath - link.substitute_name);
2182 target_ntpath_nchars = ctx->target_ntpath.Length / sizeof(wchar_t);
2184 /* If the target directory is a filesystem root, such as \??\C:\, then
2185 * it already will have a trailing slash. Don't include this slash if
2186 * we are already adding slashes via 'relpath'. This prevents an extra
2187 * slash from being generated each time the link is extracted. And
2188 * unlike on UNIX, the number of slashes in paths on Windows can be
2189 * significant; Windows won't understand the link target if it contains
2190 * too many slashes. */
2191 if (target_ntpath_nchars > 0 && relpath_nchars > 0 &&
2192 ctx->target_ntpath.Buffer[target_ntpath_nchars - 1] == L'\\')
2193 target_ntpath_nchars--;
2195 /* Also remove extra slashes from the beginning of 'relpath'. Normally
2196 * this isn't needed, but this is here to make the extra slash(es) added
2197 * by wimlib pre-v1.9.1 get removed automatically. */
2198 while (relpath_nchars >= 2 &&
2199 relpath[0] == L'\\' && relpath[1] == L'\\') {
2204 fixed_subst_name_nchars = target_ntpath_nchars + relpath_nchars;
2206 wchar_t fixed_subst_name[fixed_subst_name_nchars];
2208 wmemcpy(fixed_subst_name, ctx->target_ntpath.Buffer, target_ntpath_nchars);
2209 wmemcpy(&fixed_subst_name[target_ntpath_nchars], relpath, relpath_nchars);
2210 /* Doesn't need to be null-terminated. */
2212 /* Print name should be Win32, but not all NT names can even be
2213 * translated to Win32 names. But we can at least delete the top-level
2214 * directory, such as \??\, and this will have the expected result in
2215 * the usual case. */
2216 fixed_print_name = skip_nt_toplevel_component(fixed_subst_name,
2217 fixed_subst_name_nchars);
2218 fixed_print_name_nchars = fixed_subst_name_nchars - (fixed_print_name -
2221 link.substitute_name = fixed_subst_name;
2222 link.substitute_name_nbytes = fixed_subst_name_nchars * sizeof(wchar_t);
2223 link.print_name = (wchar_t *)fixed_print_name;
2224 link.print_name_nbytes = fixed_print_name_nchars * sizeof(wchar_t);
2225 make_link_reparse_point(&link, rpbuf, rpbuflen_p);
2228 /* Sets the reparse point on the specified file. This handles "fixing" the
2229 * targets of absolute symbolic links and junctions if WIMLIB_EXTRACT_FLAG_RPFIX
2232 set_reparse_point(const struct wim_dentry *dentry,
2233 const struct reparse_buffer_disk *rpbuf, u16 rpbuflen,
2234 struct win32_apply_ctx *ctx)
2236 if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
2237 && !(dentry->d_inode->i_rp_flags & WIM_RP_FLAG_NOT_FIXED))
2239 memcpy(&ctx->rpfixbuf, rpbuf, rpbuflen);
2240 try_rpfix(&ctx->rpfixbuf, &rpbuflen, ctx);
2241 rpbuf = &ctx->rpfixbuf;
2243 return do_set_reparse_point(dentry, rpbuf, rpbuflen, ctx);
2247 /* Import the next block of raw encrypted data */
2249 import_encrypted_data(PBYTE pbData, PVOID pvCallbackContext, PULONG Length)
2251 struct win32_apply_ctx *ctx = pvCallbackContext;
2254 copy_len = min(ctx->encrypted_size - ctx->encrypted_offset, *Length);
2255 memcpy(pbData, &ctx->data_buffer[ctx->encrypted_offset], copy_len);
2256 ctx->encrypted_offset += copy_len;
2258 return ERROR_SUCCESS;
2262 * Write the raw encrypted data to the already-created file (or directory)
2263 * corresponding to @dentry.
2265 * The raw encrypted data is provided in ctx->data_buffer, and its size is
2266 * ctx->encrypted_size.
2268 * This function may close the target directory, in which case the caller needs
2269 * to re-open it if needed.
2272 extract_encrypted_file(const struct wim_dentry *dentry,
2273 struct win32_apply_ctx *ctx)
2280 /* Temporarily build a Win32 path for OpenEncryptedFileRaw() */
2281 build_win32_extraction_path(dentry, ctx);
2283 flags = CREATE_FOR_IMPORT | OVERWRITE_HIDDEN;
2284 if (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
2285 flags |= CREATE_FOR_DIR;
2289 err = OpenEncryptedFileRaw(ctx->pathbuf.Buffer, flags, &rawctx);
2290 if (err == ERROR_SHARING_VIOLATION && !retried) {
2291 /* This can be caused by the handle we have open to the target
2292 * directory. Try closing it temporarily. */
2293 close_target_directory(ctx);
2298 /* Restore the NT namespace path */
2299 build_extraction_path(dentry, ctx);
2301 if (err != ERROR_SUCCESS) {
2302 win32_error(err, L"Can't open \"%ls\" for encrypted import",
2304 return WIMLIB_ERR_OPEN;
2307 ctx->encrypted_offset = 0;
2309 err = WriteEncryptedFileRaw(import_encrypted_data, ctx, rawctx);
2311 CloseEncryptedFileRaw(rawctx);
2313 if (err != ERROR_SUCCESS) {
2314 win32_error(err, L"Can't import encrypted file \"%ls\"",
2316 return WIMLIB_ERR_WRITE;
2322 /* Called when starting to read a blob for extraction */
2324 win32_begin_extract_blob(struct blob_descriptor *blob, void *_ctx)
2326 struct win32_apply_ctx *ctx = _ctx;
2327 const struct blob_extraction_target *targets = blob_extraction_targets(blob);
2330 ctx->num_open_handles = 0;
2331 ctx->data_buffer_ptr = NULL;
2332 ctx->any_sparse_streams = false;
2333 INIT_LIST_HEAD(&ctx->reparse_dentries);
2334 INIT_LIST_HEAD(&ctx->encrypted_dentries);
2336 for (u32 i = 0; i < blob->out_refcnt; i++) {
2337 const struct wim_inode *inode = targets[i].inode;
2338 const struct wim_inode_stream *strm = targets[i].stream;
2339 struct wim_dentry *dentry;
2341 /* A copy of the blob needs to be extracted to @inode. */
2343 if (ctx->common.supported_features.hard_links) {
2344 dentry = inode_first_extraction_dentry(inode);
2345 ret = begin_extract_blob_instance(blob, dentry, strm, ctx);
2346 ret = check_apply_error(dentry, ctx, ret);
2350 /* Hard links not supported. Extract the blob
2351 * separately to each alias of the inode. */
2352 inode_for_each_extraction_alias(dentry, inode) {
2353 ret = begin_extract_blob_instance(blob, dentry, strm, ctx);
2354 ret = check_apply_error(dentry, ctx, ret);
2369 pwrite_to_handle(HANDLE h, const void *data, size_t size, u64 offset)
2371 const void * const end = data + size;
2373 IO_STATUS_BLOCK iosb;
2376 for (p = data; p != end; p += iosb.Information,
2377 offset += iosb.Information)
2379 LARGE_INTEGER offs = { .QuadPart = offset };
2381 status = NtWriteFile(h, NULL, NULL, NULL, &iosb,
2382 (void *)p, min(INT32_MAX, end - p),
2384 if (!NT_SUCCESS(status)) {
2386 L"Error writing data to target volume");
2387 return WIMLIB_ERR_WRITE;
2393 /* Called when the next chunk of a blob has been read for extraction */
2395 win32_extract_chunk(const struct blob_descriptor *blob, u64 offset,
2396 const void *chunk, size_t size, void *_ctx)
2398 struct win32_apply_ctx *ctx = _ctx;
2399 const void * const end = chunk + size;
2407 * For sparse streams, only write nonzero regions. This lets the
2408 * filesystem use holes to represent zero regions.
2410 for (p = chunk; p != end; p += len, offset += len) {
2411 zeroes = maybe_detect_sparse_region(p, end - p, &len,
2412 ctx->any_sparse_streams);
2413 for (i = 0; i < ctx->num_open_handles; i++) {
2414 if (!zeroes || !ctx->is_sparse_stream[i]) {
2415 ret = pwrite_to_handle(ctx->open_handles[i],
2423 /* Copy the data chunk into the buffer (if needed) */
2424 if (ctx->data_buffer_ptr)
2425 ctx->data_buffer_ptr = mempcpy(ctx->data_buffer_ptr,
2431 get_system_compression_format(int extract_flags)
2433 if (extract_flags & WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS4K)
2434 return FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K;
2436 if (extract_flags & WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS8K)
2437 return FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS8K;
2439 if (extract_flags & WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS16K)
2440 return FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS16K;
2442 return FILE_PROVIDER_COMPRESSION_FORMAT_LZX;
2446 static const wchar_t *
2447 get_system_compression_format_string(int format)
2450 case FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K:
2452 case FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS8K:
2454 case FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS16K:
2455 return L"XPRESS16K";
2462 set_system_compression(HANDLE h, int format)
2466 struct wof_external_info wof_info;
2467 struct file_provider_external_info file_info;
2470 .version = WOF_CURRENT_VERSION,
2471 .provider = WOF_PROVIDER_FILE,
2474 .version = FILE_PROVIDER_CURRENT_VERSION,
2475 .compression_format = format,
2479 /* We intentionally use NtFsControlFile() rather than DeviceIoControl()
2480 * here because the "compressing this object would not save space"
2481 * status code does not map to a valid Win32 error code on older
2482 * versions of Windows (before Windows 10?). This can be a problem if
2483 * the WOFADK driver is being used rather than the regular WOF, since
2484 * WOFADK can be used on older versions of Windows. */
2485 status = winnt_fsctl(h, FSCTL_SET_EXTERNAL_BACKING,
2486 &in, sizeof(in), NULL, 0, NULL);
2488 if (status == 0xC000046F) /* "Compressing this object would not save space." */
2489 return STATUS_SUCCESS;
2494 /* Hard-coded list of files which the Windows bootloader may need to access
2495 * before the WOF driver has been loaded. */
2496 static const wchar_t * const bootloader_pattern_strings[] = {
2499 L"\\Windows\\AppPatch\\drvmain.sdb",
2500 L"\\Windows\\Boot\\DVD\\*",
2501 L"\\Windows\\Boot\\EFI\\*",
2502 L"\\Windows\\bootstat.dat",
2503 L"\\Windows\\Fonts\\vgaoem.fon",
2504 L"\\Windows\\Fonts\\vgasys.fon",
2505 L"\\Windows\\INF\\errata.inf",
2506 L"\\Windows\\System32\\config\\*",
2507 L"\\Windows\\System32\\ntkrnlpa.exe",
2508 L"\\Windows\\System32\\ntoskrnl.exe",
2509 L"\\Windows\\System32\\bootvid.dll",
2510 L"\\Windows\\System32\\ci.dll",
2511 L"\\Windows\\System32\\hal*.dll",
2512 L"\\Windows\\System32\\mcupdate_AuthenticAMD.dll",
2513 L"\\Windows\\System32\\mcupdate_GenuineIntel.dll",
2514 L"\\Windows\\System32\\pshed.dll",
2515 L"\\Windows\\System32\\apisetschema.dll",
2516 L"\\Windows\\System32\\api-ms-win*.dll",
2517 L"\\Windows\\System32\\ext-ms-win*.dll",
2518 L"\\Windows\\System32\\KernelBase.dll",
2519 L"\\Windows\\System32\\drivers\\*.sys",
2520 L"\\Windows\\System32\\*.nls",
2521 L"\\Windows\\System32\\kbd*.dll",
2522 L"\\Windows\\System32\\kd*.dll",
2523 L"\\Windows\\System32\\clfs.sys",
2524 L"\\Windows\\System32\\CodeIntegrity\\driver.stl",
2527 static const struct string_list bootloader_patterns = {
2528 .strings = (wchar_t **)bootloader_pattern_strings,
2529 .num_strings = ARRAY_LEN(bootloader_pattern_strings),
2533 set_system_compression_on_inode(struct wim_inode *inode, int format,
2534 struct win32_apply_ctx *ctx)
2536 bool retried = false;
2540 /* If it may be needed for compatibility with the Windows bootloader,
2541 * force this file to XPRESS4K or uncompressed format. The bootloader
2542 * of Windows 10 supports XPRESS4K only; older versions don't support
2543 * system compression at all. */
2544 if (!is_image_windows_10_or_later(ctx) ||
2545 format != FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K)
2547 /* We need to check the patterns against every name of the
2548 * inode, in case any of them match. */
2549 struct wim_dentry *dentry;
2550 inode_for_each_extraction_alias(dentry, inode) {
2554 if (calculate_dentry_full_path(dentry)) {
2555 ERROR("Unable to compute file path!");
2556 return STATUS_NO_MEMORY;
2559 incompatible = match_pattern_list(dentry->d_full_path,
2560 &bootloader_patterns);
2561 FREE(dentry->d_full_path);
2562 dentry->d_full_path = NULL;
2567 warned = (ctx->num_system_compression_exclusions++ > 0);
2569 if (is_image_windows_10_or_later(ctx)) {
2570 /* Force to XPRESS4K */
2572 WARNING("For compatibility with the "
2573 "Windows bootloader, some "
2576 "using the XPRESS4K format "
2577 "instead of the %"TS" format\n"
2579 get_system_compression_format_string(format));
2581 format = FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K;
2584 /* Force to uncompressed */
2586 WARNING("For compatibility with the "
2587 "Windows bootloader, some "
2589 " be compressed with"
2590 " system compression "
2591 "(\"compacted\").");
2593 return STATUS_SUCCESS;
2599 /* Open the extracted file. */
2600 status = create_file(&h, GENERIC_READ | GENERIC_WRITE, NULL,
2602 inode_first_extraction_dentry(inode), ctx);
2604 if (!NT_SUCCESS(status))
2607 /* Compress the file. If the attempt fails with "invalid device
2608 * request", then attach wof.sys (or wofadk.sys) and retry. */
2609 status = set_system_compression(h, format);
2610 if (unlikely(status == STATUS_INVALID_DEVICE_REQUEST && !retried)) {
2611 wchar_t drive_path[7];
2612 if (!win32_get_drive_path(ctx->common.target, drive_path) &&
2613 win32_try_to_attach_wof(drive_path + 4)) {
2624 * This function is called when doing a "compact-mode" extraction and we just
2625 * finished extracting a blob to one or more locations. For each location that
2626 * was the unnamed data stream of a file, this function compresses the
2627 * corresponding file using System Compression, if allowed.
2629 * Note: we're doing the compression immediately after extracting the data
2630 * rather than during a separate compression pass. This way should be faster
2631 * since the operating system should still have the file's data cached.
2633 * Note: we're having the operating system do the compression, which is not
2634 * ideal because wimlib could create the compressed data faster and more
2635 * efficiently (the compressed data format is identical to a WIM resource). But
2636 * we seemingly don't have a choice because WOF prevents applications from
2637 * creating its reparse points.
2640 handle_system_compression(struct blob_descriptor *blob, struct win32_apply_ctx *ctx)
2642 const struct blob_extraction_target *targets = blob_extraction_targets(blob);
2644 const int format = get_system_compression_format(ctx->common.extract_flags);
2646 for (u32 i = 0; i < blob->out_refcnt; i++) {
2647 struct wim_inode *inode = targets[i].inode;
2648 struct wim_inode_stream *strm = targets[i].stream;
2651 if (!stream_is_unnamed_data_stream(strm))
2654 if (will_externally_back_inode(inode, ctx, NULL, false) != 0)
2657 status = set_system_compression_on_inode(inode, format, ctx);
2658 if (likely(NT_SUCCESS(status)))
2661 if (status == STATUS_INVALID_DEVICE_REQUEST) {
2663 "The request to compress the extracted files using System Compression\n"
2664 " will not be honored because the operating system or target volume\n"
2665 " does not support it. System Compression is only supported on\n"
2666 " Windows 10 and later, and only on NTFS volumes.");
2667 ctx->common.extract_flags &= ~COMPACT_FLAGS;
2671 ctx->num_system_compression_failures++;
2672 if (ctx->num_system_compression_failures < 10) {
2673 winnt_warning(status, L"\"%ls\": Failed to compress "
2674 "extracted file using System Compression",
2676 } else if (ctx->num_system_compression_failures == 10) {
2677 WARNING("Suppressing further warnings about "
2678 "System Compression failures.");
2683 /* Called when a blob has been fully read for extraction */
2685 win32_end_extract_blob(struct blob_descriptor *blob, int status, void *_ctx)
2687 struct win32_apply_ctx *ctx = _ctx;
2689 const struct wim_dentry *dentry;
2691 /* Extend sparse streams to their final size. */
2692 if (ctx->any_sparse_streams && !status) {
2693 for (unsigned i = 0; i < ctx->num_open_handles; i++) {
2694 FILE_END_OF_FILE_INFORMATION info =
2695 { .EndOfFile = { .QuadPart = blob->size } };
2698 if (!ctx->is_sparse_stream[i])
2701 ntstatus = NtSetInformationFile(ctx->open_handles[i],
2703 &info, sizeof(info),
2704 FileEndOfFileInformation);
2705 if (!NT_SUCCESS(ntstatus)) {
2706 winnt_error(ntstatus, L"Error writing data to "
2707 "target volume (while extending)");
2708 status = WIMLIB_ERR_WRITE;
2719 if (unlikely(ctx->common.extract_flags & COMPACT_FLAGS))
2720 handle_system_compression(blob, ctx);
2722 if (likely(!ctx->data_buffer_ptr))
2725 if (!list_empty(&ctx->reparse_dentries)) {
2726 if (blob->size > REPARSE_DATA_MAX_SIZE) {
2727 dentry = list_first_entry(&ctx->reparse_dentries,
2728 struct wim_dentry, d_tmp_list);
2729 build_extraction_path(dentry, ctx);
2730 ERROR("Reparse data of \"%ls\" has size "
2731 "%"PRIu64" bytes (exceeds %u bytes)",
2732 current_path(ctx), blob->size,
2733 REPARSE_DATA_MAX_SIZE);
2734 ret = WIMLIB_ERR_INVALID_REPARSE_DATA;
2735 return check_apply_error(dentry, ctx, ret);
2738 memcpy(ctx->rpbuf.rpdata, ctx->data_buffer, blob->size);
2740 list_for_each_entry(dentry, &ctx->reparse_dentries, d_tmp_list) {
2742 /* Reparse point header */
2743 complete_reparse_point(&ctx->rpbuf, dentry->d_inode,
2746 ret = set_reparse_point(dentry, &ctx->rpbuf,
2747 REPARSE_DATA_OFFSET + blob->size,
2749 ret = check_apply_error(dentry, ctx, ret);
2755 if (!list_empty(&ctx->encrypted_dentries)) {
2756 ctx->encrypted_size = blob->size;
2757 list_for_each_entry(dentry, &ctx->encrypted_dentries, d_tmp_list) {
2758 ret = extract_encrypted_file(dentry, ctx);
2759 ret = check_apply_error(dentry, ctx, ret);
2762 /* Re-open the target directory if needed. */
2763 ret = open_target_directory(ctx);
2772 /* Attributes that can't be set directly */
2773 #define SPECIAL_ATTRIBUTES \
2774 (FILE_ATTRIBUTE_REPARSE_POINT | \
2775 FILE_ATTRIBUTE_DIRECTORY | \
2776 FILE_ATTRIBUTE_ENCRYPTED | \
2777 FILE_ATTRIBUTE_SPARSE_FILE | \
2778 FILE_ATTRIBUTE_COMPRESSED)
2781 set_object_id(HANDLE h, const struct wim_inode *inode,
2782 struct win32_apply_ctx *ctx)
2784 const void *object_id;
2788 if (!ctx->common.supported_features.object_ids)
2791 object_id = inode_get_object_id(inode, &len);
2792 if (likely(object_id == NULL)) /* No object ID? */
2795 status = winnt_fsctl(h, FSCTL_SET_OBJECT_ID,
2796 object_id, len, NULL, 0, NULL);
2797 if (NT_SUCCESS(status))
2800 /* Object IDs must be unique within the filesystem. A duplicate might
2801 * occur if an image containing object IDs is applied twice to the same
2802 * filesystem. Arguably, the user should be warned in this case; but
2803 * the reality seems to be that nothing important cares about object IDs
2804 * except the Distributed Link Tracking Service... so for now these
2805 * failures are just ignored. */
2806 if (status == STATUS_DUPLICATE_NAME ||
2807 status == STATUS_OBJECT_NAME_COLLISION)
2810 ctx->num_object_id_failures++;
2811 if (ctx->num_object_id_failures < 10) {
2812 winnt_warning(status, L"Can't set object ID on \"%ls\"",
2814 } else if (ctx->num_object_id_failures == 10) {
2815 WARNING("Suppressing further warnings about failure to set "
2821 set_xattrs(HANDLE h, const struct wim_inode *inode, struct win32_apply_ctx *ctx)
2823 const void *entries, *entries_end;
2825 const struct wim_xattr_entry *entry;
2827 u8 _buf[1024] _aligned_attribute(4);
2829 FILE_FULL_EA_INFORMATION *ea, *ea_prev;
2833 if (!ctx->common.supported_features.xattrs)
2836 entries = inode_get_xattrs(inode, &len);
2837 if (likely(entries == NULL || len == 0)) /* No extended attributes? */
2839 entries_end = entries + len;
2842 for (entry = entries; (void *)entry < entries_end;
2843 entry = xattr_entry_next(entry)) {
2844 if (!valid_xattr_entry(entry, entries_end - (void *)entry)) {
2845 ERROR("\"%"TS"\": extended attribute is corrupt or unsupported",
2846 inode_any_full_path(inode));
2847 return WIMLIB_ERR_INVALID_XATTR;
2850 bufsize += ALIGN(offsetof(FILE_FULL_EA_INFORMATION, EaName) +
2851 entry->name_len + 1 +
2852 le16_to_cpu(entry->value_len), 4);
2855 if (unlikely(bufsize != (u32)bufsize)) {
2856 ERROR("\"%"TS"\": too many extended attributes to extract!",
2857 inode_any_full_path(inode));
2858 return WIMLIB_ERR_INVALID_XATTR;
2861 if (unlikely(bufsize > sizeof(_buf))) {
2862 buf = MALLOC(bufsize);
2864 return WIMLIB_ERR_NOMEM;
2868 ea = (FILE_FULL_EA_INFORMATION *)buf;
2869 for (entry = entries; (void *)entry < entries_end;
2870 entry = xattr_entry_next(entry)) {
2874 ea_prev->NextEntryOffset = (u8 *)ea - (u8 *)ea_prev;
2875 ea->Flags = entry->flags;
2876 ea->EaNameLength = entry->name_len;
2877 ea->EaValueLength = le16_to_cpu(entry->value_len);
2878 p = mempcpy(ea->EaName, entry->name,
2879 ea->EaNameLength + 1 + ea->EaValueLength);
2880 while ((uintptr_t)p & 3)
2883 ea = (FILE_FULL_EA_INFORMATION *)p;
2885 ea_prev->NextEntryOffset = 0;
2886 wimlib_assert((u8 *)ea - buf == bufsize);
2888 status = NtSetEaFile(h, &ctx->iosb, buf, bufsize);
2889 if (unlikely(!NT_SUCCESS(status))) {
2890 if (status == STATUS_EAS_NOT_SUPPORTED) {
2891 /* This happens with Samba. */
2892 WARNING("Filesystem advertised extended attribute (EA) support, but it doesn't\n"
2893 " work. EAs will not be extracted.");
2894 ctx->common.supported_features.xattrs = 0;
2895 } else if (status == STATUS_INVALID_EA_NAME) {
2896 ctx->num_xattr_failures++;
2897 if (ctx->num_xattr_failures < 5) {
2898 winnt_warning(status,
2899 L"Can't set extended attributes on \"%ls\"",
2901 } else if (ctx->num_xattr_failures == 5) {
2902 WARNING("Suppressing further warnings about "
2903 "failure to set extended attributes.");
2906 winnt_error(status, L"Can't set extended attributes on \"%ls\"",
2908 ret = WIMLIB_ERR_SET_XATTR;
2919 /* Set the security descriptor @desc, of @desc_size bytes, on the file with open
2922 set_security_descriptor(HANDLE h, const void *_desc,
2923 size_t desc_size, struct win32_apply_ctx *ctx)
2925 SECURITY_INFORMATION info;
2927 SECURITY_DESCRIPTOR_RELATIVE *desc;
2930 * Ideally, we would just pass in the security descriptor buffer as-is.
2931 * But it turns out that Windows can mess up the security descriptor
2932 * even when using the low-level NtSetSecurityObject() function:
2934 * - Windows will clear SE_DACL_AUTO_INHERITED if it is set in the
2935 * passed buffer. To actually get Windows to set
2936 * SE_DACL_AUTO_INHERITED, the application must set the non-persistent
2937 * flag SE_DACL_AUTO_INHERIT_REQ. As usual, Microsoft didn't bother
2938 * to properly document either of these flags. It's unclear how
2939 * important SE_DACL_AUTO_INHERITED actually is, but to be safe we use
2940 * the SE_DACL_AUTO_INHERIT_REQ workaround to set it if needed.
2942 * - The above also applies to the equivalent SACL flags,
2943 * SE_SACL_AUTO_INHERITED and SE_SACL_AUTO_INHERIT_REQ.
2945 * - If the application says that it's setting
2946 * DACL_SECURITY_INFORMATION, then Windows sets SE_DACL_PRESENT in the
2947 * resulting security descriptor, even if the security descriptor the
2948 * application provided did not have a DACL. This seems to be
2949 * unavoidable, since omitting DACL_SECURITY_INFORMATION would cause a
2950 * default DACL to remain. Fortunately, this behavior seems harmless,
2951 * since the resulting DACL will still be "null" --- but it will be
2952 * "the other representation of null".
2954 * - The above also applies to SACL_SECURITY_INFORMATION and
2955 * SE_SACL_PRESENT. Again, it's seemingly unavoidable but "harmless"
2956 * that Windows changes the representation of a "null SACL".
2958 if (likely(desc_size <= STACK_MAX)) {
2959 desc = alloca(desc_size);
2961 desc = MALLOC(desc_size);
2963 return STATUS_NO_MEMORY;
2966 memcpy(desc, _desc, desc_size);
2968 if (likely(desc_size >= 4)) {
2970 if (desc->Control & SE_DACL_AUTO_INHERITED)
2971 desc->Control |= SE_DACL_AUTO_INHERIT_REQ;
2973 if (desc->Control & SE_SACL_AUTO_INHERITED)
2974 desc->Control |= SE_SACL_AUTO_INHERIT_REQ;
2978 * More API insanity. We want to set the entire security descriptor
2979 * as-is. But all available APIs require specifying the specific parts
2980 * of the security descriptor being set. Especially annoying is that
2981 * mandatory integrity labels are part of the SACL, but they aren't set
2982 * with SACL_SECURITY_INFORMATION. Instead, applications must also
2983 * specify LABEL_SECURITY_INFORMATION (Windows Vista, Windows 7) or
2984 * BACKUP_SECURITY_INFORMATION (Windows 8). But at least older versions
2985 * of Windows don't error out if you provide these newer flags...
2987 * Also, if the process isn't running as Administrator, then it probably
2988 * doesn't have SE_RESTORE_PRIVILEGE. In this case, it will always get
2989 * the STATUS_PRIVILEGE_NOT_HELD error by trying to set the SACL, even
2990 * if the security descriptor it provided did not have a SACL. By
2991 * default, in this case we try to recover and set as much of the
2992 * security descriptor as possible --- potentially excluding the DACL, and
2993 * even the owner, as well as the SACL.
2996 info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
2997 DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION |
2998 LABEL_SECURITY_INFORMATION | BACKUP_SECURITY_INFORMATION;
3002 * It's also worth noting that SetFileSecurity() is unusable because it
3003 * doesn't request "backup semantics" when it opens the file internally.
3004 * NtSetSecurityObject() seems to be the best function to use in backup
3005 * applications. (SetSecurityInfo() should also work, but it's harder
3006 * to use and must call NtSetSecurityObject() internally anyway.
3007 * BackupWrite() is theoretically usable as well, but it's inflexible
3008 * and poorly documented.)
3012 status = NtSetSecurityObject(h, info, desc);
3013 if (NT_SUCCESS(status))
3014 goto out_maybe_free_desc;
3016 /* Failed to set the requested parts of the security descriptor. If the
3017 * error was permissions-related, try to set fewer parts of the security
3018 * descriptor, unless WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled. */
3019 if ((status == STATUS_PRIVILEGE_NOT_HELD ||
3020 status == STATUS_ACCESS_DENIED) &&
3021 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
3023 if (info & SACL_SECURITY_INFORMATION) {
3024 info &= ~(SACL_SECURITY_INFORMATION |
3025 LABEL_SECURITY_INFORMATION |
3026 BACKUP_SECURITY_INFORMATION);
3027 ctx->partial_security_descriptors++;
3030 if (info & DACL_SECURITY_INFORMATION) {
3031 info &= ~DACL_SECURITY_INFORMATION;
3034 if (info & OWNER_SECURITY_INFORMATION) {
3035 info &= ~OWNER_SECURITY_INFORMATION;
3038 /* Nothing left except GROUP, and if we removed it we
3039 * wouldn't have anything at all. */
3042 /* No part of the security descriptor could be set, or
3043 * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled and the full security
3044 * descriptor could not be set. */
3045 if (!(info & SACL_SECURITY_INFORMATION))
3046 ctx->partial_security_descriptors--;
3047 ctx->no_security_descriptors++;
3049 out_maybe_free_desc:
3050 if (unlikely(desc_size > STACK_MAX))
3055 /* Set metadata on the open file @h from the WIM inode @inode. */
3057 do_apply_metadata_to_file(HANDLE h, const struct wim_inode *inode,
3058 struct win32_apply_ctx *ctx)
3060 FILE_BASIC_INFORMATION info;
3064 /* Set the file's object ID if present and object IDs are supported by
3065 * the filesystem. */
3066 set_object_id(h, inode, ctx);
3068 /* Set the file's extended attributes (EAs) if present and EAs are
3069 * supported by the filesystem. */
3070 ret = set_xattrs(h, inode, ctx);
3074 /* Set the file's security descriptor if present and we're not in
3076 if (inode_has_security_descriptor(inode) &&
3077 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
3079 const struct wim_security_data *sd;
3083 sd = wim_get_current_security_data(ctx->common.wim);
3084 desc = sd->descriptors[inode->i_security_id];
3085 desc_size = sd->sizes[inode->i_security_id];
3087 status = set_security_descriptor(h, desc, desc_size, ctx);
3088 if (!NT_SUCCESS(status) &&
3089 (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
3092 L"Can't set security descriptor on \"%ls\"",
3094 return WIMLIB_ERR_SET_SECURITY;
3098 /* Set attributes and timestamps */
3099 info.CreationTime.QuadPart = inode->i_creation_time;
3100 info.LastAccessTime.QuadPart = inode->i_last_access_time;
3101 info.LastWriteTime.QuadPart = inode->i_last_write_time;
3102 info.ChangeTime.QuadPart = 0;
3103 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES) {
3104 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
3106 info.FileAttributes = inode->i_attributes & ~SPECIAL_ATTRIBUTES;
3107 if (info.FileAttributes == 0)
3108 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
3111 status = NtSetInformationFile(h, &ctx->iosb, &info, sizeof(info),
3112 FileBasicInformation);
3113 /* On FAT volumes we get STATUS_INVALID_PARAMETER if we try to set
3114 * attributes on the root directory. (Apparently because FAT doesn't
3115 * actually have a place to store those attributes!) */
3116 if (!NT_SUCCESS(status)
3117 && !(status == STATUS_INVALID_PARAMETER &&
3118 dentry_is_root(inode_first_extraction_dentry(inode))))
3120 winnt_error(status, L"Can't set basic metadata on \"%ls\"",
3122 return WIMLIB_ERR_SET_ATTRIBUTES;
3129 apply_metadata_to_file(const struct wim_dentry *dentry,
3130 struct win32_apply_ctx *ctx)
3132 const struct wim_inode *inode = dentry->d_inode;
3138 perms = FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | WRITE_DAC |
3139 WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
3141 build_extraction_path(dentry, ctx);
3143 /* Open a handle with as many relevant permissions as possible. */
3144 while (!NT_SUCCESS(status = do_create_file(&h, perms, NULL,
3145 0, FILE_OPEN, 0, ctx)))
3147 if (status == STATUS_PRIVILEGE_NOT_HELD ||
3148 status == STATUS_ACCESS_DENIED)
3150 if (perms & ACCESS_SYSTEM_SECURITY) {
3151 perms &= ~ACCESS_SYSTEM_SECURITY;
3154 if (perms & WRITE_DAC) {
3155 perms &= ~WRITE_DAC;
3158 if (perms & WRITE_OWNER) {
3159 perms &= ~WRITE_OWNER;
3163 winnt_error(status, L"Can't open \"%ls\" to set metadata",
3165 return WIMLIB_ERR_OPEN;
3168 ret = do_apply_metadata_to_file(h, inode, ctx);
3176 apply_metadata(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
3178 const struct wim_dentry *dentry;
3181 /* We go in reverse so that metadata is set on all a directory's
3182 * children before the directory itself. This avoids any potential
3183 * problems with attributes, timestamps, or security descriptors. */
3184 list_for_each_entry_reverse(dentry, dentry_list, d_extraction_list_node)
3186 ret = apply_metadata_to_file(dentry, ctx);
3187 ret = check_apply_error(dentry, ctx, ret);
3190 ret = report_file_metadata_applied(&ctx->common);
3197 /* Issue warnings about problems during the extraction for which warnings were
3198 * not already issued (due to the high number of potential warnings if we issued
3199 * them per-file). */
3201 do_warnings(const struct win32_apply_ctx *ctx)
3203 if (ctx->partial_security_descriptors == 0
3204 && ctx->no_security_descriptors == 0
3205 && ctx->num_set_short_name_failures == 0
3207 && ctx->num_remove_short_name_failures == 0
3212 WARNING("Extraction to \"%ls\" complete, but with one or more warnings:",
3213 ctx->common.target);
3214 if (ctx->num_set_short_name_failures) {
3215 WARNING("- Could not set short names on %lu files or directories",
3216 ctx->num_set_short_name_failures);
3219 if (ctx->num_remove_short_name_failures) {
3220 WARNING("- Could not remove short names on %lu files or directories"
3221 " (This is expected on Vista and earlier)",
3222 ctx->num_remove_short_name_failures);
3225 if (ctx->partial_security_descriptors) {
3226 WARNING("- Could only partially set the security descriptor\n"
3227 " on %lu files or directories.",
3228 ctx->partial_security_descriptors);
3230 if (ctx->no_security_descriptors) {
3231 WARNING("- Could not set security descriptor at all\n"
3232 " on %lu files or directories.",
3233 ctx->no_security_descriptors);
3235 if (ctx->partial_security_descriptors || ctx->no_security_descriptors) {
3236 WARNING("To fully restore all security descriptors, run the program\n"
3237 " with Administrator rights.");
3242 count_dentries(const struct list_head *dentry_list)
3244 const struct list_head *cur;
3247 list_for_each(cur, dentry_list)
3253 /* Extract files from a WIM image to a directory on Windows */
3255 win32_extract(struct list_head *dentry_list, struct apply_ctx *_ctx)
3258 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
3261 ret = prepare_target(dentry_list, ctx);
3265 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
3266 ret = start_wimboot_extraction(dentry_list, ctx);
3271 ctx->windows_build_number = xml_get_windows_build_number(ctx->common.wim->xml_info,
3272 ctx->common.wim->current_image);
3274 dentry_count = count_dentries(dentry_list);
3276 ret = start_file_structure_phase(&ctx->common, dentry_count);
3280 ret = create_directories(dentry_list, ctx);
3284 ret = create_nondirectories(dentry_list, ctx);
3288 ret = end_file_structure_phase(&ctx->common);
3292 struct read_blob_callbacks cbs = {
3293 .begin_blob = win32_begin_extract_blob,
3294 .continue_blob = win32_extract_chunk,
3295 .end_blob = win32_end_extract_blob,
3298 ret = extract_blob_list(&ctx->common, &cbs);
3302 ret = start_file_metadata_phase(&ctx->common, dentry_count);
3306 ret = apply_metadata(dentry_list, ctx);
3310 ret = end_file_metadata_phase(&ctx->common);
3314 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
3315 ret = end_wimboot_extraction(ctx);
3322 close_target_directory(ctx);
3323 if (ctx->target_ntpath.Buffer)
3324 HeapFree(GetProcessHeap(), 0, ctx->target_ntpath.Buffer);
3325 FREE(ctx->pathbuf.Buffer);
3326 FREE(ctx->print_buffer);
3327 FREE(ctx->wimboot.wims);
3328 if (ctx->prepopulate_pats) {
3329 FREE(ctx->prepopulate_pats->strings);
3330 FREE(ctx->prepopulate_pats);
3332 FREE(ctx->mem_prepopulate_pats);
3333 FREE(ctx->data_buffer);
3337 const struct apply_operations win32_apply_ops = {
3339 .get_supported_features = win32_get_supported_features,
3340 .extract = win32_extract,
3341 .will_back_from_wim = win32_will_back_from_wim,
3342 .context_size = sizeof(struct win32_apply_ctx),
3345 #endif /* __WIN32__ */