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 /* Have we tried to enable short name support on the target volume yet?
156 bool tried_to_enable_short_names;
159 /* Get the drive letter from a Windows path, or return the null character if the
160 * path is relative. */
162 get_drive_letter(const wchar_t *path)
164 /* Skip \\?\ prefix */
165 if (!wcsncmp(path, L"\\\\?\\", 4))
168 /* Return drive letter if valid */
169 if (((path[0] >= L'a' && path[0] <= L'z') ||
170 (path[0] >= L'A' && path[0] <= L'Z')) && path[1] == L':')
177 get_vol_flags(const wchar_t *target, DWORD *vol_flags_ret,
178 bool *short_names_supported_ret)
180 wchar_t filesystem_name[MAX_PATH + 1];
182 wchar_t *volume = NULL;
185 *short_names_supported_ret = false;
187 drive[0] = get_drive_letter(target);
195 if (!GetVolumeInformation(volume, NULL, 0, NULL, NULL,
196 vol_flags_ret, filesystem_name,
197 ARRAY_LEN(filesystem_name)))
199 win32_warning(GetLastError(),
200 L"Failed to get volume information for \"%ls\"",
205 if (wcsstr(filesystem_name, L"NTFS")) {
206 /* FILE_SUPPORTS_HARD_LINKS is only supported on Windows 7 and
207 * later. Force it on anyway if filesystem is NTFS. */
208 *vol_flags_ret |= FILE_SUPPORTS_HARD_LINKS;
210 /* There's no volume flag for short names, but according to the
211 * MS documentation they are only user-settable on NTFS. */
212 *short_names_supported_ret = true;
216 static const wchar_t *
217 current_path(struct win32_apply_ctx *ctx);
220 build_extraction_path(const struct wim_dentry *dentry,
221 struct win32_apply_ctx *ctx);
224 report_dentry_apply_error(const struct wim_dentry *dentry,
225 struct win32_apply_ctx *ctx, int ret)
227 build_extraction_path(dentry, ctx);
228 return report_apply_error(&ctx->common, ret, current_path(ctx));
232 check_apply_error(const struct wim_dentry *dentry,
233 struct win32_apply_ctx *ctx, int ret)
236 ret = report_dentry_apply_error(dentry, ctx, ret);
241 win32_get_supported_features(const wchar_t *target,
242 struct wim_features *supported_features)
245 bool short_names_supported;
247 /* Query the features of the target volume. */
249 get_vol_flags(target, &vol_flags, &short_names_supported);
251 supported_features->archive_files = 1;
252 supported_features->hidden_files = 1;
253 supported_features->system_files = 1;
255 if (vol_flags & FILE_FILE_COMPRESSION)
256 supported_features->compressed_files = 1;
258 if (vol_flags & FILE_SUPPORTS_ENCRYPTION) {
259 supported_features->encrypted_files = 1;
260 supported_features->encrypted_directories = 1;
263 supported_features->not_context_indexed_files = 1;
265 /* Don't do anything with FILE_SUPPORTS_SPARSE_FILES. */
267 if (vol_flags & FILE_NAMED_STREAMS)
268 supported_features->named_data_streams = 1;
270 if (vol_flags & FILE_SUPPORTS_HARD_LINKS)
271 supported_features->hard_links = 1;
273 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS)
274 supported_features->reparse_points = 1;
276 if (vol_flags & FILE_PERSISTENT_ACLS)
277 supported_features->security_descriptors = 1;
279 if (short_names_supported)
280 supported_features->short_names = 1;
282 supported_features->timestamps = 1;
284 /* Note: Windows does not support case sensitive filenames! At least
285 * not without changing the registry and rebooting... */
290 #define COMPACT_FLAGS (WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS4K | \
291 WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS8K | \
292 WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS16K | \
293 WIMLIB_EXTRACT_FLAG_COMPACT_LZX)
298 * If not done already, load the patterns from the [PrepopulateList] section of
299 * WimBootCompress.ini in the WIM image being extracted.
301 * Note: WimBootCompress.ini applies to both types of "external backing":
303 * - WIM backing ("WIMBoot" - Windows 8.1 and later)
304 * - File backing ("System Compression" - Windows 10 and later)
307 load_prepopulate_pats(struct win32_apply_ctx *ctx)
309 const wchar_t *path = L"\\Windows\\System32\\WimBootCompress.ini";
310 struct wim_dentry *dentry;
311 const struct blob_descriptor *blob;
314 struct string_set *s;
316 struct text_file_section sec;
318 if (ctx->tried_to_load_prepopulate_list)
321 ctx->tried_to_load_prepopulate_list = true;
323 dentry = get_dentry(ctx->common.wim, path, WIMLIB_CASE_INSENSITIVE);
325 (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
326 FILE_ATTRIBUTE_REPARSE_POINT |
327 FILE_ATTRIBUTE_ENCRYPTED)) ||
328 !(blob = inode_get_blob_for_unnamed_data_stream(dentry->d_inode,
329 ctx->common.wim->blob_table)))
331 WARNING("%ls does not exist in the WIM image.\n"
332 " The default configuration will be used instead; it assumes that all\n"
333 " files are valid for external backing regardless of path, equivalent\n"
334 " to an empty [PrepopulateList] section.", path);
335 return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
338 ret = read_blob_into_alloc_buf(blob, &buf);
342 s = CALLOC(1, sizeof(struct string_set));
345 return WIMLIB_ERR_NOMEM;
348 sec.name = T("PrepopulateList");
351 ret = do_load_text_file(path, buf, blob->size, &mem, &sec, 1,
352 LOAD_TEXT_FILE_REMOVE_QUOTES |
353 LOAD_TEXT_FILE_NO_WARNINGS,
355 STATIC_ASSERT(OS_PREFERRED_PATH_SEPARATOR == WIM_PATH_SEPARATOR);
361 ctx->prepopulate_pats = s;
362 ctx->mem_prepopulate_pats = mem;
366 /* Returns %true if the specified absolute path to a file in the WIM image can
367 * be subject to external backing when extracted. Otherwise returns %false. */
369 can_externally_back_path(const wchar_t *path, const struct win32_apply_ctx *ctx)
371 /* Does the path match a pattern given in the [PrepopulateList] section
372 * of WimBootCompress.ini? */
373 if (ctx->prepopulate_pats && match_pattern_list(path, ctx->prepopulate_pats))
376 /* Since we attempt to modify the SYSTEM registry after it's extracted
377 * (see end_wimboot_extraction()), it can't be extracted as externally
378 * backed. This extends to associated files such as SYSTEM.LOG that
379 * also must be writable in order to write to the registry. Normally,
380 * SYSTEM is in [PrepopulateList], and the SYSTEM.* files match patterns
381 * in [ExclusionList] and therefore are not captured in the WIM at all.
382 * However, a WIM that wasn't specifically captured in "WIMBoot mode"
383 * may contain SYSTEM.* files. So to make things "just work", hard-code
385 if (match_path(path, L"\\Windows\\System32\\config\\SYSTEM*", false))
391 /* Can the specified WIM resource be used as the source of an external backing
392 * for the wof.sys WIM provider? */
394 is_resource_valid_for_external_backing(const struct wim_resource_descriptor *rdesc,
395 struct win32_apply_ctx *ctx)
397 /* Must be the original WIM file format. This check excludes pipable
398 * resources and solid resources. It also excludes other resources
399 * contained in such files even if they would be otherwise compatible.
401 if (rdesc->wim->hdr.magic != WIM_MAGIC ||
402 rdesc->wim->hdr.wim_version != WIM_VERSION_DEFAULT)
404 ctx->wimboot.have_wrong_version_wims = true;
409 * Whitelist of compression types and chunk sizes supported by
410 * Microsoft's WOF driver.
413 * - Uncompressed WIMs result in BSOD. However, this only applies to
414 * the WIM file itself, not to uncompressed resources in a WIM file
415 * that is otherwise compressed.
416 * - XPRESS 64K sometimes appears to work, but sometimes it causes
417 * reads to fail with STATUS_UNSUCCESSFUL.
419 switch (rdesc->compression_type) {
420 case WIMLIB_COMPRESSION_TYPE_NONE:
421 if (rdesc->wim->compression_type == WIMLIB_COMPRESSION_TYPE_NONE) {
422 ctx->wimboot.have_uncompressed_wims = true;
426 case WIMLIB_COMPRESSION_TYPE_XPRESS:
427 switch (rdesc->chunk_size) {
434 ctx->wimboot.have_unsupported_compressed_resources = true;
438 case WIMLIB_COMPRESSION_TYPE_LZX:
439 switch (rdesc->chunk_size) {
443 ctx->wimboot.have_unsupported_compressed_resources = true;
448 ctx->wimboot.have_unsupported_compressed_resources = true;
452 /* Microsoft's WoF driver errors out if it tries to satisfy a read with
453 * ending offset >= 4 GiB from an externally backed file. */
454 if (rdesc->uncompressed_size > 4200000000) {
455 ctx->wimboot.have_huge_resources = true;
462 #define EXTERNAL_BACKING_NOT_ENABLED -1
463 #define EXTERNAL_BACKING_NOT_POSSIBLE -2
464 #define EXTERNAL_BACKING_EXCLUDED -3
467 * Determines whether the specified file will be externally backed. Returns a
468 * negative status code if no, 0 if yes, or a positive wimlib error code on
469 * error. If the file is excluded from external backing based on its path, then
470 * *excluded_dentry_ret is set to the dentry for the path that matched the
473 * Note that this logic applies to both types of "external backing":
475 * - WIM backing ("WIMBoot" - Windows 8.1 and later)
476 * - File backing ("System Compression" - Windows 10 and later)
478 * However, in the case of WIM backing we also need to validate that the WIM
479 * resource that would be the source of the backing is supported by the wof.sys
483 will_externally_back_inode(struct wim_inode *inode, struct win32_apply_ctx *ctx,
484 const struct wim_dentry **excluded_dentry_ret,
487 struct wim_dentry *dentry;
488 struct blob_descriptor *blob;
491 if (load_prepopulate_pats(ctx) == WIMLIB_ERR_NOMEM)
492 return WIMLIB_ERR_NOMEM;
494 if (inode->i_can_externally_back)
497 /* This may do redundant checks because the cached value
498 * i_can_externally_back is 2-state (as opposed to 3-state:
499 * unknown/no/yes). But most files can be externally backed, so this
502 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
503 FILE_ATTRIBUTE_REPARSE_POINT |
504 FILE_ATTRIBUTE_ENCRYPTED))
505 return EXTERNAL_BACKING_NOT_POSSIBLE;
507 blob = inode_get_blob_for_unnamed_data_stream_resolved(inode);
510 return EXTERNAL_BACKING_NOT_POSSIBLE;
513 (blob->blob_location != BLOB_IN_WIM ||
514 !is_resource_valid_for_external_backing(blob->rdesc, ctx)))
515 return EXTERNAL_BACKING_NOT_POSSIBLE;
518 * We need to check the patterns in [PrepopulateList] against every name
519 * of the inode, in case any of them match.
522 inode_for_each_extraction_alias(dentry, inode) {
524 ret = calculate_dentry_full_path(dentry);
528 if (!can_externally_back_path(dentry->d_full_path, ctx)) {
529 if (excluded_dentry_ret)
530 *excluded_dentry_ret = dentry;
531 return EXTERNAL_BACKING_EXCLUDED;
535 inode->i_can_externally_back = 1;
540 * Determines if the unnamed data stream of a file will be created as a WIM
541 * external backing (a "WIMBoot pointer file"), as opposed to a standard
545 win32_will_back_from_wim(struct wim_dentry *dentry, struct apply_ctx *_ctx)
547 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
549 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
550 return EXTERNAL_BACKING_NOT_ENABLED;
552 return will_externally_back_inode(dentry->d_inode, ctx, NULL, true);
555 /* Find the WOF registration information for the specified WIM file. */
556 static struct wimboot_wim *
557 find_wimboot_wim(WIMStruct *wim_to_find, struct win32_apply_ctx *ctx)
559 for (size_t i = 0; i < ctx->wimboot.num_wims; i++)
560 if (wim_to_find == ctx->wimboot.wims[i].wim)
561 return &ctx->wimboot.wims[i];
568 set_backed_from_wim(HANDLE h, struct wim_inode *inode, struct win32_apply_ctx *ctx)
571 const struct wim_dentry *excluded_dentry;
572 const struct blob_descriptor *blob;
573 const struct wimboot_wim *wimboot_wim;
575 ret = will_externally_back_inode(inode, ctx, &excluded_dentry, true);
576 if (ret > 0) /* Error. */
579 if (ret < 0 && ret != EXTERNAL_BACKING_EXCLUDED)
580 return 0; /* Not externally backing, other than due to exclusion. */
582 if (unlikely(ret == EXTERNAL_BACKING_EXCLUDED)) {
583 /* Not externally backing due to exclusion. */
584 union wimlib_progress_info info;
586 build_extraction_path(excluded_dentry, ctx);
588 info.wimboot_exclude.path_in_wim = excluded_dentry->d_full_path;
589 info.wimboot_exclude.extraction_path = current_path(ctx);
591 return call_progress(ctx->common.progfunc,
592 WIMLIB_PROGRESS_MSG_WIMBOOT_EXCLUDE,
593 &info, ctx->common.progctx);
596 /* Externally backing. */
598 blob = inode_get_blob_for_unnamed_data_stream_resolved(inode);
599 wimboot_wim = find_wimboot_wim(blob->rdesc->wim, ctx);
601 if (unlikely(!wimboot_set_pointer(h,
603 wimboot_wim->data_source_id,
604 wimboot_wim->blob_table_hash,
605 ctx->wimboot.wof_running)))
607 const DWORD err = GetLastError();
609 build_extraction_path(inode_first_extraction_dentry(inode), ctx);
610 win32_error(err, L"\"%ls\": Couldn't set WIMBoot pointer data",
612 return WIMLIB_ERR_WIMBOOT;
617 /* Calculates the SHA-1 message digest of the WIM's blob table. */
619 hash_blob_table(WIMStruct *wim, u8 hash[SHA1_HASH_SIZE])
621 return wim_reshdr_to_hash(&wim->hdr.blob_table_reshdr, wim, hash);
625 register_wim_with_wof(WIMStruct *wim, struct win32_apply_ctx *ctx)
627 struct wimboot_wim *p;
630 /* Check if already registered */
631 for (size_t i = 0; i < ctx->wimboot.num_wims; i++)
632 if (wim == ctx->wimboot.wims[i].wim)
635 /* Not yet registered */
637 p = REALLOC(ctx->wimboot.wims,
638 (ctx->wimboot.num_wims + 1) * sizeof(ctx->wimboot.wims[0]));
640 return WIMLIB_ERR_NOMEM;
641 ctx->wimboot.wims = p;
643 ctx->wimboot.wims[ctx->wimboot.num_wims].wim = wim;
645 ret = hash_blob_table(wim, ctx->wimboot.wims[ctx->wimboot.num_wims].blob_table_hash);
649 ret = wimboot_alloc_data_source_id(wim->filename,
651 ctx->common.wim->current_image,
653 &ctx->wimboot.wims[ctx->wimboot.num_wims].data_source_id,
654 &ctx->wimboot.wof_running);
658 ctx->wimboot.num_wims++;
662 /* Prepare for doing a "WIMBoot" extraction by registering each source WIM file
663 * with WOF on the target volume. */
665 start_wimboot_extraction(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
668 struct wim_dentry *dentry;
670 if (!wim_info_get_wimboot(ctx->common.wim->wim_info,
671 ctx->common.wim->current_image))
672 WARNING("The WIM image is not marked as WIMBoot compatible. This usually\n"
673 " means it is not intended to be used to back a Windows operating\n"
674 " system. Proceeding anyway.");
676 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
677 struct blob_descriptor *blob;
679 ret = win32_will_back_from_wim(dentry, &ctx->common);
680 if (ret > 0) /* Error */
682 if (ret < 0) /* Won't externally back */
685 blob = inode_get_blob_for_unnamed_data_stream_resolved(dentry->d_inode);
686 ret = register_wim_with_wof(blob->rdesc->wim, ctx);
691 if (ctx->wimboot.have_wrong_version_wims) {
692 WARNING("At least one of the source WIM files uses a version of the WIM\n"
693 " file format that not supported by Microsoft's wof.sys driver.\n"
694 " Files whose data is contained in one of these WIM files will be\n"
695 " extracted as full files rather than externally backed.");
698 if (ctx->wimboot.have_uncompressed_wims) {
699 WARNING("At least one of the source WIM files is uncompressed. Files whose\n"
700 " data is contained in an uncompressed WIM file will be extracted as\n"
701 " full files rather than externally backed, since uncompressed WIM\n"
702 " files are not supported by Microsoft's wof.sys driver.");
705 if (ctx->wimboot.have_unsupported_compressed_resources) {
706 WARNING("At least one of the source WIM files uses a compression format that\n"
707 " is not supported by Microsoft's wof.sys driver. Files whose data is\n"
708 " contained in a compressed resource in one of these WIM files will be\n"
709 " extracted as full files rather than externally backed. (The\n"
710 " compression formats supported by wof.sys are: XPRESS 4K, XPRESS 8K,\n"
711 " XPRESS 16K, XPRESS 32K, and LZX 32K.)");
714 if (ctx->wimboot.have_huge_resources) {
715 WARNING("Some files exceeded 4.2 GB in size. Such files will be extracted\n"
716 " as full files rather than externally backed, since very large files\n"
717 " are not supported by Microsoft's wof.sys driver.");
724 build_win32_extraction_path(const struct wim_dentry *dentry,
725 struct win32_apply_ctx *ctx);
727 /* Sets WimBoot=1 in the extracted SYSTEM registry hive.
729 * WIMGAPI does this, and it's possible that it's important.
730 * But I don't know exactly what this value means to Windows. */
732 end_wimboot_extraction(struct win32_apply_ctx *ctx)
734 struct wim_dentry *dentry;
735 wchar_t subkeyname[32];
741 dentry = get_dentry(ctx->common.wim, L"\\Windows\\System32\\config\\SYSTEM",
742 WIMLIB_CASE_INSENSITIVE);
744 if (!dentry || !will_extract_dentry(dentry))
747 if (!will_extract_dentry(wim_get_current_root_dentry(ctx->common.wim)))
750 /* Not bothering to use the native routines (e.g. NtLoadKey()) for this.
751 * If this doesn't work, you probably also have many other problems. */
753 build_win32_extraction_path(dentry, ctx);
755 randomize_char_array_with_alnum(subkeyname, 20);
756 subkeyname[20] = L'\0';
758 res = RegLoadKey(HKEY_LOCAL_MACHINE, subkeyname, ctx->pathbuf.Buffer);
762 wcscpy(&subkeyname[20], L"\\Setup");
764 res = RegCreateKeyEx(HKEY_LOCAL_MACHINE, subkeyname, 0, NULL,
765 REG_OPTION_BACKUP_RESTORE, 0, NULL, &key, NULL);
771 res = RegSetValueEx(key, L"WimBoot", 0, REG_DWORD,
772 (const BYTE *)&value, sizeof(DWORD));
776 res = RegFlushKey(key);
779 res2 = RegCloseKey(key);
783 subkeyname[20] = L'\0';
784 RegUnLoadKey(HKEY_LOCAL_MACHINE, subkeyname);
788 win32_warning(res, L"Failed to set \\Setup: dword \"WimBoot\"=1 "
789 "value in registry hive \"%ls\"",
790 ctx->pathbuf.Buffer);
796 /* Returns the number of wide characters needed to represent the path to the
797 * specified @dentry, relative to the target directory, when extracted.
799 * Does not include null terminator (not needed for NtCreateFile). */
801 dentry_extraction_path_length(const struct wim_dentry *dentry)
804 const struct wim_dentry *d;
808 len += d->d_extraction_name_nchars + 1;
810 } while (!dentry_is_root(d) && will_extract_dentry(d));
812 return --len; /* No leading slash */
815 /* Returns the length of the longest string that might need to be appended to
816 * the path to an alias of an inode to open or create a named data stream.
818 * If the inode has no named data streams, this will be 0. Otherwise, this will
819 * be 1 plus the length of the longest-named data stream, since the data stream
820 * name must be separated from the path by the ':' character. */
822 inode_longest_named_data_stream_spec(const struct wim_inode *inode)
825 for (unsigned i = 0; i < inode->i_num_streams; i++) {
826 const struct wim_inode_stream *strm = &inode->i_streams[i];
827 if (!stream_is_named_data_stream(strm))
829 size_t len = utf16le_len_chars(strm->stream_name);
838 /* Find the length, in wide characters, of the longest path needed for
839 * extraction of any file in @dentry_list relative to the target directory.
841 * Accounts for named data streams, but does not include null terminator (not
842 * needed for NtCreateFile). */
844 compute_path_max(struct list_head *dentry_list)
847 const struct wim_dentry *dentry;
849 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
852 len = dentry_extraction_path_length(dentry);
854 /* Account for named data streams */
855 len += inode_longest_named_data_stream_spec(dentry->d_inode);
864 /* Build the path at which to extract the @dentry, relative to the target
867 * The path is saved in ctx->pathbuf. */
869 build_extraction_path(const struct wim_dentry *dentry,
870 struct win32_apply_ctx *ctx)
874 const struct wim_dentry *d;
876 len = dentry_extraction_path_length(dentry);
878 ctx->pathbuf.Length = len * sizeof(wchar_t);
879 p = ctx->pathbuf.Buffer + len;
881 !dentry_is_root(d->d_parent) && will_extract_dentry(d->d_parent);
884 p -= d->d_extraction_name_nchars;
885 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
888 /* No leading slash */
889 p -= d->d_extraction_name_nchars;
890 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
893 /* Build the path at which to extract the @dentry, relative to the target
894 * directory, adding the suffix for a named data stream.
896 * The path is saved in ctx->pathbuf. */
898 build_extraction_path_with_ads(const struct wim_dentry *dentry,
899 struct win32_apply_ctx *ctx,
900 const wchar_t *stream_name,
901 size_t stream_name_nchars)
905 build_extraction_path(dentry, ctx);
907 /* Add :NAME for named data stream */
908 p = ctx->pathbuf.Buffer + (ctx->pathbuf.Length / sizeof(wchar_t));
910 wmemcpy(p, stream_name, stream_name_nchars);
911 ctx->pathbuf.Length += (1 + stream_name_nchars) * sizeof(wchar_t);
914 /* Build the Win32 namespace path to the specified @dentry when extracted.
916 * The path is saved in ctx->pathbuf and will be null terminated.
918 * XXX: We could get rid of this if it wasn't needed for the file encryption
919 * APIs, and the registry manipulation in WIMBoot mode. */
921 build_win32_extraction_path(const struct wim_dentry *dentry,
922 struct win32_apply_ctx *ctx)
924 build_extraction_path(dentry, ctx);
926 /* Prepend target_ntpath to our relative path, then change \??\ into \\?\ */
928 memmove(ctx->pathbuf.Buffer +
929 (ctx->target_ntpath.Length / sizeof(wchar_t)) + 1,
930 ctx->pathbuf.Buffer, ctx->pathbuf.Length);
931 memcpy(ctx->pathbuf.Buffer, ctx->target_ntpath.Buffer,
932 ctx->target_ntpath.Length);
933 ctx->pathbuf.Buffer[ctx->target_ntpath.Length / sizeof(wchar_t)] = L'\\';
934 ctx->pathbuf.Length += ctx->target_ntpath.Length + sizeof(wchar_t);
935 ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)] = L'\0';
937 wimlib_assert(ctx->pathbuf.Length >= 4 * sizeof(wchar_t) &&
938 !wmemcmp(ctx->pathbuf.Buffer, L"\\??\\", 4));
940 ctx->pathbuf.Buffer[1] = L'\\';
944 /* Returns a "printable" representation of the last relative NT path that was
945 * constructed with build_extraction_path() or build_extraction_path_with_ads().
947 * This will be overwritten by the next call to this function. */
948 static const wchar_t *
949 current_path(struct win32_apply_ctx *ctx)
951 wchar_t *p = ctx->print_buffer;
953 p = wmempcpy(p, ctx->common.target, ctx->common.target_nchars);
955 p = wmempcpy(p, ctx->pathbuf.Buffer, ctx->pathbuf.Length / sizeof(wchar_t));
957 return ctx->print_buffer;
960 /* Open handle to the target directory if it is not already open. If the target
961 * directory does not exist, this creates it. */
963 open_target_directory(struct win32_apply_ctx *ctx)
970 ctx->attr.Length = sizeof(ctx->attr);
971 ctx->attr.RootDirectory = NULL;
972 ctx->attr.ObjectName = &ctx->target_ntpath;
973 status = (*func_NtCreateFile)(&ctx->h_target,
979 FILE_SHARE_VALID_FLAGS,
981 FILE_DIRECTORY_FILE |
982 FILE_OPEN_REPARSE_POINT |
983 FILE_OPEN_FOR_BACKUP_INTENT,
986 if (!NT_SUCCESS(status)) {
987 winnt_error(status, L"Can't open or create directory \"%ls\"",
989 return WIMLIB_ERR_OPENDIR;
991 ctx->attr.RootDirectory = ctx->h_target;
992 ctx->attr.ObjectName = &ctx->pathbuf;
997 close_target_directory(struct win32_apply_ctx *ctx)
1000 (*func_NtClose)(ctx->h_target);
1001 ctx->h_target = NULL;
1002 ctx->attr.RootDirectory = NULL;
1007 * Ensures the target directory exists and opens a handle to it, in preparation
1008 * of using paths relative to it.
1011 prepare_target(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1016 ret = win32_path_to_nt_path(ctx->common.target, &ctx->target_ntpath);
1020 ret = open_target_directory(ctx);
1024 path_max = compute_path_max(dentry_list);
1025 /* Add some extra for building Win32 paths for the file encryption APIs,
1026 * and ensure we have at least enough to potentially use a 8.3 name for
1027 * the last component. */
1028 path_max += max(2 + (ctx->target_ntpath.Length / sizeof(wchar_t)),
1031 ctx->pathbuf.MaximumLength = path_max * sizeof(wchar_t);
1032 ctx->pathbuf.Buffer = MALLOC(ctx->pathbuf.MaximumLength);
1033 if (!ctx->pathbuf.Buffer)
1034 return WIMLIB_ERR_NOMEM;
1036 ctx->print_buffer = MALLOC((ctx->common.target_nchars + 1 + path_max + 1) *
1038 if (!ctx->print_buffer)
1039 return WIMLIB_ERR_NOMEM;
1044 /* When creating an inode that will have a short (DOS) name, we create it using
1045 * the long name associated with the short name. This ensures that the short
1046 * name gets associated with the correct long name. */
1047 static struct wim_dentry *
1048 first_extraction_alias(const struct wim_inode *inode)
1050 struct wim_dentry *dentry;
1052 inode_for_each_extraction_alias(dentry, inode)
1053 if (dentry_has_short_name(dentry))
1055 return inode_first_extraction_dentry(inode);
1059 * Set or clear FILE_ATTRIBUTE_COMPRESSED if the inherited value is different
1060 * from the desired value.
1062 * Note that you can NOT override the inherited value of
1063 * FILE_ATTRIBUTE_COMPRESSED directly with NtCreateFile().
1066 adjust_compression_attribute(HANDLE h, const struct wim_dentry *dentry,
1067 struct win32_apply_ctx *ctx)
1069 const bool compressed = (dentry->d_inode->i_attributes &
1070 FILE_ATTRIBUTE_COMPRESSED);
1072 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
1075 if (!ctx->common.supported_features.compressed_files)
1078 FILE_BASIC_INFORMATION info;
1080 USHORT compression_state;
1082 /* Get current attributes */
1083 status = (*func_NtQueryInformationFile)(h, &ctx->iosb,
1084 &info, sizeof(info),
1085 FileBasicInformation);
1086 if (NT_SUCCESS(status) &&
1087 compressed == !!(info.FileAttributes & FILE_ATTRIBUTE_COMPRESSED))
1089 /* Nothing needs to be done. */
1093 /* Set the new compression state */
1096 compression_state = COMPRESSION_FORMAT_DEFAULT;
1098 compression_state = COMPRESSION_FORMAT_NONE;
1100 status = (*func_NtFsControlFile)(h,
1105 FSCTL_SET_COMPRESSION,
1110 if (NT_SUCCESS(status))
1113 winnt_error(status, L"Can't %s compression attribute on \"%ls\"",
1114 (compressed ? "set" : "clear"), current_path(ctx));
1115 return WIMLIB_ERR_SET_ATTRIBUTES;
1118 /* Try to enable short name support on the target volume. If successful, return
1119 * true. If unsuccessful, issue a warning and return false. */
1121 try_to_enable_short_names(const wchar_t *volume)
1124 FILE_FS_PERSISTENT_VOLUME_INFORMATION info;
1126 DWORD bytesReturned;
1128 h = CreateFile(volume, GENERIC_WRITE,
1129 FILE_SHARE_VALID_FLAGS, NULL, OPEN_EXISTING,
1130 FILE_FLAG_BACKUP_SEMANTICS, NULL);
1131 if (h == INVALID_HANDLE_VALUE)
1134 info.VolumeFlags = 0;
1135 info.FlagMask = PERSISTENT_VOLUME_STATE_SHORT_NAME_CREATION_DISABLED;
1139 bret = DeviceIoControl(h, FSCTL_SET_PERSISTENT_VOLUME_STATE,
1140 &info, sizeof(info), NULL, 0,
1141 &bytesReturned, NULL);
1150 win32_warning(GetLastError(),
1151 L"Failed to enable short name support on %ls",
1157 remove_conflicting_short_name(const struct wim_dentry *dentry, struct win32_apply_ctx *ctx)
1163 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1164 (13 * sizeof(wchar_t));
1165 u8 buf[bufsize] _aligned_attribute(8);
1166 bool retried = false;
1167 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1169 memset(buf, 0, bufsize);
1171 /* Build the path with the short name. */
1172 name = &ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)];
1173 while (name != ctx->pathbuf.Buffer && *(name - 1) != L'\\')
1175 end = mempcpy(name, dentry->d_short_name, dentry->d_short_name_nbytes);
1176 ctx->pathbuf.Length = ((u8 *)end - (u8 *)ctx->pathbuf.Buffer);
1178 /* Open the conflicting file (by short name). */
1179 status = (*func_NtOpenFile)(&h, GENERIC_WRITE | DELETE,
1180 &ctx->attr, &ctx->iosb,
1181 FILE_SHARE_VALID_FLAGS,
1182 FILE_OPEN_REPARSE_POINT | FILE_OPEN_FOR_BACKUP_INTENT);
1183 if (!NT_SUCCESS(status)) {
1184 winnt_warning(status, L"Can't open \"%ls\"", current_path(ctx));
1189 WARNING("Overriding conflicting short name; path=\"%ls\"",
1193 /* Try to remove the short name on the conflicting file. */
1196 status = (*func_NtSetInformationFile)(h, &ctx->iosb, info, bufsize,
1197 FileShortNameInformation);
1199 if (status == STATUS_INVALID_PARAMETER && !retried) {
1201 /* Microsoft forgot to make it possible to remove short names
1202 * until Windows 7. Oops. Use a random short name instead. */
1204 info->FileNameLength = 12 * sizeof(wchar_t);
1205 for (int i = 0; i < 8; i++)
1206 info->FileName[i] = 'A' + (rand() % 26);
1207 info->FileName[8] = L'.';
1208 info->FileName[9] = L'W';
1209 info->FileName[10] = L'L';
1210 info->FileName[11] = L'B';
1211 info->FileName[12] = L'\0';
1217 build_extraction_path(dentry, ctx);
1221 /* Set the short name on the open file @h which has been created at the location
1222 * indicated by @dentry.
1224 * Note that this may add, change, or remove the short name.
1226 * @h must be opened with DELETE access.
1228 * Returns 0 or WIMLIB_ERR_SET_SHORT_NAME. The latter only happens in
1229 * STRICT_SHORT_NAMES mode.
1232 set_short_name(HANDLE h, const struct wim_dentry *dentry,
1233 struct win32_apply_ctx *ctx)
1236 if (!ctx->common.supported_features.short_names)
1240 * Note: The size of the FILE_NAME_INFORMATION buffer must be such that
1241 * FileName contains at least 2 wide characters (4 bytes). Otherwise,
1242 * NtSetInformationFile() will return STATUS_INFO_LENGTH_MISMATCH. This
1243 * is despite the fact that FileNameLength can validly be 0 or 2 bytes,
1244 * with the former case being removing the existing short name if
1245 * present, rather than setting one.
1247 * The null terminator is seemingly optional, but to be safe we include
1248 * space for it and zero all unused space.
1251 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1252 max(dentry->d_short_name_nbytes, sizeof(wchar_t)) +
1254 u8 buf[bufsize] _aligned_attribute(8);
1255 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1257 bool tried_to_remove_existing = false;
1259 memset(buf, 0, bufsize);
1261 info->FileNameLength = dentry->d_short_name_nbytes;
1262 memcpy(info->FileName, dentry->d_short_name, dentry->d_short_name_nbytes);
1265 status = (*func_NtSetInformationFile)(h, &ctx->iosb, info, bufsize,
1266 FileShortNameInformation);
1267 if (NT_SUCCESS(status))
1270 if (status == STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME) {
1271 if (dentry->d_short_name_nbytes == 0)
1273 if (!ctx->tried_to_enable_short_names) {
1277 ctx->tried_to_enable_short_names = true;
1279 ret = win32_get_drive_path(ctx->common.target,
1283 if (try_to_enable_short_names(volume))
1289 * Short names can conflict in several cases:
1291 * - a file being extracted has a short name conflicting with an
1294 * - a file being extracted has a short name conflicting with another
1295 * file being extracted (possible, but shouldn't happen)
1297 * - a file being extracted has a short name that conflicts with the
1298 * automatically generated short name of a file we previously
1299 * extracted, but failed to set the short name for. Sounds unlikely,
1300 * but this actually does happen fairly often on versions of Windows
1301 * prior to Windows 7 because they do not support removing short names
1304 if (unlikely(status == STATUS_OBJECT_NAME_COLLISION) &&
1305 dentry->d_short_name_nbytes && !tried_to_remove_existing)
1307 tried_to_remove_existing = true;
1308 status = remove_conflicting_short_name(dentry, ctx);
1309 if (NT_SUCCESS(status))
1313 /* By default, failure to set short names is not an error (since short
1314 * names aren't too important anymore...). */
1315 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES)) {
1316 if (dentry->d_short_name_nbytes)
1317 ctx->num_set_short_name_failures++;
1319 ctx->num_remove_short_name_failures++;
1323 winnt_error(status, L"Can't set short name on \"%ls\"", current_path(ctx));
1324 return WIMLIB_ERR_SET_SHORT_NAME;
1328 * A wrapper around NtCreateFile() to make it slightly more usable...
1329 * This uses the path currently constructed in ctx->pathbuf.
1331 * Also, we always specify FILE_OPEN_FOR_BACKUP_INTENT and
1332 * FILE_OPEN_REPARSE_POINT.
1335 do_create_file(PHANDLE FileHandle,
1336 ACCESS_MASK DesiredAccess,
1337 PLARGE_INTEGER AllocationSize,
1338 ULONG FileAttributes,
1339 ULONG CreateDisposition,
1340 ULONG CreateOptions,
1341 struct win32_apply_ctx *ctx)
1343 return (*func_NtCreateFile)(FileHandle,
1349 FILE_SHARE_VALID_FLAGS,
1352 FILE_OPEN_FOR_BACKUP_INTENT |
1353 FILE_OPEN_REPARSE_POINT,
1358 /* Like do_create_file(), but builds the extraction path of the @dentry first.
1361 create_file(PHANDLE FileHandle,
1362 ACCESS_MASK DesiredAccess,
1363 PLARGE_INTEGER AllocationSize,
1364 ULONG FileAttributes,
1365 ULONG CreateDisposition,
1366 ULONG CreateOptions,
1367 const struct wim_dentry *dentry,
1368 struct win32_apply_ctx *ctx)
1370 build_extraction_path(dentry, ctx);
1371 return do_create_file(FileHandle,
1381 delete_file_or_stream(struct win32_apply_ctx *ctx)
1385 FILE_DISPOSITION_INFORMATION disposition_info;
1386 FILE_BASIC_INFORMATION basic_info;
1387 bool retried = false;
1389 status = do_create_file(&h,
1394 FILE_NON_DIRECTORY_FILE,
1396 if (unlikely(!NT_SUCCESS(status))) {
1397 winnt_error(status, L"Can't open \"%ls\" for deletion",
1399 return WIMLIB_ERR_OPEN;
1403 disposition_info.DoDeleteFile = TRUE;
1404 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1406 sizeof(disposition_info),
1407 FileDispositionInformation);
1409 if (likely(NT_SUCCESS(status)))
1412 if (status == STATUS_CANNOT_DELETE && !retried) {
1413 /* Clear file attributes and try again. This is necessary for
1414 * FILE_ATTRIBUTE_READONLY files. */
1415 status = do_create_file(&h,
1416 FILE_WRITE_ATTRIBUTES | DELETE,
1420 FILE_NON_DIRECTORY_FILE,
1422 if (!NT_SUCCESS(status)) {
1424 L"Can't open \"%ls\" to reset attributes",
1426 return WIMLIB_ERR_OPEN;
1428 memset(&basic_info, 0, sizeof(basic_info));
1429 basic_info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1430 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1433 FileBasicInformation);
1434 if (!NT_SUCCESS(status)) {
1436 L"Can't reset file attributes on \"%ls\"",
1439 return WIMLIB_ERR_SET_ATTRIBUTES;
1444 winnt_error(status, L"Can't delete \"%ls\"", current_path(ctx));
1445 return WIMLIB_ERR_OPEN;
1449 * Create a nondirectory file or named data stream at the current path,
1450 * superseding any that already exists at that path. If successful, return an
1451 * open handle to the file or named data stream.
1454 supersede_file_or_stream(struct win32_apply_ctx *ctx, HANDLE *h_ret)
1457 bool retried = false;
1459 /* FILE_ATTRIBUTE_SYSTEM is needed to ensure that
1460 * FILE_ATTRIBUTE_ENCRYPTED doesn't get set before we want it to be. */
1462 status = do_create_file(h_ret,
1463 GENERIC_READ | GENERIC_WRITE | DELETE,
1465 FILE_ATTRIBUTE_SYSTEM,
1467 FILE_NON_DIRECTORY_FILE,
1469 if (likely(NT_SUCCESS(status)))
1472 /* STATUS_OBJECT_NAME_COLLISION means that the file or stream already
1473 * exists. Delete the existing file or stream, then try again.
1475 * Note: we don't use FILE_OVERWRITE_IF or FILE_SUPERSEDE because of
1476 * problems with certain file attributes, especially
1477 * FILE_ATTRIBUTE_ENCRYPTED. FILE_SUPERSEDE is also broken in the
1478 * Windows PE ramdisk. */
1479 if (status == STATUS_OBJECT_NAME_COLLISION && !retried) {
1480 int ret = delete_file_or_stream(ctx);
1486 winnt_error(status, L"Can't create \"%ls\"", current_path(ctx));
1487 return WIMLIB_ERR_OPEN;
1490 /* Set the reparse point @rpbuf of length @rpbuflen on the extracted file
1491 * corresponding to the WIM dentry @dentry. */
1493 do_set_reparse_point(const struct wim_dentry *dentry,
1494 const struct reparse_buffer_disk *rpbuf, u16 rpbuflen,
1495 struct win32_apply_ctx *ctx)
1500 status = create_file(&h, GENERIC_WRITE, NULL,
1501 0, FILE_OPEN, 0, dentry, ctx);
1502 if (!NT_SUCCESS(status))
1505 status = (*func_NtFsControlFile)(h, NULL, NULL, NULL,
1506 &ctx->iosb, FSCTL_SET_REPARSE_POINT,
1507 (void *)rpbuf, rpbuflen,
1511 if (NT_SUCCESS(status))
1514 /* On Windows, by default only the Administrator can create symbolic
1515 * links for some reason. By default we just issue a warning if this
1516 * appears to be the problem. Use WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS
1517 * to get a hard error. */
1518 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS)
1519 && (status == STATUS_PRIVILEGE_NOT_HELD ||
1520 status == STATUS_ACCESS_DENIED)
1521 && (dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1522 dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1524 WARNING("Can't create symbolic link \"%ls\"! \n"
1525 " (Need Administrator rights, or at least "
1527 " SeCreateSymbolicLink privilege.)",
1533 winnt_error(status, L"Can't set reparse data on \"%ls\"",
1535 return WIMLIB_ERR_SET_REPARSE_DATA;
1539 * Create empty named data streams and potentially a reparse point for the
1540 * specified file, if any.
1542 * Since these won't have blob descriptors, they won't show up in the call to
1543 * extract_blob_list(). Hence the need for the special case.
1546 create_empty_streams(const struct wim_dentry *dentry,
1547 struct win32_apply_ctx *ctx)
1549 const struct wim_inode *inode = dentry->d_inode;
1552 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1553 const struct wim_inode_stream *strm = &inode->i_streams[i];
1555 if (stream_blob_resolved(strm) != NULL)
1558 if (strm->stream_type == STREAM_TYPE_REPARSE_POINT &&
1559 ctx->common.supported_features.reparse_points)
1561 u8 buf[REPARSE_DATA_OFFSET] _aligned_attribute(8);
1562 struct reparse_buffer_disk *rpbuf =
1563 (struct reparse_buffer_disk *)buf;
1564 complete_reparse_point(rpbuf, inode, 0);
1565 ret = do_set_reparse_point(dentry, rpbuf,
1566 REPARSE_DATA_OFFSET, ctx);
1569 } else if (stream_is_named_data_stream(strm) &&
1570 ctx->common.supported_features.named_data_streams)
1574 build_extraction_path_with_ads(dentry, ctx,
1576 utf16le_len_chars(strm->stream_name));
1577 ret = supersede_file_or_stream(ctx, &h);
1579 build_extraction_path(dentry, ctx);
1591 * Creates the directory named by @dentry, or uses an existing directory at that
1592 * location. If necessary, sets the short name and/or fixes compression and
1593 * encryption attributes.
1595 * Returns 0, WIMLIB_ERR_MKDIR, or WIMLIB_ERR_SET_SHORT_NAME.
1598 create_directory(const struct wim_dentry *dentry, struct win32_apply_ctx *ctx)
1605 /* DELETE is needed for set_short_name(); GENERIC_READ and GENERIC_WRITE
1606 * are needed for adjust_compression_attribute(). */
1607 perms = GENERIC_READ | GENERIC_WRITE;
1608 if (!dentry_is_root(dentry))
1611 /* FILE_ATTRIBUTE_SYSTEM is needed to ensure that
1612 * FILE_ATTRIBUTE_ENCRYPTED doesn't get set before we want it to be. */
1613 status = create_file(&h, perms, NULL, FILE_ATTRIBUTE_SYSTEM,
1614 FILE_OPEN_IF, FILE_DIRECTORY_FILE, dentry, ctx);
1615 if (!NT_SUCCESS(status)) {
1616 winnt_error(status, L"Can't create directory \"%ls\"",
1618 return WIMLIB_ERR_MKDIR;
1621 if (ctx->iosb.Information == FILE_OPENED) {
1622 /* If we opened an existing directory, try to clear its file
1623 * attributes. As far as I know, this only actually makes a
1624 * difference in the case where a FILE_ATTRIBUTE_READONLY
1625 * directory has a named data stream which needs to be
1626 * extracted. You cannot create a named data stream of such a
1627 * directory, even though this contradicts Microsoft's
1628 * documentation for FILE_ATTRIBUTE_READONLY which states it is
1629 * not honored for directories! */
1630 FILE_BASIC_INFORMATION basic_info = { .FileAttributes = FILE_ATTRIBUTE_NORMAL };
1631 (*func_NtSetInformationFile)(h, &ctx->iosb, &basic_info,
1632 sizeof(basic_info), FileBasicInformation);
1635 if (!dentry_is_root(dentry)) {
1636 ret = set_short_name(h, dentry, ctx);
1641 ret = adjust_compression_attribute(h, dentry, ctx);
1648 * Create all the directories being extracted, other than the target directory
1651 * Note: we don't honor directory hard links. However, we don't allow them to
1652 * exist in WIM images anyway (see inode_fixup.c).
1655 create_directories(struct list_head *dentry_list,
1656 struct win32_apply_ctx *ctx)
1658 const struct wim_dentry *dentry;
1661 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1663 if (!(dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY))
1666 /* Note: Here we include files with
1667 * FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT, but we
1668 * wait until later to actually set the reparse data. */
1670 ret = create_directory(dentry, ctx);
1673 ret = create_empty_streams(dentry, ctx);
1675 ret = check_apply_error(dentry, ctx, ret);
1679 ret = report_file_created(&ctx->common);
1687 * Creates the nondirectory file named by @dentry.
1689 * On success, returns an open handle to the file in @h_ret, with GENERIC_READ,
1690 * GENERIC_WRITE, and DELETE access. Also, the path to the file will be saved
1691 * in ctx->pathbuf. On failure, returns an error code.
1694 create_nondirectory_inode(HANDLE *h_ret, const struct wim_dentry *dentry,
1695 struct win32_apply_ctx *ctx)
1700 build_extraction_path(dentry, ctx);
1702 ret = supersede_file_or_stream(ctx, &h);
1706 ret = adjust_compression_attribute(h, dentry, ctx);
1710 ret = create_empty_streams(dentry, ctx);
1723 /* Creates a hard link at the location named by @dentry to the file represented
1724 * by the open handle @h. Or, if the target volume does not support hard links,
1725 * create a separate file instead. */
1727 create_link(HANDLE h, const struct wim_dentry *dentry,
1728 struct win32_apply_ctx *ctx)
1730 if (ctx->common.supported_features.hard_links) {
1732 build_extraction_path(dentry, ctx);
1734 size_t bufsize = offsetof(FILE_LINK_INFORMATION, FileName) +
1735 ctx->pathbuf.Length + sizeof(wchar_t);
1736 u8 buf[bufsize] _aligned_attribute(8);
1737 FILE_LINK_INFORMATION *info = (FILE_LINK_INFORMATION *)buf;
1740 info->ReplaceIfExists = TRUE;
1741 info->RootDirectory = ctx->attr.RootDirectory;
1742 info->FileNameLength = ctx->pathbuf.Length;
1743 memcpy(info->FileName, ctx->pathbuf.Buffer, ctx->pathbuf.Length);
1744 info->FileName[info->FileNameLength / 2] = L'\0';
1746 /* Note: the null terminator isn't actually necessary,
1747 * but if you don't add the extra character, you get
1748 * STATUS_INFO_LENGTH_MISMATCH when FileNameLength
1749 * happens to be 2 */
1751 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1753 FileLinkInformation);
1754 if (NT_SUCCESS(status))
1756 winnt_error(status, L"Failed to create link \"%ls\"",
1758 return WIMLIB_ERR_LINK;
1763 ret = create_nondirectory_inode(&h2, dentry, ctx);
1767 (*func_NtClose)(h2);
1772 /* Given an inode (represented by the open handle @h) for which one link has
1773 * been created (named by @first_dentry), create the other links.
1775 * Or, if the target volume does not support hard links, create separate files.
1777 * Note: This uses ctx->pathbuf and does not reset it.
1780 create_links(HANDLE h, const struct wim_dentry *first_dentry,
1781 struct win32_apply_ctx *ctx)
1783 const struct wim_inode *inode = first_dentry->d_inode;
1784 const struct wim_dentry *dentry;
1787 inode_for_each_extraction_alias(dentry, inode) {
1788 if (dentry != first_dentry) {
1789 ret = create_link(h, dentry, ctx);
1797 /* Create a nondirectory file, including all links. */
1799 create_nondirectory(struct wim_inode *inode, struct win32_apply_ctx *ctx)
1801 struct wim_dentry *first_dentry;
1805 first_dentry = first_extraction_alias(inode);
1807 /* Create first link. */
1808 ret = create_nondirectory_inode(&h, first_dentry, ctx);
1812 /* Set short name. */
1813 ret = set_short_name(h, first_dentry, ctx);
1815 /* Create additional links, OR if hard links are not supported just
1816 * create more files. */
1818 ret = create_links(h, first_dentry, ctx);
1820 /* "WIMBoot" extraction: set external backing by the WIM file if needed. */
1821 if (!ret && unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
1822 ret = set_backed_from_wim(h, inode, ctx);
1828 /* Create all the nondirectory files being extracted, including all aliases
1831 create_nondirectories(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1833 struct wim_dentry *dentry;
1834 struct wim_inode *inode;
1837 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1838 inode = dentry->d_inode;
1839 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1841 /* Call create_nondirectory() only once per inode */
1842 if (dentry == inode_first_extraction_dentry(inode)) {
1843 ret = create_nondirectory(inode, ctx);
1844 ret = check_apply_error(dentry, ctx, ret);
1848 ret = report_file_created(&ctx->common);
1856 close_handles(struct win32_apply_ctx *ctx)
1858 for (unsigned i = 0; i < ctx->num_open_handles; i++)
1859 (*func_NtClose)(ctx->open_handles[i]);
1862 /* Prepare to read the next blob, which has size @blob_size, into an in-memory
1865 prepare_data_buffer(struct win32_apply_ctx *ctx, u64 blob_size)
1867 if (blob_size > ctx->data_buffer_size) {
1868 /* Larger buffer needed. */
1870 if ((size_t)blob_size != blob_size)
1872 new_buffer = REALLOC(ctx->data_buffer, blob_size);
1875 ctx->data_buffer = new_buffer;
1876 ctx->data_buffer_size = blob_size;
1878 /* On the first call this changes data_buffer_ptr from NULL, which tells
1879 * extract_chunk() that the data buffer needs to be filled while reading
1880 * the stream data. */
1881 ctx->data_buffer_ptr = ctx->data_buffer;
1886 begin_extract_blob_instance(const struct blob_descriptor *blob,
1887 struct wim_dentry *dentry,
1888 const struct wim_inode_stream *strm,
1889 struct win32_apply_ctx *ctx)
1891 FILE_ALLOCATION_INFORMATION alloc_info;
1895 if (unlikely(strm->stream_type == STREAM_TYPE_REPARSE_POINT)) {
1896 /* We can't write the reparse point stream directly; we must set
1897 * it with FSCTL_SET_REPARSE_POINT, which requires that all the
1898 * data be available. So, stage the data in a buffer. */
1899 if (!prepare_data_buffer(ctx, blob->size))
1900 return WIMLIB_ERR_NOMEM;
1901 list_add_tail(&dentry->d_tmp_list, &ctx->reparse_dentries);
1905 if (unlikely(strm->stream_type == STREAM_TYPE_EFSRPC_RAW_DATA)) {
1906 /* We can't write encrypted files directly; we must use
1907 * WriteEncryptedFileRaw(), which requires providing the data
1908 * through a callback function. This can't easily be combined
1909 * with our own callback-based approach.
1911 * The current workaround is to simply read the blob into memory
1912 * and write the encrypted file from that.
1914 * TODO: This isn't sufficient for extremely large encrypted
1915 * files. Perhaps we should create an extra thread to write
1917 if (!prepare_data_buffer(ctx, blob->size))
1918 return WIMLIB_ERR_NOMEM;
1919 list_add_tail(&dentry->d_tmp_list, &ctx->encrypted_dentries);
1923 /* It's a data stream (may be unnamed or named). */
1924 wimlib_assert(strm->stream_type == STREAM_TYPE_DATA);
1926 if (ctx->num_open_handles == MAX_OPEN_FILES) {
1927 /* XXX: Fix this. But because of the checks in
1928 * extract_blob_list(), this can now only happen on a filesystem
1929 * that does not support hard links. */
1930 ERROR("Can't extract data: too many open files!");
1931 return WIMLIB_ERR_UNSUPPORTED;
1935 if (unlikely(stream_is_named(strm))) {
1936 build_extraction_path_with_ads(dentry, ctx,
1938 utf16le_len_chars(strm->stream_name));
1940 build_extraction_path(dentry, ctx);
1944 /* Open a new handle */
1945 status = do_create_file(&h,
1946 FILE_WRITE_DATA | SYNCHRONIZE,
1947 NULL, 0, FILE_OPEN_IF,
1948 FILE_SEQUENTIAL_ONLY |
1949 FILE_SYNCHRONOUS_IO_NONALERT,
1951 if (!NT_SUCCESS(status)) {
1952 winnt_error(status, L"Can't open \"%ls\" for writing",
1954 return WIMLIB_ERR_OPEN;
1957 ctx->open_handles[ctx->num_open_handles++] = h;
1959 /* Allocate space for the data. */
1960 alloc_info.AllocationSize.QuadPart = blob->size;
1961 (*func_NtSetInformationFile)(h, &ctx->iosb,
1962 &alloc_info, sizeof(alloc_info),
1963 FileAllocationInformation);
1967 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1968 * pointer to the suffix of the path that begins with the device directly, such
1969 * as e:\Windows\System32. */
1970 static const wchar_t *
1971 skip_nt_toplevel_component(const wchar_t *path, size_t path_nchars)
1973 static const wchar_t * const dirs[] = {
1978 const wchar_t * const end = path + path_nchars;
1980 for (size_t i = 0; i < ARRAY_LEN(dirs); i++) {
1981 size_t len = wcslen(dirs[i]);
1982 if (len <= (end - path) && !wmemcmp(path, dirs[i], len)) {
1984 while (path != end && *path == L'\\')
1993 * Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1994 * pointer to the suffix of the path that is device-relative but possibly with
1995 * leading slashes, such as \Windows\System32.
1997 * The path has an explicit length and is not necessarily null terminated.
1999 static const wchar_t *
2000 get_device_relative_path(const wchar_t *path, size_t path_nchars)
2002 const wchar_t * const orig_path = path;
2003 const wchar_t * const end = path + path_nchars;
2005 path = skip_nt_toplevel_component(path, path_nchars);
2006 if (path == orig_path)
2009 while (path != end && *path != L'\\')
2016 * Given a reparse point buffer for an inode for which the absolute link target
2017 * was relativized when it was archived, de-relative the link target to be
2018 * consistent with the actual extraction location.
2021 try_rpfix(struct reparse_buffer_disk *rpbuf, u16 *rpbuflen_p,
2022 struct win32_apply_ctx *ctx)
2024 struct link_reparse_point link;
2025 size_t orig_subst_name_nchars;
2026 const wchar_t *relpath;
2027 size_t relpath_nchars;
2028 size_t target_ntpath_nchars;
2029 size_t fixed_subst_name_nchars;
2030 const wchar_t *fixed_print_name;
2031 size_t fixed_print_name_nchars;
2033 /* Do nothing if the reparse data is invalid. */
2034 if (parse_link_reparse_point(rpbuf, *rpbuflen_p, &link))
2037 /* Do nothing if the reparse point is a relative symbolic link. */
2038 if (link_is_relative_symlink(&link))
2041 /* Build the new substitute name from the NT namespace path to the
2042 * target directory, then a path separator, then the "device relative"
2043 * part of the old substitute name. */
2045 orig_subst_name_nchars = link.substitute_name_nbytes / sizeof(wchar_t);
2047 relpath = get_device_relative_path(link.substitute_name,
2048 orig_subst_name_nchars);
2049 relpath_nchars = orig_subst_name_nchars -
2050 (relpath - link.substitute_name);
2052 target_ntpath_nchars = ctx->target_ntpath.Length / sizeof(wchar_t);
2054 fixed_subst_name_nchars = target_ntpath_nchars + relpath_nchars;
2056 wchar_t fixed_subst_name[fixed_subst_name_nchars];
2058 wmemcpy(fixed_subst_name, ctx->target_ntpath.Buffer, target_ntpath_nchars);
2059 wmemcpy(&fixed_subst_name[target_ntpath_nchars], relpath, relpath_nchars);
2060 /* Doesn't need to be null-terminated. */
2062 /* Print name should be Win32, but not all NT names can even be
2063 * translated to Win32 names. But we can at least delete the top-level
2064 * directory, such as \??\, and this will have the expected result in
2065 * the usual case. */
2066 fixed_print_name = skip_nt_toplevel_component(fixed_subst_name,
2067 fixed_subst_name_nchars);
2068 fixed_print_name_nchars = fixed_subst_name_nchars - (fixed_print_name -
2071 link.substitute_name = fixed_subst_name;
2072 link.substitute_name_nbytes = fixed_subst_name_nchars * sizeof(wchar_t);
2073 link.print_name = (wchar_t *)fixed_print_name;
2074 link.print_name_nbytes = fixed_print_name_nchars * sizeof(wchar_t);
2075 make_link_reparse_point(&link, rpbuf, rpbuflen_p);
2078 /* Sets the reparse point on the specified file. This handles "fixing" the
2079 * targets of absolute symbolic links and junctions if WIMLIB_EXTRACT_FLAG_RPFIX
2082 set_reparse_point(const struct wim_dentry *dentry,
2083 const struct reparse_buffer_disk *rpbuf, u16 rpbuflen,
2084 struct win32_apply_ctx *ctx)
2086 if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
2087 && !(dentry->d_inode->i_rp_flags & WIM_RP_FLAG_NOT_FIXED))
2089 memcpy(&ctx->rpfixbuf, rpbuf, rpbuflen);
2090 try_rpfix(&ctx->rpfixbuf, &rpbuflen, ctx);
2091 rpbuf = &ctx->rpfixbuf;
2093 return do_set_reparse_point(dentry, rpbuf, rpbuflen, ctx);
2097 /* Import the next block of raw encrypted data */
2099 import_encrypted_data(PBYTE pbData, PVOID pvCallbackContext, PULONG Length)
2101 struct win32_apply_ctx *ctx = pvCallbackContext;
2104 copy_len = min(ctx->encrypted_size - ctx->encrypted_offset, *Length);
2105 memcpy(pbData, &ctx->data_buffer[ctx->encrypted_offset], copy_len);
2106 ctx->encrypted_offset += copy_len;
2108 return ERROR_SUCCESS;
2112 * Write the raw encrypted data to the already-created file (or directory)
2113 * corresponding to @dentry.
2115 * The raw encrypted data is provided in ctx->data_buffer, and its size is
2116 * ctx->encrypted_size.
2118 * This function may close the target directory, in which case the caller needs
2119 * to re-open it if needed.
2122 extract_encrypted_file(const struct wim_dentry *dentry,
2123 struct win32_apply_ctx *ctx)
2130 /* Temporarily build a Win32 path for OpenEncryptedFileRaw() */
2131 build_win32_extraction_path(dentry, ctx);
2133 flags = CREATE_FOR_IMPORT | OVERWRITE_HIDDEN;
2134 if (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
2135 flags |= CREATE_FOR_DIR;
2139 err = OpenEncryptedFileRaw(ctx->pathbuf.Buffer, flags, &rawctx);
2140 if (err == ERROR_SHARING_VIOLATION && !retried) {
2141 /* This can be caused by the handle we have open to the target
2142 * directory. Try closing it temporarily. */
2143 close_target_directory(ctx);
2148 /* Restore the NT namespace path */
2149 build_extraction_path(dentry, ctx);
2151 if (err != ERROR_SUCCESS) {
2152 win32_error(err, L"Can't open \"%ls\" for encrypted import",
2154 return WIMLIB_ERR_OPEN;
2157 ctx->encrypted_offset = 0;
2159 err = WriteEncryptedFileRaw(import_encrypted_data, ctx, rawctx);
2161 CloseEncryptedFileRaw(rawctx);
2163 if (err != ERROR_SUCCESS) {
2164 win32_error(err, L"Can't import encrypted file \"%ls\"",
2166 return WIMLIB_ERR_WRITE;
2172 /* Called when starting to read a blob for extraction on Windows */
2174 begin_extract_blob(struct blob_descriptor *blob, void *_ctx)
2176 struct win32_apply_ctx *ctx = _ctx;
2177 const struct blob_extraction_target *targets = blob_extraction_targets(blob);
2180 ctx->num_open_handles = 0;
2181 ctx->data_buffer_ptr = NULL;
2182 INIT_LIST_HEAD(&ctx->reparse_dentries);
2183 INIT_LIST_HEAD(&ctx->encrypted_dentries);
2185 for (u32 i = 0; i < blob->out_refcnt; i++) {
2186 const struct wim_inode *inode = targets[i].inode;
2187 const struct wim_inode_stream *strm = targets[i].stream;
2188 struct wim_dentry *dentry;
2190 /* A copy of the blob needs to be extracted to @inode. */
2192 if (ctx->common.supported_features.hard_links) {
2193 dentry = inode_first_extraction_dentry(inode);
2194 ret = begin_extract_blob_instance(blob, dentry, strm, ctx);
2195 ret = check_apply_error(dentry, ctx, ret);
2199 /* Hard links not supported. Extract the blob
2200 * separately to each alias of the inode. */
2201 inode_for_each_extraction_alias(dentry, inode) {
2202 ret = begin_extract_blob_instance(blob, dentry, strm, ctx);
2203 ret = check_apply_error(dentry, ctx, ret);
2217 /* Called when the next chunk of a blob has been read for extraction on Windows
2220 extract_chunk(const void *chunk, size_t size, void *_ctx)
2222 struct win32_apply_ctx *ctx = _ctx;
2224 /* Write the data chunk to each open handle */
2225 for (unsigned i = 0; i < ctx->num_open_handles; i++) {
2226 u8 *bufptr = (u8 *)chunk;
2227 size_t bytes_remaining = size;
2229 while (bytes_remaining) {
2230 ULONG count = min(0xFFFFFFFF, bytes_remaining);
2232 status = (*func_NtWriteFile)(ctx->open_handles[i],
2234 &ctx->iosb, bufptr, count,
2236 if (!NT_SUCCESS(status)) {
2237 winnt_error(status, L"Error writing data to target volume");
2238 return WIMLIB_ERR_WRITE;
2240 bufptr += ctx->iosb.Information;
2241 bytes_remaining -= ctx->iosb.Information;
2245 /* Copy the data chunk into the buffer (if needed) */
2246 if (ctx->data_buffer_ptr)
2247 ctx->data_buffer_ptr = mempcpy(ctx->data_buffer_ptr,
2253 get_system_compression_format(int extract_flags)
2255 if (extract_flags & WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS4K)
2256 return FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K;
2258 if (extract_flags & WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS8K)
2259 return FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS8K;
2261 if (extract_flags & WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS16K)
2262 return FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS16K;
2264 return FILE_PROVIDER_COMPRESSION_FORMAT_LZX;
2268 set_system_compression(HANDLE h, int format)
2271 IO_STATUS_BLOCK iosb;
2273 struct wof_external_info wof_info;
2274 struct file_provider_external_info file_info;
2277 .version = WOF_CURRENT_VERSION,
2278 .provider = WOF_PROVIDER_FILE,
2281 .version = FILE_PROVIDER_CURRENT_VERSION,
2282 .compression_format = format,
2286 /* We intentionally use NtFsControlFile() rather than DeviceIoControl()
2287 * here because the "compressing this object would not save space"
2288 * status code does not map to a valid Win32 error code on older
2289 * versions of Windows (before Windows 10?). This can be a problem if
2290 * the WOFADK driver is being used rather than the regular WOF, since
2291 * WOFADK can be used on older versions of Windows. */
2292 status = (*func_NtFsControlFile)(h, NULL, NULL, NULL, &iosb,
2293 FSCTL_SET_EXTERNAL_BACKING,
2294 &in, sizeof(in), NULL, 0);
2296 if (status == 0xC000046F) /* "Compressing this object would not save space." */
2297 return STATUS_SUCCESS;
2303 * This function is called when doing a "compact-mode" extraction and we just
2304 * finished extracting a blob to one or more locations. For each location that
2305 * was the unnamed data stream of a file, this function compresses the
2306 * corresponding file using System Compression, if allowed.
2308 * Note: we're doing the compression immediately after extracting the data
2309 * rather than during a separate compression pass. This way should be faster
2310 * since the operating system should still have the file's data cached.
2312 * Note: we're having the operating system do the compression, which is not
2313 * ideal because wimlib could create the compressed data faster and more
2314 * efficiently (the compressed data format is identical to a WIM resource). But
2315 * we seemingly don't have a choice because WOF prevents applications from
2316 * creating its reparse points.
2319 handle_system_compression(struct blob_descriptor *blob, struct win32_apply_ctx *ctx)
2321 const struct blob_extraction_target *targets = blob_extraction_targets(blob);
2323 const int format = get_system_compression_format(ctx->common.extract_flags);
2325 for (u32 i = 0; i < blob->out_refcnt; i++) {
2326 struct wim_inode *inode = targets[i].inode;
2327 struct wim_inode_stream *strm = targets[i].stream;
2331 if (!stream_is_unnamed_data_stream(strm))
2334 if (will_externally_back_inode(inode, ctx, NULL, false) != 0)
2337 status = create_file(&h, GENERIC_READ | GENERIC_WRITE, NULL,
2339 inode_first_extraction_dentry(inode), ctx);
2341 if (NT_SUCCESS(status)) {
2342 status = set_system_compression(h, format);
2346 if (status == STATUS_INVALID_DEVICE_REQUEST) {
2348 "The request to compress the extracted files using System Compression\n"
2349 " will not be honored because the operating system or target volume\n"
2350 " does not support it. System Compression is only supported on\n"
2351 " Windows 10 and later, and only on NTFS volumes.");
2352 ctx->common.extract_flags &= ~COMPACT_FLAGS;
2356 if (!NT_SUCCESS(status)) {
2357 ctx->num_system_compression_failures++;
2358 if (ctx->num_system_compression_failures < 10) {
2359 winnt_warning(status, L"\"%ls\": Failed to compress "
2360 "extracted file using System Compression",
2362 } else if (ctx->num_system_compression_failures == 10) {
2363 WARNING("Suppressing further warnings about "
2364 "System Compression failures.");
2370 /* Called when a blob has been fully read for extraction on Windows */
2372 end_extract_blob(struct blob_descriptor *blob, int status, void *_ctx)
2374 struct win32_apply_ctx *ctx = _ctx;
2376 const struct wim_dentry *dentry;
2383 if (unlikely(ctx->common.extract_flags & COMPACT_FLAGS))
2384 handle_system_compression(blob, ctx);
2386 if (likely(!ctx->data_buffer_ptr))
2389 if (!list_empty(&ctx->reparse_dentries)) {
2390 if (blob->size > REPARSE_DATA_MAX_SIZE) {
2391 dentry = list_first_entry(&ctx->reparse_dentries,
2392 struct wim_dentry, d_tmp_list);
2393 build_extraction_path(dentry, ctx);
2394 ERROR("Reparse data of \"%ls\" has size "
2395 "%"PRIu64" bytes (exceeds %u bytes)",
2396 current_path(ctx), blob->size,
2397 REPARSE_DATA_MAX_SIZE);
2398 ret = WIMLIB_ERR_INVALID_REPARSE_DATA;
2399 return check_apply_error(dentry, ctx, ret);
2402 memcpy(ctx->rpbuf.rpdata, ctx->data_buffer, blob->size);
2404 list_for_each_entry(dentry, &ctx->reparse_dentries, d_tmp_list) {
2406 /* Reparse point header */
2407 complete_reparse_point(&ctx->rpbuf, dentry->d_inode,
2410 ret = set_reparse_point(dentry, &ctx->rpbuf,
2411 REPARSE_DATA_OFFSET + blob->size,
2413 ret = check_apply_error(dentry, ctx, ret);
2419 if (!list_empty(&ctx->encrypted_dentries)) {
2420 ctx->encrypted_size = blob->size;
2421 list_for_each_entry(dentry, &ctx->encrypted_dentries, d_tmp_list) {
2422 ret = extract_encrypted_file(dentry, ctx);
2423 ret = check_apply_error(dentry, ctx, ret);
2426 /* Re-open the target directory if needed. */
2427 ret = open_target_directory(ctx);
2436 /* Attributes that can't be set directly */
2437 #define SPECIAL_ATTRIBUTES \
2438 (FILE_ATTRIBUTE_REPARSE_POINT | \
2439 FILE_ATTRIBUTE_DIRECTORY | \
2440 FILE_ATTRIBUTE_ENCRYPTED | \
2441 FILE_ATTRIBUTE_SPARSE_FILE | \
2442 FILE_ATTRIBUTE_COMPRESSED)
2444 /* Set the security descriptor @desc, of @desc_size bytes, on the file with open
2447 set_security_descriptor(HANDLE h, const void *_desc,
2448 size_t desc_size, struct win32_apply_ctx *ctx)
2450 SECURITY_INFORMATION info;
2452 SECURITY_DESCRIPTOR_RELATIVE *desc;
2455 * Ideally, we would just pass in the security descriptor buffer as-is.
2456 * But it turns out that Windows can mess up the security descriptor
2457 * even when using the low-level NtSetSecurityObject() function:
2459 * - Windows will clear SE_DACL_AUTO_INHERITED if it is set in the
2460 * passed buffer. To actually get Windows to set
2461 * SE_DACL_AUTO_INHERITED, the application must set the non-persistent
2462 * flag SE_DACL_AUTO_INHERIT_REQ. As usual, Microsoft didn't bother
2463 * to properly document either of these flags. It's unclear how
2464 * important SE_DACL_AUTO_INHERITED actually is, but to be safe we use
2465 * the SE_DACL_AUTO_INHERIT_REQ workaround to set it if needed.
2467 * - The above also applies to the equivalent SACL flags,
2468 * SE_SACL_AUTO_INHERITED and SE_SACL_AUTO_INHERIT_REQ.
2470 * - If the application says that it's setting
2471 * DACL_SECURITY_INFORMATION, then Windows sets SE_DACL_PRESENT in the
2472 * resulting security descriptor, even if the security descriptor the
2473 * application provided did not have a DACL. This seems to be
2474 * unavoidable, since omitting DACL_SECURITY_INFORMATION would cause a
2475 * default DACL to remain. Fortunately, this behavior seems harmless,
2476 * since the resulting DACL will still be "null" --- but it will be
2477 * "the other representation of null".
2479 * - The above also applies to SACL_SECURITY_INFORMATION and
2480 * SE_SACL_PRESENT. Again, it's seemingly unavoidable but "harmless"
2481 * that Windows changes the representation of a "null SACL".
2483 if (likely(desc_size <= STACK_MAX)) {
2484 desc = alloca(desc_size);
2486 desc = MALLOC(desc_size);
2488 return STATUS_NO_MEMORY;
2491 memcpy(desc, _desc, desc_size);
2493 if (likely(desc_size >= 4)) {
2495 if (desc->Control & SE_DACL_AUTO_INHERITED)
2496 desc->Control |= SE_DACL_AUTO_INHERIT_REQ;
2498 if (desc->Control & SE_SACL_AUTO_INHERITED)
2499 desc->Control |= SE_SACL_AUTO_INHERIT_REQ;
2503 * More API insanity. We want to set the entire security descriptor
2504 * as-is. But all available APIs require specifying the specific parts
2505 * of the security descriptor being set. Especially annoying is that
2506 * mandatory integrity labels are part of the SACL, but they aren't set
2507 * with SACL_SECURITY_INFORMATION. Instead, applications must also
2508 * specify LABEL_SECURITY_INFORMATION (Windows Vista, Windows 7) or
2509 * BACKUP_SECURITY_INFORMATION (Windows 8). But at least older versions
2510 * of Windows don't error out if you provide these newer flags...
2512 * Also, if the process isn't running as Administrator, then it probably
2513 * doesn't have SE_RESTORE_PRIVILEGE. In this case, it will always get
2514 * the STATUS_PRIVILEGE_NOT_HELD error by trying to set the SACL, even
2515 * if the security descriptor it provided did not have a SACL. By
2516 * default, in this case we try to recover and set as much of the
2517 * security descriptor as possible --- potentially excluding the DACL, and
2518 * even the owner, as well as the SACL.
2521 info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
2522 DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION |
2523 LABEL_SECURITY_INFORMATION | BACKUP_SECURITY_INFORMATION;
2527 * It's also worth noting that SetFileSecurity() is unusable because it
2528 * doesn't request "backup semantics" when it opens the file internally.
2529 * NtSetSecurityObject() seems to be the best function to use in backup
2530 * applications. (SetSecurityInfo() should also work, but it's harder
2531 * to use and must call NtSetSecurityObject() internally anyway.
2532 * BackupWrite() is theoretically usable as well, but it's inflexible
2533 * and poorly documented.)
2537 status = (*func_NtSetSecurityObject)(h, info, desc);
2538 if (NT_SUCCESS(status))
2539 goto out_maybe_free_desc;
2541 /* Failed to set the requested parts of the security descriptor. If the
2542 * error was permissions-related, try to set fewer parts of the security
2543 * descriptor, unless WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled. */
2544 if ((status == STATUS_PRIVILEGE_NOT_HELD ||
2545 status == STATUS_ACCESS_DENIED) &&
2546 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2548 if (info & SACL_SECURITY_INFORMATION) {
2549 info &= ~(SACL_SECURITY_INFORMATION |
2550 LABEL_SECURITY_INFORMATION |
2551 BACKUP_SECURITY_INFORMATION);
2552 ctx->partial_security_descriptors++;
2555 if (info & DACL_SECURITY_INFORMATION) {
2556 info &= ~DACL_SECURITY_INFORMATION;
2559 if (info & OWNER_SECURITY_INFORMATION) {
2560 info &= ~OWNER_SECURITY_INFORMATION;
2563 /* Nothing left except GROUP, and if we removed it we
2564 * wouldn't have anything at all. */
2567 /* No part of the security descriptor could be set, or
2568 * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled and the full security
2569 * descriptor could not be set. */
2570 if (!(info & SACL_SECURITY_INFORMATION))
2571 ctx->partial_security_descriptors--;
2572 ctx->no_security_descriptors++;
2574 out_maybe_free_desc:
2575 if (unlikely(desc_size > STACK_MAX))
2580 /* Set metadata on the open file @h from the WIM inode @inode. */
2582 do_apply_metadata_to_file(HANDLE h, const struct wim_inode *inode,
2583 struct win32_apply_ctx *ctx)
2585 FILE_BASIC_INFORMATION info;
2588 /* Set security descriptor if present and not in NO_ACLS mode */
2589 if (inode_has_security_descriptor(inode) &&
2590 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
2592 const struct wim_security_data *sd;
2596 sd = wim_get_current_security_data(ctx->common.wim);
2597 desc = sd->descriptors[inode->i_security_id];
2598 desc_size = sd->sizes[inode->i_security_id];
2600 status = set_security_descriptor(h, desc, desc_size, ctx);
2601 if (!NT_SUCCESS(status) &&
2602 (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2605 L"Can't set security descriptor on \"%ls\"",
2607 return WIMLIB_ERR_SET_SECURITY;
2611 /* Set attributes and timestamps */
2612 info.CreationTime.QuadPart = inode->i_creation_time;
2613 info.LastAccessTime.QuadPart = inode->i_last_access_time;
2614 info.LastWriteTime.QuadPart = inode->i_last_write_time;
2615 info.ChangeTime.QuadPart = 0;
2616 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES) {
2617 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
2619 info.FileAttributes = inode->i_attributes & ~SPECIAL_ATTRIBUTES;
2620 if (info.FileAttributes == 0)
2621 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
2624 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
2625 &info, sizeof(info),
2626 FileBasicInformation);
2627 /* On FAT volumes we get STATUS_INVALID_PARAMETER if we try to set
2628 * attributes on the root directory. (Apparently because FAT doesn't
2629 * actually have a place to store those attributes!) */
2630 if (!NT_SUCCESS(status)
2631 && !(status == STATUS_INVALID_PARAMETER &&
2632 dentry_is_root(inode_first_extraction_dentry(inode))))
2634 winnt_error(status, L"Can't set basic metadata on \"%ls\"",
2636 return WIMLIB_ERR_SET_ATTRIBUTES;
2643 apply_metadata_to_file(const struct wim_dentry *dentry,
2644 struct win32_apply_ctx *ctx)
2646 const struct wim_inode *inode = dentry->d_inode;
2652 perms = FILE_WRITE_ATTRIBUTES | WRITE_DAC |
2653 WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
2655 build_extraction_path(dentry, ctx);
2657 /* Open a handle with as many relevant permissions as possible. */
2658 while (!NT_SUCCESS(status = do_create_file(&h, perms, NULL,
2659 0, FILE_OPEN, 0, ctx)))
2661 if (status == STATUS_PRIVILEGE_NOT_HELD ||
2662 status == STATUS_ACCESS_DENIED)
2664 if (perms & ACCESS_SYSTEM_SECURITY) {
2665 perms &= ~ACCESS_SYSTEM_SECURITY;
2668 if (perms & WRITE_DAC) {
2669 perms &= ~WRITE_DAC;
2672 if (perms & WRITE_OWNER) {
2673 perms &= ~WRITE_OWNER;
2677 winnt_error(status, L"Can't open \"%ls\" to set metadata",
2679 return WIMLIB_ERR_OPEN;
2682 ret = do_apply_metadata_to_file(h, inode, ctx);
2690 apply_metadata(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
2692 const struct wim_dentry *dentry;
2695 /* We go in reverse so that metadata is set on all a directory's
2696 * children before the directory itself. This avoids any potential
2697 * problems with attributes, timestamps, or security descriptors. */
2698 list_for_each_entry_reverse(dentry, dentry_list, d_extraction_list_node)
2700 ret = apply_metadata_to_file(dentry, ctx);
2701 ret = check_apply_error(dentry, ctx, ret);
2704 ret = report_file_metadata_applied(&ctx->common);
2711 /* Issue warnings about problems during the extraction for which warnings were
2712 * not already issued (due to the high number of potential warnings if we issued
2713 * them per-file). */
2715 do_warnings(const struct win32_apply_ctx *ctx)
2717 if (ctx->partial_security_descriptors == 0
2718 && ctx->no_security_descriptors == 0
2719 && ctx->num_set_short_name_failures == 0
2721 && ctx->num_remove_short_name_failures == 0
2726 WARNING("Extraction to \"%ls\" complete, but with one or more warnings:",
2727 ctx->common.target);
2728 if (ctx->num_set_short_name_failures) {
2729 WARNING("- Could not set short names on %lu files or directories",
2730 ctx->num_set_short_name_failures);
2733 if (ctx->num_remove_short_name_failures) {
2734 WARNING("- Could not remove short names on %lu files or directories"
2735 " (This is expected on Vista and earlier)",
2736 ctx->num_remove_short_name_failures);
2739 if (ctx->partial_security_descriptors) {
2740 WARNING("- Could only partially set the security descriptor\n"
2741 " on %lu files or directories.",
2742 ctx->partial_security_descriptors);
2744 if (ctx->no_security_descriptors) {
2745 WARNING("- Could not set security descriptor at all\n"
2746 " on %lu files or directories.",
2747 ctx->no_security_descriptors);
2749 if (ctx->partial_security_descriptors || ctx->no_security_descriptors) {
2750 WARNING("To fully restore all security descriptors, run the program\n"
2751 " with Administrator rights.");
2756 count_dentries(const struct list_head *dentry_list)
2758 const struct list_head *cur;
2761 list_for_each(cur, dentry_list)
2767 /* Extract files from a WIM image to a directory on Windows */
2769 win32_extract(struct list_head *dentry_list, struct apply_ctx *_ctx)
2772 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
2775 ret = prepare_target(dentry_list, ctx);
2779 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
2780 ret = start_wimboot_extraction(dentry_list, ctx);
2785 dentry_count = count_dentries(dentry_list);
2787 ret = start_file_structure_phase(&ctx->common, dentry_count);
2791 ret = create_directories(dentry_list, ctx);
2795 ret = create_nondirectories(dentry_list, ctx);
2799 ret = end_file_structure_phase(&ctx->common);
2803 struct read_blob_callbacks cbs = {
2804 .begin_blob = begin_extract_blob,
2805 .consume_chunk = extract_chunk,
2806 .end_blob = end_extract_blob,
2809 ret = extract_blob_list(&ctx->common, &cbs);
2813 ret = start_file_metadata_phase(&ctx->common, dentry_count);
2817 ret = apply_metadata(dentry_list, ctx);
2821 ret = end_file_metadata_phase(&ctx->common);
2825 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
2826 ret = end_wimboot_extraction(ctx);
2833 close_target_directory(ctx);
2834 if (ctx->target_ntpath.Buffer)
2835 HeapFree(GetProcessHeap(), 0, ctx->target_ntpath.Buffer);
2836 FREE(ctx->pathbuf.Buffer);
2837 FREE(ctx->print_buffer);
2838 FREE(ctx->wimboot.wims);
2839 if (ctx->prepopulate_pats) {
2840 FREE(ctx->prepopulate_pats->strings);
2841 FREE(ctx->prepopulate_pats);
2843 FREE(ctx->mem_prepopulate_pats);
2844 FREE(ctx->data_buffer);
2848 const struct apply_operations win32_apply_ops = {
2850 .get_supported_features = win32_get_supported_features,
2851 .extract = win32_extract,
2852 .will_back_from_wim = win32_will_back_from_wim,
2853 .context_size = sizeof(struct win32_apply_ctx),
2856 #endif /* __WIN32__ */