2 * win32_apply.c - Windows-specific code for applying files from a WIM image.
6 * Copyright (C) 2013, 2014, 2015 Eric Biggers
8 * This file is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU Lesser General Public License as published by the Free
10 * Software Foundation; either version 3 of the License, or (at your option) any
13 * This file is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this file; if not, see http://www.gnu.org/licenses/.
28 #include "wimlib/win32_common.h"
30 #include "wimlib/apply.h"
31 #include "wimlib/assert.h"
32 #include "wimlib/blob_table.h"
33 #include "wimlib/capture.h" /* for mangle_pat() and match_pattern_list() */
34 #include "wimlib/dentry.h"
35 #include "wimlib/encoding.h"
36 #include "wimlib/error.h"
37 #include "wimlib/metadata.h"
38 #include "wimlib/paths.h"
39 #include "wimlib/pattern.h"
40 #include "wimlib/reparse.h"
41 #include "wimlib/textfile.h"
42 #include "wimlib/xml.h"
43 #include "wimlib/wimboot.h"
44 #include "wimlib/wof.h"
46 struct win32_apply_ctx {
48 /* Extract flags, the pointer to the WIMStruct, etc. */
49 struct apply_ctx common;
51 /* WIMBoot information, only filled in if WIMLIB_EXTRACT_FLAG_WIMBOOT
54 /* This array contains the WIM files registered with WOF on the
55 * target volume for this extraction operation. All WIMStructs
56 * in this array are distinct and have ->filename != NULL. */
60 u8 blob_table_hash[SHA1_HASH_SIZE];
64 bool have_wrong_version_wims;
65 bool have_uncompressed_wims;
66 bool have_unsupported_compressed_resources;
67 bool have_huge_resources;
70 /* External backing information */
71 struct string_set *prepopulate_pats;
72 void *mem_prepopulate_pats;
73 bool tried_to_load_prepopulate_list;
75 /* Open handle to the target directory */
78 /* NT namespace path to the target directory (buffer allocated) */
79 UNICODE_STRING target_ntpath;
81 /* Temporary buffer for building paths (buffer allocated) */
82 UNICODE_STRING pathbuf;
84 /* Object attributes to reuse for opening files in the target directory.
85 * (attr.ObjectName == &pathbuf) and (attr.RootDirectory == h_target).
87 OBJECT_ATTRIBUTES attr;
89 /* Temporary I/O status block for system calls */
92 /* Allocated buffer for creating "printable" paths from our
93 * target-relative NT paths */
94 wchar_t *print_buffer;
96 /* Allocated buffer for reading blob data when it cannot be extracted
100 /* Pointer to the next byte in @data_buffer to fill */
103 /* Size allocated in @data_buffer */
104 size_t data_buffer_size;
106 /* Current offset in the raw encrypted file being written */
107 size_t encrypted_offset;
109 /* Current size of the raw encrypted file being written */
110 size_t encrypted_size;
112 /* Temporary buffer for reparse data */
113 struct reparse_buffer_disk rpbuf;
115 /* Temporary buffer for reparse data of "fixed" absolute symbolic links
117 struct reparse_buffer_disk rpfixbuf;
119 /* Array of open handles to filesystem streams currently being written
121 HANDLE open_handles[MAX_OPEN_FILES];
123 /* Number of handles in @open_handles currently open (filled in from the
124 * beginning of the array) */
125 unsigned num_open_handles;
127 /* List of dentries, joined by @d_tmp_list, that need to have reparse
128 * data extracted as soon as the whole blob has been read into
130 struct list_head reparse_dentries;
132 /* List of dentries, joined by @d_tmp_list, that need to have raw
133 * encrypted data extracted as soon as the whole blob has been read into
135 struct list_head encrypted_dentries;
137 /* Number of files for which we didn't have permission to set the full
138 * security descriptor. */
139 unsigned long partial_security_descriptors;
141 /* Number of files for which we didn't have permission to set any part
142 * of the security descriptor. */
143 unsigned long no_security_descriptors;
145 /* Number of files for which we couldn't set the short name. */
146 unsigned long num_set_short_name_failures;
148 /* Number of files for which we couldn't remove the short name. */
149 unsigned long num_remove_short_name_failures;
151 /* Number of files on which we couldn't set System Compression. */
152 unsigned long num_system_compression_failures;
154 /* The number of files which, for compatibility with the Windows
155 * bootloader, were not compressed using the requested system
156 * compression format. This includes matches with the hardcoded pattern
157 * list only; it does not include matches with patterns in
158 * [PrepopulateList]. */
159 unsigned long num_system_compression_exclusions;
161 /* The Windows build number of the image being applied, or 0 if unknown.
163 u64 windows_build_number;
165 /* Have we tried to enable short name support on the target volume yet?
167 bool tried_to_enable_short_names;
170 /* Get the drive letter from a Windows path, or return the null character if the
171 * path is relative. */
173 get_drive_letter(const wchar_t *path)
175 /* Skip \\?\ prefix */
176 if (!wcsncmp(path, L"\\\\?\\", 4))
179 /* Return drive letter if valid */
180 if (((path[0] >= L'a' && path[0] <= L'z') ||
181 (path[0] >= L'A' && path[0] <= L'Z')) && path[1] == L':')
188 get_vol_flags(const wchar_t *target, DWORD *vol_flags_ret,
189 bool *short_names_supported_ret)
191 wchar_t filesystem_name[MAX_PATH + 1];
193 wchar_t *volume = NULL;
196 *short_names_supported_ret = false;
198 drive[0] = get_drive_letter(target);
206 if (!GetVolumeInformation(volume, NULL, 0, NULL, NULL,
207 vol_flags_ret, filesystem_name,
208 ARRAY_LEN(filesystem_name)))
210 win32_warning(GetLastError(),
211 L"Failed to get volume information for \"%ls\"",
216 if (wcsstr(filesystem_name, L"NTFS")) {
217 /* FILE_SUPPORTS_HARD_LINKS is only supported on Windows 7 and
218 * later. Force it on anyway if filesystem is NTFS. */
219 *vol_flags_ret |= FILE_SUPPORTS_HARD_LINKS;
221 /* There's no volume flag for short names, but according to the
222 * MS documentation they are only user-settable on NTFS. */
223 *short_names_supported_ret = true;
227 /* Is the image being extracted an OS image for Windows 10 or later? */
229 is_image_windows_10_or_later(struct win32_apply_ctx *ctx)
231 /* Note: if no build number is available, this returns false. */
232 return ctx->windows_build_number >= 10240;
235 static const wchar_t *
236 current_path(struct win32_apply_ctx *ctx);
239 build_extraction_path(const struct wim_dentry *dentry,
240 struct win32_apply_ctx *ctx);
243 report_dentry_apply_error(const struct wim_dentry *dentry,
244 struct win32_apply_ctx *ctx, int ret)
246 build_extraction_path(dentry, ctx);
247 return report_apply_error(&ctx->common, ret, current_path(ctx));
251 check_apply_error(const struct wim_dentry *dentry,
252 struct win32_apply_ctx *ctx, int ret)
255 ret = report_dentry_apply_error(dentry, ctx, ret);
260 win32_get_supported_features(const wchar_t *target,
261 struct wim_features *supported_features)
264 bool short_names_supported;
266 /* Query the features of the target volume. */
268 get_vol_flags(target, &vol_flags, &short_names_supported);
270 supported_features->archive_files = 1;
271 supported_features->hidden_files = 1;
272 supported_features->system_files = 1;
274 if (vol_flags & FILE_FILE_COMPRESSION)
275 supported_features->compressed_files = 1;
277 if (vol_flags & FILE_SUPPORTS_ENCRYPTION) {
278 supported_features->encrypted_files = 1;
279 supported_features->encrypted_directories = 1;
282 supported_features->not_context_indexed_files = 1;
284 /* Don't do anything with FILE_SUPPORTS_SPARSE_FILES. */
286 if (vol_flags & FILE_NAMED_STREAMS)
287 supported_features->named_data_streams = 1;
289 if (vol_flags & FILE_SUPPORTS_HARD_LINKS)
290 supported_features->hard_links = 1;
292 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS)
293 supported_features->reparse_points = 1;
295 if (vol_flags & FILE_PERSISTENT_ACLS)
296 supported_features->security_descriptors = 1;
298 if (short_names_supported)
299 supported_features->short_names = 1;
301 supported_features->timestamps = 1;
303 /* Note: Windows does not support case sensitive filenames! At least
304 * not without changing the registry and rebooting... */
309 #define COMPACT_FLAGS (WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS4K | \
310 WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS8K | \
311 WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS16K | \
312 WIMLIB_EXTRACT_FLAG_COMPACT_LZX)
317 * If not done already, load the patterns from the [PrepopulateList] section of
318 * WimBootCompress.ini in the WIM image being extracted.
320 * Note: WimBootCompress.ini applies to both types of "external backing":
322 * - WIM backing ("WIMBoot" - Windows 8.1 and later)
323 * - File backing ("System Compression" - Windows 10 and later)
326 load_prepopulate_pats(struct win32_apply_ctx *ctx)
328 const wchar_t *path = L"\\Windows\\System32\\WimBootCompress.ini";
329 struct wim_dentry *dentry;
330 const struct blob_descriptor *blob;
333 struct string_set *s;
335 struct text_file_section sec;
337 if (ctx->tried_to_load_prepopulate_list)
340 ctx->tried_to_load_prepopulate_list = true;
342 dentry = get_dentry(ctx->common.wim, path, WIMLIB_CASE_INSENSITIVE);
344 (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
345 FILE_ATTRIBUTE_REPARSE_POINT |
346 FILE_ATTRIBUTE_ENCRYPTED)) ||
347 !(blob = inode_get_blob_for_unnamed_data_stream(dentry->d_inode,
348 ctx->common.wim->blob_table)))
350 WARNING("%ls does not exist in the WIM image.\n"
351 " The default configuration will be used instead; it assumes that all\n"
352 " files are valid for external backing regardless of path, equivalent\n"
353 " to an empty [PrepopulateList] section.", path);
354 return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
357 ret = read_blob_into_alloc_buf(blob, &buf);
361 s = CALLOC(1, sizeof(struct string_set));
364 return WIMLIB_ERR_NOMEM;
367 sec.name = T("PrepopulateList");
370 ret = do_load_text_file(path, buf, blob->size, &mem, &sec, 1,
371 LOAD_TEXT_FILE_REMOVE_QUOTES |
372 LOAD_TEXT_FILE_NO_WARNINGS,
374 STATIC_ASSERT(OS_PREFERRED_PATH_SEPARATOR == WIM_PATH_SEPARATOR);
380 ctx->prepopulate_pats = s;
381 ctx->mem_prepopulate_pats = mem;
385 /* Returns %true if the specified absolute path to a file in the WIM image can
386 * be subject to external backing when extracted. Otherwise returns %false. */
388 can_externally_back_path(const wchar_t *path, const struct win32_apply_ctx *ctx)
390 /* Does the path match a pattern given in the [PrepopulateList] section
391 * of WimBootCompress.ini? */
392 if (ctx->prepopulate_pats && match_pattern_list(path, ctx->prepopulate_pats))
395 /* Since we attempt to modify the SYSTEM registry after it's extracted
396 * (see end_wimboot_extraction()), it can't be extracted as externally
397 * backed. This extends to associated files such as SYSTEM.LOG that
398 * also must be writable in order to write to the registry. Normally,
399 * SYSTEM is in [PrepopulateList], and the SYSTEM.* files match patterns
400 * in [ExclusionList] and therefore are not captured in the WIM at all.
401 * However, a WIM that wasn't specifically captured in "WIMBoot mode"
402 * may contain SYSTEM.* files. So to make things "just work", hard-code
404 if (match_path(path, L"\\Windows\\System32\\config\\SYSTEM*", false))
410 /* Can the specified WIM resource be used as the source of an external backing
411 * for the wof.sys WIM provider? */
413 is_resource_valid_for_external_backing(const struct wim_resource_descriptor *rdesc,
414 struct win32_apply_ctx *ctx)
416 /* Must be the original WIM file format. This check excludes pipable
417 * resources and solid resources. It also excludes other resources
418 * contained in such files even if they would be otherwise compatible.
420 if (rdesc->wim->hdr.magic != WIM_MAGIC ||
421 rdesc->wim->hdr.wim_version != WIM_VERSION_DEFAULT)
423 ctx->wimboot.have_wrong_version_wims = true;
428 * Whitelist of compression types and chunk sizes supported by
429 * Microsoft's WOF driver.
432 * - Uncompressed WIMs result in BSOD. However, this only applies to
433 * the WIM file itself, not to uncompressed resources in a WIM file
434 * that is otherwise compressed.
435 * - XPRESS 64K sometimes appears to work, but sometimes it causes
436 * reads to fail with STATUS_UNSUCCESSFUL.
438 switch (rdesc->compression_type) {
439 case WIMLIB_COMPRESSION_TYPE_NONE:
440 if (rdesc->wim->compression_type == WIMLIB_COMPRESSION_TYPE_NONE) {
441 ctx->wimboot.have_uncompressed_wims = true;
445 case WIMLIB_COMPRESSION_TYPE_XPRESS:
446 switch (rdesc->chunk_size) {
453 ctx->wimboot.have_unsupported_compressed_resources = true;
457 case WIMLIB_COMPRESSION_TYPE_LZX:
458 switch (rdesc->chunk_size) {
462 ctx->wimboot.have_unsupported_compressed_resources = true;
467 ctx->wimboot.have_unsupported_compressed_resources = true;
471 /* Microsoft's WoF driver errors out if it tries to satisfy a read with
472 * ending offset >= 4 GiB from an externally backed file. */
473 if (rdesc->uncompressed_size > 4200000000) {
474 ctx->wimboot.have_huge_resources = true;
481 #define EXTERNAL_BACKING_NOT_ENABLED -1
482 #define EXTERNAL_BACKING_NOT_POSSIBLE -2
483 #define EXTERNAL_BACKING_EXCLUDED -3
486 * Determines whether the specified file will be externally backed. Returns a
487 * negative status code if no, 0 if yes, or a positive wimlib error code on
488 * error. If the file is excluded from external backing based on its path, then
489 * *excluded_dentry_ret is set to the dentry for the path that matched the
492 * Note that this logic applies to both types of "external backing":
494 * - WIM backing ("WIMBoot" - Windows 8.1 and later)
495 * - File backing ("System Compression" - Windows 10 and later)
497 * However, in the case of WIM backing we also need to validate that the WIM
498 * resource that would be the source of the backing is supported by the wof.sys
502 will_externally_back_inode(struct wim_inode *inode, struct win32_apply_ctx *ctx,
503 const struct wim_dentry **excluded_dentry_ret,
506 struct wim_dentry *dentry;
507 struct blob_descriptor *blob;
510 if (load_prepopulate_pats(ctx) == WIMLIB_ERR_NOMEM)
511 return WIMLIB_ERR_NOMEM;
513 if (inode->i_can_externally_back)
516 /* This may do redundant checks because the cached value
517 * i_can_externally_back is 2-state (as opposed to 3-state:
518 * unknown/no/yes). But most files can be externally backed, so this
521 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
522 FILE_ATTRIBUTE_REPARSE_POINT |
523 FILE_ATTRIBUTE_ENCRYPTED))
524 return EXTERNAL_BACKING_NOT_POSSIBLE;
526 blob = inode_get_blob_for_unnamed_data_stream_resolved(inode);
529 return EXTERNAL_BACKING_NOT_POSSIBLE;
532 (blob->blob_location != BLOB_IN_WIM ||
533 !is_resource_valid_for_external_backing(blob->rdesc, ctx)))
534 return EXTERNAL_BACKING_NOT_POSSIBLE;
537 * We need to check the patterns in [PrepopulateList] against every name
538 * of the inode, in case any of them match.
541 inode_for_each_extraction_alias(dentry, inode) {
543 ret = calculate_dentry_full_path(dentry);
547 if (!can_externally_back_path(dentry->d_full_path, ctx)) {
548 if (excluded_dentry_ret)
549 *excluded_dentry_ret = dentry;
550 return EXTERNAL_BACKING_EXCLUDED;
554 inode->i_can_externally_back = 1;
559 * Determines if the unnamed data stream of a file will be created as a WIM
560 * external backing (a "WIMBoot pointer file"), as opposed to a standard
564 win32_will_back_from_wim(struct wim_dentry *dentry, struct apply_ctx *_ctx)
566 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
568 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
569 return EXTERNAL_BACKING_NOT_ENABLED;
571 return will_externally_back_inode(dentry->d_inode, ctx, NULL, true);
574 /* Find the WOF registration information for the specified WIM file. */
575 static struct wimboot_wim *
576 find_wimboot_wim(WIMStruct *wim_to_find, struct win32_apply_ctx *ctx)
578 for (size_t i = 0; i < ctx->wimboot.num_wims; i++)
579 if (wim_to_find == ctx->wimboot.wims[i].wim)
580 return &ctx->wimboot.wims[i];
587 set_backed_from_wim(HANDLE h, struct wim_inode *inode, struct win32_apply_ctx *ctx)
590 const struct wim_dentry *excluded_dentry;
591 const struct blob_descriptor *blob;
592 const struct wimboot_wim *wimboot_wim;
594 ret = will_externally_back_inode(inode, ctx, &excluded_dentry, true);
595 if (ret > 0) /* Error. */
598 if (ret < 0 && ret != EXTERNAL_BACKING_EXCLUDED)
599 return 0; /* Not externally backing, other than due to exclusion. */
601 if (unlikely(ret == EXTERNAL_BACKING_EXCLUDED)) {
602 /* Not externally backing due to exclusion. */
603 union wimlib_progress_info info;
605 build_extraction_path(excluded_dentry, ctx);
607 info.wimboot_exclude.path_in_wim = excluded_dentry->d_full_path;
608 info.wimboot_exclude.extraction_path = current_path(ctx);
610 return call_progress(ctx->common.progfunc,
611 WIMLIB_PROGRESS_MSG_WIMBOOT_EXCLUDE,
612 &info, ctx->common.progctx);
615 /* Externally backing. */
617 blob = inode_get_blob_for_unnamed_data_stream_resolved(inode);
618 wimboot_wim = find_wimboot_wim(blob->rdesc->wim, ctx);
620 if (unlikely(!wimboot_set_pointer(h,
622 wimboot_wim->data_source_id,
623 wimboot_wim->blob_table_hash,
624 ctx->wimboot.wof_running)))
626 const DWORD err = GetLastError();
628 build_extraction_path(inode_first_extraction_dentry(inode), ctx);
629 win32_error(err, L"\"%ls\": Couldn't set WIMBoot pointer data",
631 return WIMLIB_ERR_WIMBOOT;
636 /* Calculates the SHA-1 message digest of the WIM's blob table. */
638 hash_blob_table(WIMStruct *wim, u8 hash[SHA1_HASH_SIZE])
640 return wim_reshdr_to_hash(&wim->hdr.blob_table_reshdr, wim, hash);
644 register_wim_with_wof(WIMStruct *wim, struct win32_apply_ctx *ctx)
646 struct wimboot_wim *p;
649 /* Check if already registered */
650 for (size_t i = 0; i < ctx->wimboot.num_wims; i++)
651 if (wim == ctx->wimboot.wims[i].wim)
654 /* Not yet registered */
656 p = REALLOC(ctx->wimboot.wims,
657 (ctx->wimboot.num_wims + 1) * sizeof(ctx->wimboot.wims[0]));
659 return WIMLIB_ERR_NOMEM;
660 ctx->wimboot.wims = p;
662 ctx->wimboot.wims[ctx->wimboot.num_wims].wim = wim;
664 ret = hash_blob_table(wim, ctx->wimboot.wims[ctx->wimboot.num_wims].blob_table_hash);
668 ret = wimboot_alloc_data_source_id(wim->filename,
670 ctx->common.wim->current_image,
672 &ctx->wimboot.wims[ctx->wimboot.num_wims].data_source_id,
673 &ctx->wimboot.wof_running);
677 ctx->wimboot.num_wims++;
681 /* Prepare for doing a "WIMBoot" extraction by registering each source WIM file
682 * with WOF on the target volume. */
684 start_wimboot_extraction(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
687 struct wim_dentry *dentry;
689 if (!xml_get_wimboot(ctx->common.wim->xml_info,
690 ctx->common.wim->current_image))
691 WARNING("The WIM image is not marked as WIMBoot compatible. This usually\n"
692 " means it is not intended to be used to back a Windows operating\n"
693 " system. Proceeding anyway.");
695 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
696 struct blob_descriptor *blob;
698 ret = win32_will_back_from_wim(dentry, &ctx->common);
699 if (ret > 0) /* Error */
701 if (ret < 0) /* Won't externally back */
704 blob = inode_get_blob_for_unnamed_data_stream_resolved(dentry->d_inode);
705 ret = register_wim_with_wof(blob->rdesc->wim, ctx);
710 if (ctx->wimboot.have_wrong_version_wims) {
711 WARNING("At least one of the source WIM files uses a version of the WIM\n"
712 " file format that not supported by Microsoft's wof.sys driver.\n"
713 " Files whose data is contained in one of these WIM files will be\n"
714 " extracted as full files rather than externally backed.");
717 if (ctx->wimboot.have_uncompressed_wims) {
718 WARNING("At least one of the source WIM files is uncompressed. Files whose\n"
719 " data is contained in an uncompressed WIM file will be extracted as\n"
720 " full files rather than externally backed, since uncompressed WIM\n"
721 " files are not supported by Microsoft's wof.sys driver.");
724 if (ctx->wimboot.have_unsupported_compressed_resources) {
725 WARNING("At least one of the source WIM files uses a compression format that\n"
726 " is not supported by Microsoft's wof.sys driver. Files whose data is\n"
727 " contained in a compressed resource in one of these WIM files will be\n"
728 " extracted as full files rather than externally backed. (The\n"
729 " compression formats supported by wof.sys are: XPRESS 4K, XPRESS 8K,\n"
730 " XPRESS 16K, XPRESS 32K, and LZX 32K.)");
733 if (ctx->wimboot.have_huge_resources) {
734 WARNING("Some files exceeded 4.2 GB in size. Such files will be extracted\n"
735 " as full files rather than externally backed, since very large files\n"
736 " are not supported by Microsoft's wof.sys driver.");
743 build_win32_extraction_path(const struct wim_dentry *dentry,
744 struct win32_apply_ctx *ctx);
746 /* Sets WimBoot=1 in the extracted SYSTEM registry hive.
748 * WIMGAPI does this, and it's possible that it's important.
749 * But I don't know exactly what this value means to Windows. */
751 end_wimboot_extraction(struct win32_apply_ctx *ctx)
753 struct wim_dentry *dentry;
754 wchar_t subkeyname[32];
760 dentry = get_dentry(ctx->common.wim, L"\\Windows\\System32\\config\\SYSTEM",
761 WIMLIB_CASE_INSENSITIVE);
763 if (!dentry || !will_extract_dentry(dentry))
766 if (!will_extract_dentry(wim_get_current_root_dentry(ctx->common.wim)))
769 /* Not bothering to use the native routines (e.g. NtLoadKey()) for this.
770 * If this doesn't work, you probably also have many other problems. */
772 build_win32_extraction_path(dentry, ctx);
774 randomize_char_array_with_alnum(subkeyname, 20);
775 subkeyname[20] = L'\0';
777 res = RegLoadKey(HKEY_LOCAL_MACHINE, subkeyname, ctx->pathbuf.Buffer);
781 wcscpy(&subkeyname[20], L"\\Setup");
783 res = RegCreateKeyEx(HKEY_LOCAL_MACHINE, subkeyname, 0, NULL,
784 REG_OPTION_BACKUP_RESTORE, 0, NULL, &key, NULL);
790 res = RegSetValueEx(key, L"WimBoot", 0, REG_DWORD,
791 (const BYTE *)&value, sizeof(DWORD));
795 res = RegFlushKey(key);
798 res2 = RegCloseKey(key);
802 subkeyname[20] = L'\0';
803 RegUnLoadKey(HKEY_LOCAL_MACHINE, subkeyname);
807 win32_warning(res, L"Failed to set \\Setup: dword \"WimBoot\"=1 "
808 "value in registry hive \"%ls\"",
809 ctx->pathbuf.Buffer);
815 /* Returns the number of wide characters needed to represent the path to the
816 * specified @dentry, relative to the target directory, when extracted.
818 * Does not include null terminator (not needed for NtCreateFile). */
820 dentry_extraction_path_length(const struct wim_dentry *dentry)
823 const struct wim_dentry *d;
827 len += d->d_extraction_name_nchars + 1;
829 } while (!dentry_is_root(d) && will_extract_dentry(d));
831 return --len; /* No leading slash */
834 /* Returns the length of the longest string that might need to be appended to
835 * the path to an alias of an inode to open or create a named data stream.
837 * If the inode has no named data streams, this will be 0. Otherwise, this will
838 * be 1 plus the length of the longest-named data stream, since the data stream
839 * name must be separated from the path by the ':' character. */
841 inode_longest_named_data_stream_spec(const struct wim_inode *inode)
844 for (unsigned i = 0; i < inode->i_num_streams; i++) {
845 const struct wim_inode_stream *strm = &inode->i_streams[i];
846 if (!stream_is_named_data_stream(strm))
848 size_t len = utf16le_len_chars(strm->stream_name);
857 /* Find the length, in wide characters, of the longest path needed for
858 * extraction of any file in @dentry_list relative to the target directory.
860 * Accounts for named data streams, but does not include null terminator (not
861 * needed for NtCreateFile). */
863 compute_path_max(struct list_head *dentry_list)
866 const struct wim_dentry *dentry;
868 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
871 len = dentry_extraction_path_length(dentry);
873 /* Account for named data streams */
874 len += inode_longest_named_data_stream_spec(dentry->d_inode);
883 /* Build the path at which to extract the @dentry, relative to the target
886 * The path is saved in ctx->pathbuf. */
888 build_extraction_path(const struct wim_dentry *dentry,
889 struct win32_apply_ctx *ctx)
893 const struct wim_dentry *d;
895 len = dentry_extraction_path_length(dentry);
897 ctx->pathbuf.Length = len * sizeof(wchar_t);
898 p = ctx->pathbuf.Buffer + len;
900 !dentry_is_root(d->d_parent) && will_extract_dentry(d->d_parent);
903 p -= d->d_extraction_name_nchars;
904 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
907 /* No leading slash */
908 p -= d->d_extraction_name_nchars;
909 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
912 /* Build the path at which to extract the @dentry, relative to the target
913 * directory, adding the suffix for a named data stream.
915 * The path is saved in ctx->pathbuf. */
917 build_extraction_path_with_ads(const struct wim_dentry *dentry,
918 struct win32_apply_ctx *ctx,
919 const wchar_t *stream_name,
920 size_t stream_name_nchars)
924 build_extraction_path(dentry, ctx);
926 /* Add :NAME for named data stream */
927 p = ctx->pathbuf.Buffer + (ctx->pathbuf.Length / sizeof(wchar_t));
929 wmemcpy(p, stream_name, stream_name_nchars);
930 ctx->pathbuf.Length += (1 + stream_name_nchars) * sizeof(wchar_t);
933 /* Build the Win32 namespace path to the specified @dentry when extracted.
935 * The path is saved in ctx->pathbuf and will be null terminated.
937 * XXX: We could get rid of this if it wasn't needed for the file encryption
938 * APIs, and the registry manipulation in WIMBoot mode. */
940 build_win32_extraction_path(const struct wim_dentry *dentry,
941 struct win32_apply_ctx *ctx)
943 build_extraction_path(dentry, ctx);
945 /* Prepend target_ntpath to our relative path, then change \??\ into \\?\ */
947 memmove(ctx->pathbuf.Buffer +
948 (ctx->target_ntpath.Length / sizeof(wchar_t)) + 1,
949 ctx->pathbuf.Buffer, ctx->pathbuf.Length);
950 memcpy(ctx->pathbuf.Buffer, ctx->target_ntpath.Buffer,
951 ctx->target_ntpath.Length);
952 ctx->pathbuf.Buffer[ctx->target_ntpath.Length / sizeof(wchar_t)] = L'\\';
953 ctx->pathbuf.Length += ctx->target_ntpath.Length + sizeof(wchar_t);
954 ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)] = L'\0';
956 wimlib_assert(ctx->pathbuf.Length >= 4 * sizeof(wchar_t) &&
957 !wmemcmp(ctx->pathbuf.Buffer, L"\\??\\", 4));
959 ctx->pathbuf.Buffer[1] = L'\\';
963 /* Returns a "printable" representation of the last relative NT path that was
964 * constructed with build_extraction_path() or build_extraction_path_with_ads().
966 * This will be overwritten by the next call to this function. */
967 static const wchar_t *
968 current_path(struct win32_apply_ctx *ctx)
970 wchar_t *p = ctx->print_buffer;
972 p = wmempcpy(p, ctx->common.target, ctx->common.target_nchars);
974 p = wmempcpy(p, ctx->pathbuf.Buffer, ctx->pathbuf.Length / sizeof(wchar_t));
976 return ctx->print_buffer;
979 /* Open handle to the target directory if it is not already open. If the target
980 * directory does not exist, this creates it. */
982 open_target_directory(struct win32_apply_ctx *ctx)
989 ctx->attr.Length = sizeof(ctx->attr);
990 ctx->attr.RootDirectory = NULL;
991 ctx->attr.ObjectName = &ctx->target_ntpath;
993 /* Don't use FILE_OPEN_REPARSE_POINT here; we want the extraction to
994 * happen at the directory "pointed to" by the reparse point. */
995 status = (*func_NtCreateFile)(&ctx->h_target,
1001 FILE_SHARE_VALID_FLAGS,
1003 FILE_DIRECTORY_FILE |
1004 FILE_OPEN_FOR_BACKUP_INTENT,
1007 if (!NT_SUCCESS(status)) {
1008 winnt_error(status, L"Can't open or create directory \"%ls\"",
1009 ctx->common.target);
1010 return WIMLIB_ERR_OPENDIR;
1012 ctx->attr.RootDirectory = ctx->h_target;
1013 ctx->attr.ObjectName = &ctx->pathbuf;
1018 close_target_directory(struct win32_apply_ctx *ctx)
1020 if (ctx->h_target) {
1021 (*func_NtClose)(ctx->h_target);
1022 ctx->h_target = NULL;
1023 ctx->attr.RootDirectory = NULL;
1028 * Ensures the target directory exists and opens a handle to it, in preparation
1029 * of using paths relative to it.
1032 prepare_target(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1037 ret = win32_path_to_nt_path(ctx->common.target, &ctx->target_ntpath);
1041 ret = open_target_directory(ctx);
1045 path_max = compute_path_max(dentry_list);
1046 /* Add some extra for building Win32 paths for the file encryption APIs,
1047 * and ensure we have at least enough to potentially use a 8.3 name for
1048 * the last component. */
1049 path_max += max(2 + (ctx->target_ntpath.Length / sizeof(wchar_t)),
1052 ctx->pathbuf.MaximumLength = path_max * sizeof(wchar_t);
1053 ctx->pathbuf.Buffer = MALLOC(ctx->pathbuf.MaximumLength);
1054 if (!ctx->pathbuf.Buffer)
1055 return WIMLIB_ERR_NOMEM;
1057 ctx->print_buffer = MALLOC((ctx->common.target_nchars + 1 + path_max + 1) *
1059 if (!ctx->print_buffer)
1060 return WIMLIB_ERR_NOMEM;
1065 /* When creating an inode that will have a short (DOS) name, we create it using
1066 * the long name associated with the short name. This ensures that the short
1067 * name gets associated with the correct long name. */
1068 static struct wim_dentry *
1069 first_extraction_alias(const struct wim_inode *inode)
1071 struct wim_dentry *dentry;
1073 inode_for_each_extraction_alias(dentry, inode)
1074 if (dentry_has_short_name(dentry))
1076 return inode_first_extraction_dentry(inode);
1080 * Set or clear FILE_ATTRIBUTE_COMPRESSED if the inherited value is different
1081 * from the desired value.
1083 * Note that you can NOT override the inherited value of
1084 * FILE_ATTRIBUTE_COMPRESSED directly with NtCreateFile().
1087 adjust_compression_attribute(HANDLE h, const struct wim_dentry *dentry,
1088 struct win32_apply_ctx *ctx)
1090 const bool compressed = (dentry->d_inode->i_attributes &
1091 FILE_ATTRIBUTE_COMPRESSED);
1093 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
1096 if (!ctx->common.supported_features.compressed_files)
1099 FILE_BASIC_INFORMATION info;
1101 USHORT compression_state;
1102 DWORD bytes_returned;
1104 /* Get current attributes */
1105 status = (*func_NtQueryInformationFile)(h, &ctx->iosb,
1106 &info, sizeof(info),
1107 FileBasicInformation);
1108 if (NT_SUCCESS(status) &&
1109 compressed == !!(info.FileAttributes & FILE_ATTRIBUTE_COMPRESSED))
1111 /* Nothing needs to be done. */
1115 /* Set the new compression state */
1118 compression_state = COMPRESSION_FORMAT_DEFAULT;
1120 compression_state = COMPRESSION_FORMAT_NONE;
1122 /* Note: don't use NtFsControlFile() here unless prepared to handle
1123 * STATUS_PENDING. */
1124 if (DeviceIoControl(h, FSCTL_SET_COMPRESSION,
1125 &compression_state, sizeof(USHORT), NULL, 0,
1126 &bytes_returned, NULL))
1129 win32_error(GetLastError(), L"Can't %s compression attribute on \"%ls\"",
1130 (compressed ? "set" : "clear"), current_path(ctx));
1131 return WIMLIB_ERR_SET_ATTRIBUTES;
1134 /* Try to enable short name support on the target volume. If successful, return
1135 * true. If unsuccessful, issue a warning and return false. */
1137 try_to_enable_short_names(const wchar_t *volume)
1140 FILE_FS_PERSISTENT_VOLUME_INFORMATION info;
1142 DWORD bytesReturned;
1144 h = CreateFile(volume, GENERIC_WRITE,
1145 FILE_SHARE_VALID_FLAGS, NULL, OPEN_EXISTING,
1146 FILE_FLAG_BACKUP_SEMANTICS, NULL);
1147 if (h == INVALID_HANDLE_VALUE)
1150 info.VolumeFlags = 0;
1151 info.FlagMask = PERSISTENT_VOLUME_STATE_SHORT_NAME_CREATION_DISABLED;
1155 bret = DeviceIoControl(h, FSCTL_SET_PERSISTENT_VOLUME_STATE,
1156 &info, sizeof(info), NULL, 0,
1157 &bytesReturned, NULL);
1166 win32_warning(GetLastError(),
1167 L"Failed to enable short name support on %ls",
1173 remove_conflicting_short_name(const struct wim_dentry *dentry, struct win32_apply_ctx *ctx)
1179 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1180 (13 * sizeof(wchar_t));
1181 u8 buf[bufsize] _aligned_attribute(8);
1182 bool retried = false;
1183 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1185 memset(buf, 0, bufsize);
1187 /* Build the path with the short name. */
1188 name = &ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)];
1189 while (name != ctx->pathbuf.Buffer && *(name - 1) != L'\\')
1191 end = mempcpy(name, dentry->d_short_name, dentry->d_short_name_nbytes);
1192 ctx->pathbuf.Length = ((u8 *)end - (u8 *)ctx->pathbuf.Buffer);
1194 /* Open the conflicting file (by short name). */
1195 status = (*func_NtOpenFile)(&h, GENERIC_WRITE | DELETE,
1196 &ctx->attr, &ctx->iosb,
1197 FILE_SHARE_VALID_FLAGS,
1198 FILE_OPEN_REPARSE_POINT | FILE_OPEN_FOR_BACKUP_INTENT);
1199 if (!NT_SUCCESS(status)) {
1200 winnt_warning(status, L"Can't open \"%ls\"", current_path(ctx));
1205 WARNING("Overriding conflicting short name; path=\"%ls\"",
1209 /* Try to remove the short name on the conflicting file. */
1212 status = (*func_NtSetInformationFile)(h, &ctx->iosb, info, bufsize,
1213 FileShortNameInformation);
1215 if (status == STATUS_INVALID_PARAMETER && !retried) {
1217 /* Microsoft forgot to make it possible to remove short names
1218 * until Windows 7. Oops. Use a random short name instead. */
1220 info->FileNameLength = 12 * sizeof(wchar_t);
1221 for (int i = 0; i < 8; i++)
1222 info->FileName[i] = 'A' + (rand() % 26);
1223 info->FileName[8] = L'.';
1224 info->FileName[9] = L'W';
1225 info->FileName[10] = L'L';
1226 info->FileName[11] = L'B';
1227 info->FileName[12] = L'\0';
1233 build_extraction_path(dentry, ctx);
1237 /* Set the short name on the open file @h which has been created at the location
1238 * indicated by @dentry.
1240 * Note that this may add, change, or remove the short name.
1242 * @h must be opened with DELETE access.
1244 * Returns 0 or WIMLIB_ERR_SET_SHORT_NAME. The latter only happens in
1245 * STRICT_SHORT_NAMES mode.
1248 set_short_name(HANDLE h, const struct wim_dentry *dentry,
1249 struct win32_apply_ctx *ctx)
1252 if (!ctx->common.supported_features.short_names)
1256 * Note: The size of the FILE_NAME_INFORMATION buffer must be such that
1257 * FileName contains at least 2 wide characters (4 bytes). Otherwise,
1258 * NtSetInformationFile() will return STATUS_INFO_LENGTH_MISMATCH. This
1259 * is despite the fact that FileNameLength can validly be 0 or 2 bytes,
1260 * with the former case being removing the existing short name if
1261 * present, rather than setting one.
1263 * The null terminator is seemingly optional, but to be safe we include
1264 * space for it and zero all unused space.
1267 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1268 max(dentry->d_short_name_nbytes, sizeof(wchar_t)) +
1270 u8 buf[bufsize] _aligned_attribute(8);
1271 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1273 bool tried_to_remove_existing = false;
1275 memset(buf, 0, bufsize);
1277 info->FileNameLength = dentry->d_short_name_nbytes;
1278 memcpy(info->FileName, dentry->d_short_name, dentry->d_short_name_nbytes);
1281 status = (*func_NtSetInformationFile)(h, &ctx->iosb, info, bufsize,
1282 FileShortNameInformation);
1283 if (NT_SUCCESS(status))
1286 if (status == STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME) {
1287 if (dentry->d_short_name_nbytes == 0)
1289 if (!ctx->tried_to_enable_short_names) {
1293 ctx->tried_to_enable_short_names = true;
1295 ret = win32_get_drive_path(ctx->common.target,
1299 if (try_to_enable_short_names(volume))
1305 * Short names can conflict in several cases:
1307 * - a file being extracted has a short name conflicting with an
1310 * - a file being extracted has a short name conflicting with another
1311 * file being extracted (possible, but shouldn't happen)
1313 * - a file being extracted has a short name that conflicts with the
1314 * automatically generated short name of a file we previously
1315 * extracted, but failed to set the short name for. Sounds unlikely,
1316 * but this actually does happen fairly often on versions of Windows
1317 * prior to Windows 7 because they do not support removing short names
1320 if (unlikely(status == STATUS_OBJECT_NAME_COLLISION) &&
1321 dentry->d_short_name_nbytes && !tried_to_remove_existing)
1323 tried_to_remove_existing = true;
1324 status = remove_conflicting_short_name(dentry, ctx);
1325 if (NT_SUCCESS(status))
1329 /* By default, failure to set short names is not an error (since short
1330 * names aren't too important anymore...). */
1331 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES)) {
1332 if (dentry->d_short_name_nbytes)
1333 ctx->num_set_short_name_failures++;
1335 ctx->num_remove_short_name_failures++;
1339 winnt_error(status, L"Can't set short name on \"%ls\"", current_path(ctx));
1340 return WIMLIB_ERR_SET_SHORT_NAME;
1344 * A wrapper around NtCreateFile() to make it slightly more usable...
1345 * This uses the path currently constructed in ctx->pathbuf.
1347 * Also, we always specify FILE_OPEN_FOR_BACKUP_INTENT and
1348 * FILE_OPEN_REPARSE_POINT.
1351 do_create_file(PHANDLE FileHandle,
1352 ACCESS_MASK DesiredAccess,
1353 PLARGE_INTEGER AllocationSize,
1354 ULONG FileAttributes,
1355 ULONG CreateDisposition,
1356 ULONG CreateOptions,
1357 struct win32_apply_ctx *ctx)
1359 return (*func_NtCreateFile)(FileHandle,
1365 FILE_SHARE_VALID_FLAGS,
1368 FILE_OPEN_FOR_BACKUP_INTENT |
1369 FILE_OPEN_REPARSE_POINT,
1374 /* Like do_create_file(), but builds the extraction path of the @dentry first.
1377 create_file(PHANDLE FileHandle,
1378 ACCESS_MASK DesiredAccess,
1379 PLARGE_INTEGER AllocationSize,
1380 ULONG FileAttributes,
1381 ULONG CreateDisposition,
1382 ULONG CreateOptions,
1383 const struct wim_dentry *dentry,
1384 struct win32_apply_ctx *ctx)
1386 build_extraction_path(dentry, ctx);
1387 return do_create_file(FileHandle,
1397 delete_file_or_stream(struct win32_apply_ctx *ctx)
1401 FILE_DISPOSITION_INFORMATION disposition_info;
1402 FILE_BASIC_INFORMATION basic_info;
1403 bool retried = false;
1405 status = do_create_file(&h,
1410 FILE_NON_DIRECTORY_FILE,
1412 if (unlikely(!NT_SUCCESS(status))) {
1413 winnt_error(status, L"Can't open \"%ls\" for deletion",
1415 return WIMLIB_ERR_OPEN;
1419 disposition_info.DoDeleteFile = TRUE;
1420 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1422 sizeof(disposition_info),
1423 FileDispositionInformation);
1425 if (likely(NT_SUCCESS(status)))
1428 if (status == STATUS_CANNOT_DELETE && !retried) {
1429 /* Clear file attributes and try again. This is necessary for
1430 * FILE_ATTRIBUTE_READONLY files. */
1431 status = do_create_file(&h,
1432 FILE_WRITE_ATTRIBUTES | DELETE,
1436 FILE_NON_DIRECTORY_FILE,
1438 if (!NT_SUCCESS(status)) {
1440 L"Can't open \"%ls\" to reset attributes",
1442 return WIMLIB_ERR_OPEN;
1444 memset(&basic_info, 0, sizeof(basic_info));
1445 basic_info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1446 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1449 FileBasicInformation);
1450 if (!NT_SUCCESS(status)) {
1452 L"Can't reset file attributes on \"%ls\"",
1455 return WIMLIB_ERR_SET_ATTRIBUTES;
1460 winnt_error(status, L"Can't delete \"%ls\"", current_path(ctx));
1461 return WIMLIB_ERR_OPEN;
1465 * Create a nondirectory file or named data stream at the current path,
1466 * superseding any that already exists at that path. If successful, return an
1467 * open handle to the file or named data stream.
1470 supersede_file_or_stream(struct win32_apply_ctx *ctx, HANDLE *h_ret)
1473 bool retried = false;
1475 /* FILE_ATTRIBUTE_SYSTEM is needed to ensure that
1476 * FILE_ATTRIBUTE_ENCRYPTED doesn't get set before we want it to be. */
1478 status = do_create_file(h_ret,
1479 GENERIC_READ | GENERIC_WRITE | DELETE,
1481 FILE_ATTRIBUTE_SYSTEM,
1483 FILE_NON_DIRECTORY_FILE,
1485 if (likely(NT_SUCCESS(status)))
1488 /* STATUS_OBJECT_NAME_COLLISION means that the file or stream already
1489 * exists. Delete the existing file or stream, then try again.
1491 * Note: we don't use FILE_OVERWRITE_IF or FILE_SUPERSEDE because of
1492 * problems with certain file attributes, especially
1493 * FILE_ATTRIBUTE_ENCRYPTED. FILE_SUPERSEDE is also broken in the
1494 * Windows PE ramdisk. */
1495 if (status == STATUS_OBJECT_NAME_COLLISION && !retried) {
1496 int ret = delete_file_or_stream(ctx);
1502 winnt_error(status, L"Can't create \"%ls\"", current_path(ctx));
1503 return WIMLIB_ERR_OPEN;
1506 /* Set the reparse point @rpbuf of length @rpbuflen on the extracted file
1507 * corresponding to the WIM dentry @dentry. */
1509 do_set_reparse_point(const struct wim_dentry *dentry,
1510 const struct reparse_buffer_disk *rpbuf, u16 rpbuflen,
1511 struct win32_apply_ctx *ctx)
1516 status = create_file(&h, GENERIC_WRITE, NULL,
1517 0, FILE_OPEN, 0, dentry, ctx);
1518 if (!NT_SUCCESS(status))
1521 status = (*func_NtFsControlFile)(h, NULL, NULL, NULL,
1522 &ctx->iosb, FSCTL_SET_REPARSE_POINT,
1523 (void *)rpbuf, rpbuflen,
1527 if (NT_SUCCESS(status))
1530 /* On Windows, by default only the Administrator can create symbolic
1531 * links for some reason. By default we just issue a warning if this
1532 * appears to be the problem. Use WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS
1533 * to get a hard error. */
1534 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS)
1535 && (status == STATUS_PRIVILEGE_NOT_HELD ||
1536 status == STATUS_ACCESS_DENIED)
1537 && (dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1538 dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1540 WARNING("Can't create symbolic link \"%ls\"! \n"
1541 " (Need Administrator rights, or at least "
1543 " SeCreateSymbolicLink privilege.)",
1549 winnt_error(status, L"Can't set reparse data on \"%ls\"",
1551 return WIMLIB_ERR_SET_REPARSE_DATA;
1555 * Create empty named data streams and potentially a reparse point for the
1556 * specified file, if any.
1558 * Since these won't have blob descriptors, they won't show up in the call to
1559 * extract_blob_list(). Hence the need for the special case.
1562 create_empty_streams(const struct wim_dentry *dentry,
1563 struct win32_apply_ctx *ctx)
1565 const struct wim_inode *inode = dentry->d_inode;
1568 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1569 const struct wim_inode_stream *strm = &inode->i_streams[i];
1571 if (stream_blob_resolved(strm) != NULL)
1574 if (strm->stream_type == STREAM_TYPE_REPARSE_POINT &&
1575 ctx->common.supported_features.reparse_points)
1577 u8 buf[REPARSE_DATA_OFFSET] _aligned_attribute(8);
1578 struct reparse_buffer_disk *rpbuf =
1579 (struct reparse_buffer_disk *)buf;
1580 complete_reparse_point(rpbuf, inode, 0);
1581 ret = do_set_reparse_point(dentry, rpbuf,
1582 REPARSE_DATA_OFFSET, ctx);
1585 } else if (stream_is_named_data_stream(strm) &&
1586 ctx->common.supported_features.named_data_streams)
1590 build_extraction_path_with_ads(dentry, ctx,
1592 utf16le_len_chars(strm->stream_name));
1593 ret = supersede_file_or_stream(ctx, &h);
1595 build_extraction_path(dentry, ctx);
1607 * Creates the directory named by @dentry, or uses an existing directory at that
1608 * location. If necessary, sets the short name and/or fixes compression and
1609 * encryption attributes.
1611 * Returns 0, WIMLIB_ERR_MKDIR, or WIMLIB_ERR_SET_SHORT_NAME.
1614 create_directory(const struct wim_dentry *dentry, struct win32_apply_ctx *ctx)
1621 /* DELETE is needed for set_short_name(); GENERIC_READ and GENERIC_WRITE
1622 * are needed for adjust_compression_attribute(). */
1623 perms = GENERIC_READ | GENERIC_WRITE;
1624 if (!dentry_is_root(dentry))
1627 /* FILE_ATTRIBUTE_SYSTEM is needed to ensure that
1628 * FILE_ATTRIBUTE_ENCRYPTED doesn't get set before we want it to be. */
1629 status = create_file(&h, perms, NULL, FILE_ATTRIBUTE_SYSTEM,
1630 FILE_OPEN_IF, FILE_DIRECTORY_FILE, dentry, ctx);
1631 if (!NT_SUCCESS(status)) {
1632 winnt_error(status, L"Can't create directory \"%ls\"",
1634 return WIMLIB_ERR_MKDIR;
1637 if (ctx->iosb.Information == FILE_OPENED) {
1638 /* If we opened an existing directory, try to clear its file
1639 * attributes. As far as I know, this only actually makes a
1640 * difference in the case where a FILE_ATTRIBUTE_READONLY
1641 * directory has a named data stream which needs to be
1642 * extracted. You cannot create a named data stream of such a
1643 * directory, even though this contradicts Microsoft's
1644 * documentation for FILE_ATTRIBUTE_READONLY which states it is
1645 * not honored for directories! */
1646 FILE_BASIC_INFORMATION basic_info = { .FileAttributes = FILE_ATTRIBUTE_NORMAL };
1647 (*func_NtSetInformationFile)(h, &ctx->iosb, &basic_info,
1648 sizeof(basic_info), FileBasicInformation);
1651 if (!dentry_is_root(dentry)) {
1652 ret = set_short_name(h, dentry, ctx);
1657 ret = adjust_compression_attribute(h, dentry, ctx);
1664 * Create all the directories being extracted, other than the target directory
1667 * Note: we don't honor directory hard links. However, we don't allow them to
1668 * exist in WIM images anyway (see inode_fixup.c).
1671 create_directories(struct list_head *dentry_list,
1672 struct win32_apply_ctx *ctx)
1674 const struct wim_dentry *dentry;
1677 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1679 if (!(dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY))
1682 /* Note: Here we include files with
1683 * FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT, but we
1684 * wait until later to actually set the reparse data. */
1686 ret = create_directory(dentry, ctx);
1689 ret = create_empty_streams(dentry, ctx);
1691 ret = check_apply_error(dentry, ctx, ret);
1695 ret = report_file_created(&ctx->common);
1703 * Creates the nondirectory file named by @dentry.
1705 * On success, returns an open handle to the file in @h_ret, with GENERIC_READ,
1706 * GENERIC_WRITE, and DELETE access. Also, the path to the file will be saved
1707 * in ctx->pathbuf. On failure, returns an error code.
1710 create_nondirectory_inode(HANDLE *h_ret, const struct wim_dentry *dentry,
1711 struct win32_apply_ctx *ctx)
1716 build_extraction_path(dentry, ctx);
1718 ret = supersede_file_or_stream(ctx, &h);
1722 ret = adjust_compression_attribute(h, dentry, ctx);
1726 ret = create_empty_streams(dentry, ctx);
1739 /* Creates a hard link at the location named by @dentry to the file represented
1740 * by the open handle @h. Or, if the target volume does not support hard links,
1741 * create a separate file instead. */
1743 create_link(HANDLE h, const struct wim_dentry *dentry,
1744 struct win32_apply_ctx *ctx)
1746 if (ctx->common.supported_features.hard_links) {
1748 build_extraction_path(dentry, ctx);
1750 size_t bufsize = offsetof(FILE_LINK_INFORMATION, FileName) +
1751 ctx->pathbuf.Length + sizeof(wchar_t);
1752 u8 buf[bufsize] _aligned_attribute(8);
1753 FILE_LINK_INFORMATION *info = (FILE_LINK_INFORMATION *)buf;
1756 info->ReplaceIfExists = TRUE;
1757 info->RootDirectory = ctx->attr.RootDirectory;
1758 info->FileNameLength = ctx->pathbuf.Length;
1759 memcpy(info->FileName, ctx->pathbuf.Buffer, ctx->pathbuf.Length);
1760 info->FileName[info->FileNameLength / 2] = L'\0';
1762 /* Note: the null terminator isn't actually necessary,
1763 * but if you don't add the extra character, you get
1764 * STATUS_INFO_LENGTH_MISMATCH when FileNameLength
1765 * happens to be 2 */
1767 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1769 FileLinkInformation);
1770 if (NT_SUCCESS(status))
1772 winnt_error(status, L"Failed to create link \"%ls\"",
1774 return WIMLIB_ERR_LINK;
1779 ret = create_nondirectory_inode(&h2, dentry, ctx);
1783 (*func_NtClose)(h2);
1788 /* Given an inode (represented by the open handle @h) for which one link has
1789 * been created (named by @first_dentry), create the other links.
1791 * Or, if the target volume does not support hard links, create separate files.
1793 * Note: This uses ctx->pathbuf and does not reset it.
1796 create_links(HANDLE h, const struct wim_dentry *first_dentry,
1797 struct win32_apply_ctx *ctx)
1799 const struct wim_inode *inode = first_dentry->d_inode;
1800 const struct wim_dentry *dentry;
1803 inode_for_each_extraction_alias(dentry, inode) {
1804 if (dentry != first_dentry) {
1805 ret = create_link(h, dentry, ctx);
1813 /* Create a nondirectory file, including all links. */
1815 create_nondirectory(struct wim_inode *inode, struct win32_apply_ctx *ctx)
1817 struct wim_dentry *first_dentry;
1821 first_dentry = first_extraction_alias(inode);
1823 /* Create first link. */
1824 ret = create_nondirectory_inode(&h, first_dentry, ctx);
1828 /* Set short name. */
1829 ret = set_short_name(h, first_dentry, ctx);
1831 /* Create additional links, OR if hard links are not supported just
1832 * create more files. */
1834 ret = create_links(h, first_dentry, ctx);
1836 /* "WIMBoot" extraction: set external backing by the WIM file if needed. */
1837 if (!ret && unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
1838 ret = set_backed_from_wim(h, inode, ctx);
1844 /* Create all the nondirectory files being extracted, including all aliases
1847 create_nondirectories(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1849 struct wim_dentry *dentry;
1850 struct wim_inode *inode;
1853 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1854 inode = dentry->d_inode;
1855 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1857 /* Call create_nondirectory() only once per inode */
1858 if (dentry == inode_first_extraction_dentry(inode)) {
1859 ret = create_nondirectory(inode, ctx);
1860 ret = check_apply_error(dentry, ctx, ret);
1864 ret = report_file_created(&ctx->common);
1872 close_handles(struct win32_apply_ctx *ctx)
1874 for (unsigned i = 0; i < ctx->num_open_handles; i++)
1875 (*func_NtClose)(ctx->open_handles[i]);
1878 /* Prepare to read the next blob, which has size @blob_size, into an in-memory
1881 prepare_data_buffer(struct win32_apply_ctx *ctx, u64 blob_size)
1883 if (blob_size > ctx->data_buffer_size) {
1884 /* Larger buffer needed. */
1886 if ((size_t)blob_size != blob_size)
1888 new_buffer = REALLOC(ctx->data_buffer, blob_size);
1891 ctx->data_buffer = new_buffer;
1892 ctx->data_buffer_size = blob_size;
1894 /* On the first call this changes data_buffer_ptr from NULL, which tells
1895 * extract_chunk() that the data buffer needs to be filled while reading
1896 * the stream data. */
1897 ctx->data_buffer_ptr = ctx->data_buffer;
1902 begin_extract_blob_instance(const struct blob_descriptor *blob,
1903 struct wim_dentry *dentry,
1904 const struct wim_inode_stream *strm,
1905 struct win32_apply_ctx *ctx)
1907 FILE_ALLOCATION_INFORMATION alloc_info;
1911 if (unlikely(strm->stream_type == STREAM_TYPE_REPARSE_POINT)) {
1912 /* We can't write the reparse point stream directly; we must set
1913 * it with FSCTL_SET_REPARSE_POINT, which requires that all the
1914 * data be available. So, stage the data in a buffer. */
1915 if (!prepare_data_buffer(ctx, blob->size))
1916 return WIMLIB_ERR_NOMEM;
1917 list_add_tail(&dentry->d_tmp_list, &ctx->reparse_dentries);
1921 if (unlikely(strm->stream_type == STREAM_TYPE_EFSRPC_RAW_DATA)) {
1922 /* We can't write encrypted files directly; we must use
1923 * WriteEncryptedFileRaw(), which requires providing the data
1924 * through a callback function. This can't easily be combined
1925 * with our own callback-based approach.
1927 * The current workaround is to simply read the blob into memory
1928 * and write the encrypted file from that.
1930 * TODO: This isn't sufficient for extremely large encrypted
1931 * files. Perhaps we should create an extra thread to write
1933 if (!prepare_data_buffer(ctx, blob->size))
1934 return WIMLIB_ERR_NOMEM;
1935 list_add_tail(&dentry->d_tmp_list, &ctx->encrypted_dentries);
1939 /* It's a data stream (may be unnamed or named). */
1940 wimlib_assert(strm->stream_type == STREAM_TYPE_DATA);
1942 if (ctx->num_open_handles == MAX_OPEN_FILES) {
1943 /* XXX: Fix this. But because of the checks in
1944 * extract_blob_list(), this can now only happen on a filesystem
1945 * that does not support hard links. */
1946 ERROR("Can't extract data: too many open files!");
1947 return WIMLIB_ERR_UNSUPPORTED;
1951 if (unlikely(stream_is_named(strm))) {
1952 build_extraction_path_with_ads(dentry, ctx,
1954 utf16le_len_chars(strm->stream_name));
1956 build_extraction_path(dentry, ctx);
1960 /* Open a new handle */
1961 status = do_create_file(&h,
1962 FILE_WRITE_DATA | SYNCHRONIZE,
1963 NULL, 0, FILE_OPEN_IF,
1964 FILE_SEQUENTIAL_ONLY |
1965 FILE_SYNCHRONOUS_IO_NONALERT,
1967 if (!NT_SUCCESS(status)) {
1968 winnt_error(status, L"Can't open \"%ls\" for writing",
1970 return WIMLIB_ERR_OPEN;
1973 ctx->open_handles[ctx->num_open_handles++] = h;
1975 /* Allocate space for the data. */
1976 alloc_info.AllocationSize.QuadPart = blob->size;
1977 (*func_NtSetInformationFile)(h, &ctx->iosb,
1978 &alloc_info, sizeof(alloc_info),
1979 FileAllocationInformation);
1983 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1984 * pointer to the suffix of the path that begins with the device directly, such
1985 * as e:\Windows\System32. */
1986 static const wchar_t *
1987 skip_nt_toplevel_component(const wchar_t *path, size_t path_nchars)
1989 static const wchar_t * const dirs[] = {
1994 const wchar_t * const end = path + path_nchars;
1996 for (size_t i = 0; i < ARRAY_LEN(dirs); i++) {
1997 size_t len = wcslen(dirs[i]);
1998 if (len <= (end - path) && !wmemcmp(path, dirs[i], len)) {
2000 while (path != end && *path == L'\\')
2009 * Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
2010 * pointer to the suffix of the path that is device-relative but possibly with
2011 * leading slashes, such as \Windows\System32.
2013 * The path has an explicit length and is not necessarily null terminated.
2015 static const wchar_t *
2016 get_device_relative_path(const wchar_t *path, size_t path_nchars)
2018 const wchar_t * const orig_path = path;
2019 const wchar_t * const end = path + path_nchars;
2021 path = skip_nt_toplevel_component(path, path_nchars);
2022 if (path == orig_path)
2025 while (path != end && *path != L'\\')
2032 * Given a reparse point buffer for an inode for which the absolute link target
2033 * was relativized when it was archived, de-relative the link target to be
2034 * consistent with the actual extraction location.
2037 try_rpfix(struct reparse_buffer_disk *rpbuf, u16 *rpbuflen_p,
2038 struct win32_apply_ctx *ctx)
2040 struct link_reparse_point link;
2041 size_t orig_subst_name_nchars;
2042 const wchar_t *relpath;
2043 size_t relpath_nchars;
2044 size_t target_ntpath_nchars;
2045 size_t fixed_subst_name_nchars;
2046 const wchar_t *fixed_print_name;
2047 size_t fixed_print_name_nchars;
2049 /* Do nothing if the reparse data is invalid. */
2050 if (parse_link_reparse_point(rpbuf, *rpbuflen_p, &link))
2053 /* Do nothing if the reparse point is a relative symbolic link. */
2054 if (link_is_relative_symlink(&link))
2057 /* Build the new substitute name from the NT namespace path to the
2058 * target directory, then a path separator, then the "device relative"
2059 * part of the old substitute name. */
2061 orig_subst_name_nchars = link.substitute_name_nbytes / sizeof(wchar_t);
2063 relpath = get_device_relative_path(link.substitute_name,
2064 orig_subst_name_nchars);
2065 relpath_nchars = orig_subst_name_nchars -
2066 (relpath - link.substitute_name);
2068 target_ntpath_nchars = ctx->target_ntpath.Length / sizeof(wchar_t);
2070 fixed_subst_name_nchars = target_ntpath_nchars + relpath_nchars;
2072 wchar_t fixed_subst_name[fixed_subst_name_nchars];
2074 wmemcpy(fixed_subst_name, ctx->target_ntpath.Buffer, target_ntpath_nchars);
2075 wmemcpy(&fixed_subst_name[target_ntpath_nchars], relpath, relpath_nchars);
2076 /* Doesn't need to be null-terminated. */
2078 /* Print name should be Win32, but not all NT names can even be
2079 * translated to Win32 names. But we can at least delete the top-level
2080 * directory, such as \??\, and this will have the expected result in
2081 * the usual case. */
2082 fixed_print_name = skip_nt_toplevel_component(fixed_subst_name,
2083 fixed_subst_name_nchars);
2084 fixed_print_name_nchars = fixed_subst_name_nchars - (fixed_print_name -
2087 link.substitute_name = fixed_subst_name;
2088 link.substitute_name_nbytes = fixed_subst_name_nchars * sizeof(wchar_t);
2089 link.print_name = (wchar_t *)fixed_print_name;
2090 link.print_name_nbytes = fixed_print_name_nchars * sizeof(wchar_t);
2091 make_link_reparse_point(&link, rpbuf, rpbuflen_p);
2094 /* Sets the reparse point on the specified file. This handles "fixing" the
2095 * targets of absolute symbolic links and junctions if WIMLIB_EXTRACT_FLAG_RPFIX
2098 set_reparse_point(const struct wim_dentry *dentry,
2099 const struct reparse_buffer_disk *rpbuf, u16 rpbuflen,
2100 struct win32_apply_ctx *ctx)
2102 if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
2103 && !(dentry->d_inode->i_rp_flags & WIM_RP_FLAG_NOT_FIXED))
2105 memcpy(&ctx->rpfixbuf, rpbuf, rpbuflen);
2106 try_rpfix(&ctx->rpfixbuf, &rpbuflen, ctx);
2107 rpbuf = &ctx->rpfixbuf;
2109 return do_set_reparse_point(dentry, rpbuf, rpbuflen, ctx);
2113 /* Import the next block of raw encrypted data */
2115 import_encrypted_data(PBYTE pbData, PVOID pvCallbackContext, PULONG Length)
2117 struct win32_apply_ctx *ctx = pvCallbackContext;
2120 copy_len = min(ctx->encrypted_size - ctx->encrypted_offset, *Length);
2121 memcpy(pbData, &ctx->data_buffer[ctx->encrypted_offset], copy_len);
2122 ctx->encrypted_offset += copy_len;
2124 return ERROR_SUCCESS;
2128 * Write the raw encrypted data to the already-created file (or directory)
2129 * corresponding to @dentry.
2131 * The raw encrypted data is provided in ctx->data_buffer, and its size is
2132 * ctx->encrypted_size.
2134 * This function may close the target directory, in which case the caller needs
2135 * to re-open it if needed.
2138 extract_encrypted_file(const struct wim_dentry *dentry,
2139 struct win32_apply_ctx *ctx)
2146 /* Temporarily build a Win32 path for OpenEncryptedFileRaw() */
2147 build_win32_extraction_path(dentry, ctx);
2149 flags = CREATE_FOR_IMPORT | OVERWRITE_HIDDEN;
2150 if (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
2151 flags |= CREATE_FOR_DIR;
2155 err = OpenEncryptedFileRaw(ctx->pathbuf.Buffer, flags, &rawctx);
2156 if (err == ERROR_SHARING_VIOLATION && !retried) {
2157 /* This can be caused by the handle we have open to the target
2158 * directory. Try closing it temporarily. */
2159 close_target_directory(ctx);
2164 /* Restore the NT namespace path */
2165 build_extraction_path(dentry, ctx);
2167 if (err != ERROR_SUCCESS) {
2168 win32_error(err, L"Can't open \"%ls\" for encrypted import",
2170 return WIMLIB_ERR_OPEN;
2173 ctx->encrypted_offset = 0;
2175 err = WriteEncryptedFileRaw(import_encrypted_data, ctx, rawctx);
2177 CloseEncryptedFileRaw(rawctx);
2179 if (err != ERROR_SUCCESS) {
2180 win32_error(err, L"Can't import encrypted file \"%ls\"",
2182 return WIMLIB_ERR_WRITE;
2188 /* Called when starting to read a blob for extraction on Windows */
2190 begin_extract_blob(struct blob_descriptor *blob, void *_ctx)
2192 struct win32_apply_ctx *ctx = _ctx;
2193 const struct blob_extraction_target *targets = blob_extraction_targets(blob);
2196 ctx->num_open_handles = 0;
2197 ctx->data_buffer_ptr = NULL;
2198 INIT_LIST_HEAD(&ctx->reparse_dentries);
2199 INIT_LIST_HEAD(&ctx->encrypted_dentries);
2201 for (u32 i = 0; i < blob->out_refcnt; i++) {
2202 const struct wim_inode *inode = targets[i].inode;
2203 const struct wim_inode_stream *strm = targets[i].stream;
2204 struct wim_dentry *dentry;
2206 /* A copy of the blob needs to be extracted to @inode. */
2208 if (ctx->common.supported_features.hard_links) {
2209 dentry = inode_first_extraction_dentry(inode);
2210 ret = begin_extract_blob_instance(blob, dentry, strm, ctx);
2211 ret = check_apply_error(dentry, ctx, ret);
2215 /* Hard links not supported. Extract the blob
2216 * separately to each alias of the inode. */
2217 inode_for_each_extraction_alias(dentry, inode) {
2218 ret = begin_extract_blob_instance(blob, dentry, strm, ctx);
2219 ret = check_apply_error(dentry, ctx, ret);
2233 /* Called when the next chunk of a blob has been read for extraction on Windows
2236 extract_chunk(const void *chunk, size_t size, void *_ctx)
2238 struct win32_apply_ctx *ctx = _ctx;
2240 /* Write the data chunk to each open handle */
2241 for (unsigned i = 0; i < ctx->num_open_handles; i++) {
2242 u8 *bufptr = (u8 *)chunk;
2243 size_t bytes_remaining = size;
2245 while (bytes_remaining) {
2246 ULONG count = min(0xFFFFFFFF, bytes_remaining);
2248 status = (*func_NtWriteFile)(ctx->open_handles[i],
2250 &ctx->iosb, bufptr, count,
2252 if (!NT_SUCCESS(status)) {
2253 winnt_error(status, L"Error writing data to target volume");
2254 return WIMLIB_ERR_WRITE;
2256 bufptr += ctx->iosb.Information;
2257 bytes_remaining -= ctx->iosb.Information;
2261 /* Copy the data chunk into the buffer (if needed) */
2262 if (ctx->data_buffer_ptr)
2263 ctx->data_buffer_ptr = mempcpy(ctx->data_buffer_ptr,
2269 get_system_compression_format(int extract_flags)
2271 if (extract_flags & WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS4K)
2272 return FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K;
2274 if (extract_flags & WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS8K)
2275 return FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS8K;
2277 if (extract_flags & WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS16K)
2278 return FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS16K;
2280 return FILE_PROVIDER_COMPRESSION_FORMAT_LZX;
2284 static const wchar_t *
2285 get_system_compression_format_string(int format)
2288 case FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K:
2290 case FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS8K:
2292 case FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS16K:
2293 return L"XPRESS16K";
2300 set_system_compression(HANDLE h, int format)
2303 IO_STATUS_BLOCK iosb;
2305 struct wof_external_info wof_info;
2306 struct file_provider_external_info file_info;
2309 .version = WOF_CURRENT_VERSION,
2310 .provider = WOF_PROVIDER_FILE,
2313 .version = FILE_PROVIDER_CURRENT_VERSION,
2314 .compression_format = format,
2318 /* We intentionally use NtFsControlFile() rather than DeviceIoControl()
2319 * here because the "compressing this object would not save space"
2320 * status code does not map to a valid Win32 error code on older
2321 * versions of Windows (before Windows 10?). This can be a problem if
2322 * the WOFADK driver is being used rather than the regular WOF, since
2323 * WOFADK can be used on older versions of Windows. */
2324 status = (*func_NtFsControlFile)(h, NULL, NULL, NULL, &iosb,
2325 FSCTL_SET_EXTERNAL_BACKING,
2326 &in, sizeof(in), NULL, 0);
2328 if (status == 0xC000046F) /* "Compressing this object would not save space." */
2329 return STATUS_SUCCESS;
2334 /* Hard-coded list of files which the Windows bootloader may need to access
2335 * before the WOF driver has been loaded. */
2336 static wchar_t *bootloader_pattern_strings[] = {
2339 L"\\Windows\\AppPatch\\drvmain.sdb",
2340 L"\\Windows\\Boot\\DVD\\*",
2341 L"\\Windows\\Boot\\EFI\\*",
2342 L"\\Windows\\bootstat.dat",
2343 L"\\Windows\\Fonts\\vgaoem.fon",
2344 L"\\Windows\\Fonts\\vgasys.fon",
2345 L"\\Windows\\INF\\errata.inf",
2346 L"\\Windows\\System32\\config\\*",
2347 L"\\Windows\\System32\\ntkrnlpa.exe",
2348 L"\\Windows\\System32\\ntoskrnl.exe",
2349 L"\\Windows\\System32\\bootvid.dll",
2350 L"\\Windows\\System32\\ci.dll",
2351 L"\\Windows\\System32\\hal*.dll",
2352 L"\\Windows\\System32\\mcupdate_AuthenticAMD.dll",
2353 L"\\Windows\\System32\\mcupdate_GenuineIntel.dll",
2354 L"\\Windows\\System32\\pshed.dll",
2355 L"\\Windows\\System32\\apisetschema.dll",
2356 L"\\Windows\\System32\\api-ms-win*.dll",
2357 L"\\Windows\\System32\\ext-ms-win*.dll",
2358 L"\\Windows\\System32\\KernelBase.dll",
2359 L"\\Windows\\System32\\drivers\\*.sys",
2360 L"\\Windows\\System32\\*.nls",
2361 L"\\Windows\\System32\\kbd*.dll",
2362 L"\\Windows\\System32\\kd*.dll",
2363 L"\\Windows\\System32\\clfs.sys",
2364 L"\\Windows\\System32\\CodeIntegrity\\driver.stl",
2367 static const struct string_set bootloader_patterns = {
2368 .strings = bootloader_pattern_strings,
2369 .num_strings = ARRAY_LEN(bootloader_pattern_strings),
2373 set_system_compression_on_inode(struct wim_inode *inode, int format,
2374 struct win32_apply_ctx *ctx)
2376 bool retried = false;
2380 /* If it may be needed for compatibility with the Windows bootloader,
2381 * force this file to XPRESS4K or uncompressed format. The bootloader
2382 * of Windows 10 supports XPRESS4K only; older versions don't support
2383 * system compression at all. */
2384 if (!is_image_windows_10_or_later(ctx) ||
2385 format != FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K)
2387 /* We need to check the patterns against every name of the
2388 * inode, in case any of them match. */
2389 struct wim_dentry *dentry;
2390 inode_for_each_extraction_alias(dentry, inode) {
2394 if (calculate_dentry_full_path(dentry)) {
2395 ERROR("Unable to compute file path!");
2396 return STATUS_NO_MEMORY;
2399 incompatible = match_pattern_list(dentry->d_full_path,
2400 &bootloader_patterns);
2401 FREE(dentry->d_full_path);
2402 dentry->d_full_path = NULL;
2407 warned = (ctx->num_system_compression_exclusions++ > 0);
2409 if (is_image_windows_10_or_later(ctx)) {
2410 /* Force to XPRESS4K */
2412 WARNING("For compatibility with the "
2413 "Windows bootloader, some "
2416 "using the XPRESS4K format "
2417 "instead of the %"TS" format\n"
2419 get_system_compression_format_string(format));
2421 format = FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K;
2424 /* Force to uncompressed */
2426 WARNING("For compatibility with the "
2427 "Windows bootloader, some "
2429 " be compressed with"
2430 " system compression "
2431 "(\"compacted\").");
2433 return STATUS_SUCCESS;
2439 /* Open the extracted file. */
2440 status = create_file(&h, GENERIC_READ | GENERIC_WRITE, NULL,
2442 inode_first_extraction_dentry(inode), ctx);
2444 if (!NT_SUCCESS(status))
2447 /* Compress the file. If the attempt fails with "invalid device
2448 * request", then attach wof.sys (or wofadk.sys) and retry. */
2449 status = set_system_compression(h, format);
2450 if (unlikely(status == STATUS_INVALID_DEVICE_REQUEST && !retried)) {
2451 wchar_t drive_path[7];
2452 if (!win32_get_drive_path(ctx->common.target, drive_path) &&
2453 win32_try_to_attach_wof(drive_path + 4)) {
2464 * This function is called when doing a "compact-mode" extraction and we just
2465 * finished extracting a blob to one or more locations. For each location that
2466 * was the unnamed data stream of a file, this function compresses the
2467 * corresponding file using System Compression, if allowed.
2469 * Note: we're doing the compression immediately after extracting the data
2470 * rather than during a separate compression pass. This way should be faster
2471 * since the operating system should still have the file's data cached.
2473 * Note: we're having the operating system do the compression, which is not
2474 * ideal because wimlib could create the compressed data faster and more
2475 * efficiently (the compressed data format is identical to a WIM resource). But
2476 * we seemingly don't have a choice because WOF prevents applications from
2477 * creating its reparse points.
2480 handle_system_compression(struct blob_descriptor *blob, struct win32_apply_ctx *ctx)
2482 const struct blob_extraction_target *targets = blob_extraction_targets(blob);
2484 const int format = get_system_compression_format(ctx->common.extract_flags);
2486 for (u32 i = 0; i < blob->out_refcnt; i++) {
2487 struct wim_inode *inode = targets[i].inode;
2488 struct wim_inode_stream *strm = targets[i].stream;
2491 if (!stream_is_unnamed_data_stream(strm))
2494 if (will_externally_back_inode(inode, ctx, NULL, false) != 0)
2497 status = set_system_compression_on_inode(inode, format, ctx);
2498 if (likely(NT_SUCCESS(status)))
2501 if (status == STATUS_INVALID_DEVICE_REQUEST) {
2503 "The request to compress the extracted files using System Compression\n"
2504 " will not be honored because the operating system or target volume\n"
2505 " does not support it. System Compression is only supported on\n"
2506 " Windows 10 and later, and only on NTFS volumes.");
2507 ctx->common.extract_flags &= ~COMPACT_FLAGS;
2511 ctx->num_system_compression_failures++;
2512 if (ctx->num_system_compression_failures < 10) {
2513 winnt_warning(status, L"\"%ls\": Failed to compress "
2514 "extracted file using System Compression",
2516 } else if (ctx->num_system_compression_failures == 10) {
2517 WARNING("Suppressing further warnings about "
2518 "System Compression failures.");
2523 /* Called when a blob has been fully read for extraction on Windows */
2525 end_extract_blob(struct blob_descriptor *blob, int status, void *_ctx)
2527 struct win32_apply_ctx *ctx = _ctx;
2529 const struct wim_dentry *dentry;
2536 if (unlikely(ctx->common.extract_flags & COMPACT_FLAGS))
2537 handle_system_compression(blob, ctx);
2539 if (likely(!ctx->data_buffer_ptr))
2542 if (!list_empty(&ctx->reparse_dentries)) {
2543 if (blob->size > REPARSE_DATA_MAX_SIZE) {
2544 dentry = list_first_entry(&ctx->reparse_dentries,
2545 struct wim_dentry, d_tmp_list);
2546 build_extraction_path(dentry, ctx);
2547 ERROR("Reparse data of \"%ls\" has size "
2548 "%"PRIu64" bytes (exceeds %u bytes)",
2549 current_path(ctx), blob->size,
2550 REPARSE_DATA_MAX_SIZE);
2551 ret = WIMLIB_ERR_INVALID_REPARSE_DATA;
2552 return check_apply_error(dentry, ctx, ret);
2555 memcpy(ctx->rpbuf.rpdata, ctx->data_buffer, blob->size);
2557 list_for_each_entry(dentry, &ctx->reparse_dentries, d_tmp_list) {
2559 /* Reparse point header */
2560 complete_reparse_point(&ctx->rpbuf, dentry->d_inode,
2563 ret = set_reparse_point(dentry, &ctx->rpbuf,
2564 REPARSE_DATA_OFFSET + blob->size,
2566 ret = check_apply_error(dentry, ctx, ret);
2572 if (!list_empty(&ctx->encrypted_dentries)) {
2573 ctx->encrypted_size = blob->size;
2574 list_for_each_entry(dentry, &ctx->encrypted_dentries, d_tmp_list) {
2575 ret = extract_encrypted_file(dentry, ctx);
2576 ret = check_apply_error(dentry, ctx, ret);
2579 /* Re-open the target directory if needed. */
2580 ret = open_target_directory(ctx);
2589 /* Attributes that can't be set directly */
2590 #define SPECIAL_ATTRIBUTES \
2591 (FILE_ATTRIBUTE_REPARSE_POINT | \
2592 FILE_ATTRIBUTE_DIRECTORY | \
2593 FILE_ATTRIBUTE_ENCRYPTED | \
2594 FILE_ATTRIBUTE_SPARSE_FILE | \
2595 FILE_ATTRIBUTE_COMPRESSED)
2597 /* Set the security descriptor @desc, of @desc_size bytes, on the file with open
2600 set_security_descriptor(HANDLE h, const void *_desc,
2601 size_t desc_size, struct win32_apply_ctx *ctx)
2603 SECURITY_INFORMATION info;
2605 SECURITY_DESCRIPTOR_RELATIVE *desc;
2608 * Ideally, we would just pass in the security descriptor buffer as-is.
2609 * But it turns out that Windows can mess up the security descriptor
2610 * even when using the low-level NtSetSecurityObject() function:
2612 * - Windows will clear SE_DACL_AUTO_INHERITED if it is set in the
2613 * passed buffer. To actually get Windows to set
2614 * SE_DACL_AUTO_INHERITED, the application must set the non-persistent
2615 * flag SE_DACL_AUTO_INHERIT_REQ. As usual, Microsoft didn't bother
2616 * to properly document either of these flags. It's unclear how
2617 * important SE_DACL_AUTO_INHERITED actually is, but to be safe we use
2618 * the SE_DACL_AUTO_INHERIT_REQ workaround to set it if needed.
2620 * - The above also applies to the equivalent SACL flags,
2621 * SE_SACL_AUTO_INHERITED and SE_SACL_AUTO_INHERIT_REQ.
2623 * - If the application says that it's setting
2624 * DACL_SECURITY_INFORMATION, then Windows sets SE_DACL_PRESENT in the
2625 * resulting security descriptor, even if the security descriptor the
2626 * application provided did not have a DACL. This seems to be
2627 * unavoidable, since omitting DACL_SECURITY_INFORMATION would cause a
2628 * default DACL to remain. Fortunately, this behavior seems harmless,
2629 * since the resulting DACL will still be "null" --- but it will be
2630 * "the other representation of null".
2632 * - The above also applies to SACL_SECURITY_INFORMATION and
2633 * SE_SACL_PRESENT. Again, it's seemingly unavoidable but "harmless"
2634 * that Windows changes the representation of a "null SACL".
2636 if (likely(desc_size <= STACK_MAX)) {
2637 desc = alloca(desc_size);
2639 desc = MALLOC(desc_size);
2641 return STATUS_NO_MEMORY;
2644 memcpy(desc, _desc, desc_size);
2646 if (likely(desc_size >= 4)) {
2648 if (desc->Control & SE_DACL_AUTO_INHERITED)
2649 desc->Control |= SE_DACL_AUTO_INHERIT_REQ;
2651 if (desc->Control & SE_SACL_AUTO_INHERITED)
2652 desc->Control |= SE_SACL_AUTO_INHERIT_REQ;
2656 * More API insanity. We want to set the entire security descriptor
2657 * as-is. But all available APIs require specifying the specific parts
2658 * of the security descriptor being set. Especially annoying is that
2659 * mandatory integrity labels are part of the SACL, but they aren't set
2660 * with SACL_SECURITY_INFORMATION. Instead, applications must also
2661 * specify LABEL_SECURITY_INFORMATION (Windows Vista, Windows 7) or
2662 * BACKUP_SECURITY_INFORMATION (Windows 8). But at least older versions
2663 * of Windows don't error out if you provide these newer flags...
2665 * Also, if the process isn't running as Administrator, then it probably
2666 * doesn't have SE_RESTORE_PRIVILEGE. In this case, it will always get
2667 * the STATUS_PRIVILEGE_NOT_HELD error by trying to set the SACL, even
2668 * if the security descriptor it provided did not have a SACL. By
2669 * default, in this case we try to recover and set as much of the
2670 * security descriptor as possible --- potentially excluding the DACL, and
2671 * even the owner, as well as the SACL.
2674 info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
2675 DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION |
2676 LABEL_SECURITY_INFORMATION | BACKUP_SECURITY_INFORMATION;
2680 * It's also worth noting that SetFileSecurity() is unusable because it
2681 * doesn't request "backup semantics" when it opens the file internally.
2682 * NtSetSecurityObject() seems to be the best function to use in backup
2683 * applications. (SetSecurityInfo() should also work, but it's harder
2684 * to use and must call NtSetSecurityObject() internally anyway.
2685 * BackupWrite() is theoretically usable as well, but it's inflexible
2686 * and poorly documented.)
2690 status = (*func_NtSetSecurityObject)(h, info, desc);
2691 if (NT_SUCCESS(status))
2692 goto out_maybe_free_desc;
2694 /* Failed to set the requested parts of the security descriptor. If the
2695 * error was permissions-related, try to set fewer parts of the security
2696 * descriptor, unless WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled. */
2697 if ((status == STATUS_PRIVILEGE_NOT_HELD ||
2698 status == STATUS_ACCESS_DENIED) &&
2699 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2701 if (info & SACL_SECURITY_INFORMATION) {
2702 info &= ~(SACL_SECURITY_INFORMATION |
2703 LABEL_SECURITY_INFORMATION |
2704 BACKUP_SECURITY_INFORMATION);
2705 ctx->partial_security_descriptors++;
2708 if (info & DACL_SECURITY_INFORMATION) {
2709 info &= ~DACL_SECURITY_INFORMATION;
2712 if (info & OWNER_SECURITY_INFORMATION) {
2713 info &= ~OWNER_SECURITY_INFORMATION;
2716 /* Nothing left except GROUP, and if we removed it we
2717 * wouldn't have anything at all. */
2720 /* No part of the security descriptor could be set, or
2721 * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled and the full security
2722 * descriptor could not be set. */
2723 if (!(info & SACL_SECURITY_INFORMATION))
2724 ctx->partial_security_descriptors--;
2725 ctx->no_security_descriptors++;
2727 out_maybe_free_desc:
2728 if (unlikely(desc_size > STACK_MAX))
2733 /* Set metadata on the open file @h from the WIM inode @inode. */
2735 do_apply_metadata_to_file(HANDLE h, const struct wim_inode *inode,
2736 struct win32_apply_ctx *ctx)
2738 FILE_BASIC_INFORMATION info;
2741 /* Set security descriptor if present and not in NO_ACLS mode */
2742 if (inode_has_security_descriptor(inode) &&
2743 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
2745 const struct wim_security_data *sd;
2749 sd = wim_get_current_security_data(ctx->common.wim);
2750 desc = sd->descriptors[inode->i_security_id];
2751 desc_size = sd->sizes[inode->i_security_id];
2753 status = set_security_descriptor(h, desc, desc_size, ctx);
2754 if (!NT_SUCCESS(status) &&
2755 (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2758 L"Can't set security descriptor on \"%ls\"",
2760 return WIMLIB_ERR_SET_SECURITY;
2764 /* Set attributes and timestamps */
2765 info.CreationTime.QuadPart = inode->i_creation_time;
2766 info.LastAccessTime.QuadPart = inode->i_last_access_time;
2767 info.LastWriteTime.QuadPart = inode->i_last_write_time;
2768 info.ChangeTime.QuadPart = 0;
2769 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES) {
2770 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
2772 info.FileAttributes = inode->i_attributes & ~SPECIAL_ATTRIBUTES;
2773 if (info.FileAttributes == 0)
2774 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
2777 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
2778 &info, sizeof(info),
2779 FileBasicInformation);
2780 /* On FAT volumes we get STATUS_INVALID_PARAMETER if we try to set
2781 * attributes on the root directory. (Apparently because FAT doesn't
2782 * actually have a place to store those attributes!) */
2783 if (!NT_SUCCESS(status)
2784 && !(status == STATUS_INVALID_PARAMETER &&
2785 dentry_is_root(inode_first_extraction_dentry(inode))))
2787 winnt_error(status, L"Can't set basic metadata on \"%ls\"",
2789 return WIMLIB_ERR_SET_ATTRIBUTES;
2796 apply_metadata_to_file(const struct wim_dentry *dentry,
2797 struct win32_apply_ctx *ctx)
2799 const struct wim_inode *inode = dentry->d_inode;
2805 perms = FILE_WRITE_ATTRIBUTES | WRITE_DAC |
2806 WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
2808 build_extraction_path(dentry, ctx);
2810 /* Open a handle with as many relevant permissions as possible. */
2811 while (!NT_SUCCESS(status = do_create_file(&h, perms, NULL,
2812 0, FILE_OPEN, 0, ctx)))
2814 if (status == STATUS_PRIVILEGE_NOT_HELD ||
2815 status == STATUS_ACCESS_DENIED)
2817 if (perms & ACCESS_SYSTEM_SECURITY) {
2818 perms &= ~ACCESS_SYSTEM_SECURITY;
2821 if (perms & WRITE_DAC) {
2822 perms &= ~WRITE_DAC;
2825 if (perms & WRITE_OWNER) {
2826 perms &= ~WRITE_OWNER;
2830 winnt_error(status, L"Can't open \"%ls\" to set metadata",
2832 return WIMLIB_ERR_OPEN;
2835 ret = do_apply_metadata_to_file(h, inode, ctx);
2843 apply_metadata(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
2845 const struct wim_dentry *dentry;
2848 /* We go in reverse so that metadata is set on all a directory's
2849 * children before the directory itself. This avoids any potential
2850 * problems with attributes, timestamps, or security descriptors. */
2851 list_for_each_entry_reverse(dentry, dentry_list, d_extraction_list_node)
2853 ret = apply_metadata_to_file(dentry, ctx);
2854 ret = check_apply_error(dentry, ctx, ret);
2857 ret = report_file_metadata_applied(&ctx->common);
2864 /* Issue warnings about problems during the extraction for which warnings were
2865 * not already issued (due to the high number of potential warnings if we issued
2866 * them per-file). */
2868 do_warnings(const struct win32_apply_ctx *ctx)
2870 if (ctx->partial_security_descriptors == 0
2871 && ctx->no_security_descriptors == 0
2872 && ctx->num_set_short_name_failures == 0
2874 && ctx->num_remove_short_name_failures == 0
2879 WARNING("Extraction to \"%ls\" complete, but with one or more warnings:",
2880 ctx->common.target);
2881 if (ctx->num_set_short_name_failures) {
2882 WARNING("- Could not set short names on %lu files or directories",
2883 ctx->num_set_short_name_failures);
2886 if (ctx->num_remove_short_name_failures) {
2887 WARNING("- Could not remove short names on %lu files or directories"
2888 " (This is expected on Vista and earlier)",
2889 ctx->num_remove_short_name_failures);
2892 if (ctx->partial_security_descriptors) {
2893 WARNING("- Could only partially set the security descriptor\n"
2894 " on %lu files or directories.",
2895 ctx->partial_security_descriptors);
2897 if (ctx->no_security_descriptors) {
2898 WARNING("- Could not set security descriptor at all\n"
2899 " on %lu files or directories.",
2900 ctx->no_security_descriptors);
2902 if (ctx->partial_security_descriptors || ctx->no_security_descriptors) {
2903 WARNING("To fully restore all security descriptors, run the program\n"
2904 " with Administrator rights.");
2909 count_dentries(const struct list_head *dentry_list)
2911 const struct list_head *cur;
2914 list_for_each(cur, dentry_list)
2920 /* Extract files from a WIM image to a directory on Windows */
2922 win32_extract(struct list_head *dentry_list, struct apply_ctx *_ctx)
2925 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
2928 ret = prepare_target(dentry_list, ctx);
2932 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
2933 ret = start_wimboot_extraction(dentry_list, ctx);
2938 ctx->windows_build_number = xml_get_windows_build_number(ctx->common.wim->xml_info,
2939 ctx->common.wim->current_image);
2941 dentry_count = count_dentries(dentry_list);
2943 ret = start_file_structure_phase(&ctx->common, dentry_count);
2947 ret = create_directories(dentry_list, ctx);
2951 ret = create_nondirectories(dentry_list, ctx);
2955 ret = end_file_structure_phase(&ctx->common);
2959 struct read_blob_callbacks cbs = {
2960 .begin_blob = begin_extract_blob,
2961 .consume_chunk = extract_chunk,
2962 .end_blob = end_extract_blob,
2965 ret = extract_blob_list(&ctx->common, &cbs);
2969 ret = start_file_metadata_phase(&ctx->common, dentry_count);
2973 ret = apply_metadata(dentry_list, ctx);
2977 ret = end_file_metadata_phase(&ctx->common);
2981 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
2982 ret = end_wimboot_extraction(ctx);
2989 close_target_directory(ctx);
2990 if (ctx->target_ntpath.Buffer)
2991 HeapFree(GetProcessHeap(), 0, ctx->target_ntpath.Buffer);
2992 FREE(ctx->pathbuf.Buffer);
2993 FREE(ctx->print_buffer);
2994 FREE(ctx->wimboot.wims);
2995 if (ctx->prepopulate_pats) {
2996 FREE(ctx->prepopulate_pats->strings);
2997 FREE(ctx->prepopulate_pats);
2999 FREE(ctx->mem_prepopulate_pats);
3000 FREE(ctx->data_buffer);
3004 const struct apply_operations win32_apply_ops = {
3006 .get_supported_features = win32_get_supported_features,
3007 .extract = win32_extract,
3008 .will_back_from_wim = win32_will_back_from_wim,
3009 .context_size = sizeof(struct win32_apply_ctx),
3012 #endif /* __WIN32__ */