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/reparse.h"
40 #include "wimlib/textfile.h"
41 #include "wimlib/xml.h"
42 #include "wimlib/wildcard.h"
43 #include "wimlib/wimboot.h"
45 struct win32_apply_ctx {
47 /* Extract flags, the pointer to the WIMStruct, etc. */
48 struct apply_ctx common;
50 /* WIMBoot information, only filled in if WIMLIB_EXTRACT_FLAG_WIMBOOT
53 /* This array contains the WIM files registered with WOF on the
54 * target volume for this extraction operation. All WIMStructs
55 * in this array are distinct and have ->filename != NULL. */
59 u8 blob_table_hash[SHA1_HASH_SIZE];
62 struct string_set *prepopulate_pats;
63 void *mem_prepopulate_pats;
65 bool tried_to_load_prepopulate_list;
67 bool have_wrong_version_wims;
68 bool have_uncompressed_wims;
69 bool have_unsupported_compressed_resources;
70 bool have_huge_resources;
73 /* Open handle to the target directory */
76 /* NT namespace path to the target directory (buffer allocated) */
77 UNICODE_STRING target_ntpath;
79 /* Temporary buffer for building paths (buffer allocated) */
80 UNICODE_STRING pathbuf;
82 /* Object attributes to reuse for opening files in the target directory.
83 * (attr.ObjectName == &pathbuf) and (attr.RootDirectory == h_target).
85 OBJECT_ATTRIBUTES attr;
87 /* Temporary I/O status block for system calls */
90 /* Allocated buffer for creating "printable" paths from our
91 * target-relative NT paths */
92 wchar_t *print_buffer;
94 /* Allocated buffer for reading blob data when it cannot be extracted
98 /* Pointer to the next byte in @data_buffer to fill */
101 /* Size allocated in @data_buffer */
102 size_t data_buffer_size;
104 /* Current offset in the raw encrypted file being written */
105 size_t encrypted_offset;
107 /* Current size of the raw encrypted file being written */
108 size_t encrypted_size;
110 /* Temporary buffer for reparse data */
111 struct reparse_buffer_disk rpbuf;
113 /* Temporary buffer for reparse data of "fixed" absolute symbolic links
115 struct reparse_buffer_disk rpfixbuf;
117 /* Array of open handles to filesystem streams currently being written
119 HANDLE open_handles[MAX_OPEN_FILES];
121 /* Number of handles in @open_handles currently open (filled in from the
122 * beginning of the array) */
123 unsigned num_open_handles;
125 /* List of dentries, joined by @tmp_list, that need to have reparse data
126 * extracted as soon as the whole blob has been read into @data_buffer.
128 struct list_head reparse_dentries;
130 /* List of dentries, joined by @tmp_list, that need to have raw
131 * encrypted data extracted as soon as the whole blob has been read into
133 struct list_head encrypted_dentries;
135 /* Number of files for which we didn't have permission to set the full
136 * security descriptor. */
137 unsigned long partial_security_descriptors;
139 /* Number of files for which we didn't have permission to set any part
140 * of the security descriptor. */
141 unsigned long no_security_descriptors;
143 /* Number of files for which we couldn't set the short name. */
144 unsigned long num_set_short_name_failures;
146 /* Number of files for which we couldn't remove the short name. */
147 unsigned long num_remove_short_name_failures;
149 /* Have we tried to enable short name support on the target volume yet?
151 bool tried_to_enable_short_names;
154 /* Get the drive letter from a Windows path, or return the null character if the
155 * path is relative. */
157 get_drive_letter(const wchar_t *path)
159 /* Skip \\?\ prefix */
160 if (!wcsncmp(path, L"\\\\?\\", 4))
163 /* Return drive letter if valid */
164 if (((path[0] >= L'a' && path[0] <= L'z') ||
165 (path[0] >= L'A' && path[0] <= L'Z')) && path[1] == L':')
172 get_vol_flags(const wchar_t *target, DWORD *vol_flags_ret,
173 bool *short_names_supported_ret)
175 wchar_t filesystem_name[MAX_PATH + 1];
177 wchar_t *volume = NULL;
180 *short_names_supported_ret = false;
182 drive[0] = get_drive_letter(target);
190 if (!GetVolumeInformation(volume, NULL, 0, NULL, NULL,
191 vol_flags_ret, filesystem_name,
192 ARRAY_LEN(filesystem_name)))
194 win32_warning(GetLastError(),
195 L"Failed to get volume information for \"%ls\"",
200 if (wcsstr(filesystem_name, L"NTFS")) {
201 /* FILE_SUPPORTS_HARD_LINKS is only supported on Windows 7 and
202 * later. Force it on anyway if filesystem is NTFS. */
203 *vol_flags_ret |= FILE_SUPPORTS_HARD_LINKS;
205 /* There's no volume flag for short names, but according to the
206 * MS documentation they are only user-settable on NTFS. */
207 *short_names_supported_ret = true;
211 static const wchar_t *
212 current_path(struct win32_apply_ctx *ctx);
215 build_extraction_path(const struct wim_dentry *dentry,
216 struct win32_apply_ctx *ctx);
219 report_dentry_apply_error(const struct wim_dentry *dentry,
220 struct win32_apply_ctx *ctx, int ret)
222 build_extraction_path(dentry, ctx);
223 return report_apply_error(&ctx->common, ret, current_path(ctx));
227 check_apply_error(const struct wim_dentry *dentry,
228 struct win32_apply_ctx *ctx, int ret)
231 ret = report_dentry_apply_error(dentry, ctx, ret);
236 win32_get_supported_features(const wchar_t *target,
237 struct wim_features *supported_features)
240 bool short_names_supported;
242 /* Query the features of the target volume. */
244 get_vol_flags(target, &vol_flags, &short_names_supported);
246 supported_features->archive_files = 1;
247 supported_features->hidden_files = 1;
248 supported_features->system_files = 1;
250 if (vol_flags & FILE_FILE_COMPRESSION)
251 supported_features->compressed_files = 1;
253 if (vol_flags & FILE_SUPPORTS_ENCRYPTION) {
254 supported_features->encrypted_files = 1;
255 supported_features->encrypted_directories = 1;
258 supported_features->not_context_indexed_files = 1;
260 /* Don't do anything with FILE_SUPPORTS_SPARSE_FILES. */
262 if (vol_flags & FILE_NAMED_STREAMS)
263 supported_features->named_data_streams = 1;
265 if (vol_flags & FILE_SUPPORTS_HARD_LINKS)
266 supported_features->hard_links = 1;
268 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS)
269 supported_features->reparse_points = 1;
271 if (vol_flags & FILE_PERSISTENT_ACLS)
272 supported_features->security_descriptors = 1;
274 if (short_names_supported)
275 supported_features->short_names = 1;
277 supported_features->timestamps = 1;
279 /* Note: Windows does not support case sensitive filenames! At least
280 * not without changing the registry and rebooting... */
285 /* Load the patterns from [PrepopulateList] of WimBootCompress.ini in the WIM
286 * image being extracted. */
288 load_prepopulate_pats(struct win32_apply_ctx *ctx)
290 const wchar_t *path = L"\\Windows\\System32\\WimBootCompress.ini";
291 struct wim_dentry *dentry;
292 struct blob_descriptor *blob;
295 struct string_set *s;
297 struct text_file_section sec;
299 ctx->wimboot.tried_to_load_prepopulate_list = true;
301 dentry = get_dentry(ctx->common.wim, path, WIMLIB_CASE_INSENSITIVE);
303 (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
304 FILE_ATTRIBUTE_REPARSE_POINT |
305 FILE_ATTRIBUTE_ENCRYPTED)) ||
306 !(blob = inode_get_blob_for_unnamed_data_stream(dentry->d_inode,
307 ctx->common.wim->blob_table)))
309 WARNING("%ls does not exist in the WIM image.\n"
310 " The default configuration will be used instead; it assumes that all\n"
311 " files are valid for external backing regardless of path, equivalent\n"
312 " to an empty [PrepopulateList] section.", path);
313 return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
316 ret = read_full_blob_into_alloc_buf(blob, &buf);
320 s = CALLOC(1, sizeof(struct string_set));
323 return WIMLIB_ERR_NOMEM;
326 sec.name = T("PrepopulateList");
329 ret = do_load_text_file(path, buf, blob->size, &mem, &sec, 1,
330 LOAD_TEXT_FILE_REMOVE_QUOTES |
331 LOAD_TEXT_FILE_NO_WARNINGS,
333 BUILD_BUG_ON(OS_PREFERRED_PATH_SEPARATOR != WIM_PATH_SEPARATOR);
339 ctx->wimboot.prepopulate_pats = s;
340 ctx->wimboot.mem_prepopulate_pats = mem;
344 /* Returns %true if the specified absolute path to a file in the WIM image
345 * matches a pattern in [PrepopulateList] of WimBootCompress.ini. Otherwise
348 in_prepopulate_list(const wchar_t *path, size_t path_nchars,
349 const struct win32_apply_ctx *ctx)
351 const struct string_set *pats = ctx->wimboot.prepopulate_pats;
353 if (!pats || !pats->num_strings)
356 return match_pattern_list(path, path_nchars, pats);
359 /* Returns %true if the specified absolute path to a file in the WIM image can
360 * be subject to external backing when extracted. Otherwise returns %false. */
362 can_externally_back_path(const wchar_t *path, size_t path_nchars,
363 const struct win32_apply_ctx *ctx)
365 if (in_prepopulate_list(path, path_nchars, ctx))
368 /* Since we attempt to modify the SYSTEM registry after it's extracted
369 * (see end_wimboot_extraction()), it can't be extracted as externally
370 * backed. This extends to associated files such as SYSTEM.LOG that
371 * also must be writable in order to write to the registry. Normally,
372 * SYSTEM is in [PrepopulateList], and the SYSTEM.* files match patterns
373 * in [ExclusionList] and therefore are not captured in the WIM at all.
374 * However, a WIM that wasn't specifically captured in "WIMBoot mode"
375 * may contain SYSTEM.* files. So to make things "just work", hard-code
377 if (match_path(path, path_nchars, L"\\Windows\\System32\\config\\SYSTEM*",
378 OS_PREFERRED_PATH_SEPARATOR, false))
385 is_resource_valid_for_external_backing(const struct wim_resource_descriptor *rdesc,
386 struct win32_apply_ctx *ctx)
388 /* Must be the original WIM file format. This check excludes pipable
389 * resources and solid resources. It also excludes other resources
390 * contained in such files even if they would be otherwise compatible.
392 if (rdesc->wim->hdr.magic != WIM_MAGIC ||
393 rdesc->wim->hdr.wim_version != WIM_VERSION_DEFAULT)
395 ctx->wimboot.have_wrong_version_wims = true;
400 * Whitelist of compression types and chunk sizes supported by
401 * Microsoft's WOF driver.
404 * - Uncompressed WIMs result in BSOD. However, this only applies to
405 * the WIM file itself, not to uncompressed resources in a WIM file
406 * that is otherwise compressed.
407 * - XPRESS 64K sometimes appears to work, but sometimes it causes
408 * reads to fail with STATUS_UNSUCCESSFUL.
410 switch (rdesc->compression_type) {
411 case WIMLIB_COMPRESSION_TYPE_NONE:
412 if (rdesc->wim->compression_type == WIMLIB_COMPRESSION_TYPE_NONE) {
413 ctx->wimboot.have_uncompressed_wims = true;
417 case WIMLIB_COMPRESSION_TYPE_XPRESS:
418 switch (rdesc->chunk_size) {
425 ctx->wimboot.have_unsupported_compressed_resources = true;
429 case WIMLIB_COMPRESSION_TYPE_LZX:
430 switch (rdesc->chunk_size) {
434 ctx->wimboot.have_unsupported_compressed_resources = true;
439 ctx->wimboot.have_unsupported_compressed_resources = true;
443 /* Microsoft's WoF driver errors out if it tries to satisfy a read with
444 * ending offset >= 4 GiB from an externally backed file. */
445 if (rdesc->uncompressed_size > 4200000000) {
446 ctx->wimboot.have_huge_resources = true;
453 #define WIM_BACKING_NOT_ENABLED -1
454 #define WIM_BACKING_NOT_POSSIBLE -2
455 #define WIM_BACKING_EXCLUDED -3
458 will_externally_back_inode(struct wim_inode *inode, struct win32_apply_ctx *ctx,
459 const struct wim_dentry **excluded_dentry_ret)
461 struct list_head *next;
462 struct wim_dentry *dentry;
463 struct blob_descriptor *blob;
466 if (inode->i_can_externally_back)
469 /* This may do redundant checks because the cached value
470 * i_can_externally_back is 2-state (as opposed to 3-state:
471 * unknown/no/yes). But most files can be externally backed, so this
474 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
475 FILE_ATTRIBUTE_REPARSE_POINT |
476 FILE_ATTRIBUTE_ENCRYPTED))
477 return WIM_BACKING_NOT_POSSIBLE;
479 blob = inode_get_blob_for_unnamed_data_stream_resolved(inode);
481 if (!blob || blob->blob_location != BLOB_IN_WIM ||
482 !is_resource_valid_for_external_backing(blob->rdesc, ctx))
483 return WIM_BACKING_NOT_POSSIBLE;
486 * We need to check the patterns in [PrepopulateList] against every name
487 * of the inode, in case any of them match.
489 next = inode->i_extraction_aliases.next;
491 dentry = list_entry(next, struct wim_dentry,
492 d_extraction_alias_node);
494 ret = calculate_dentry_full_path(dentry);
498 if (!can_externally_back_path(dentry->_full_path,
499 wcslen(dentry->_full_path), ctx))
501 if (excluded_dentry_ret)
502 *excluded_dentry_ret = dentry;
503 return WIM_BACKING_EXCLUDED;
506 } while (next != &inode->i_extraction_aliases);
508 inode->i_can_externally_back = 1;
513 * Determines if the unnamed data stream of a file will be created as an
514 * external backing, as opposed to a standard extraction.
517 win32_will_externally_back(struct wim_dentry *dentry, struct apply_ctx *_ctx)
519 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
521 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
522 return WIM_BACKING_NOT_ENABLED;
524 if (!ctx->wimboot.tried_to_load_prepopulate_list)
525 if (load_prepopulate_pats(ctx) == WIMLIB_ERR_NOMEM)
526 return WIMLIB_ERR_NOMEM;
528 return will_externally_back_inode(dentry->d_inode, ctx, NULL);
531 /* Find the WOF registration information for the specified WIM file. */
532 static struct wimboot_wim *
533 find_wimboot_wim(WIMStruct *wim_to_find, struct win32_apply_ctx *ctx)
535 for (size_t i = 0; i < ctx->wimboot.num_wims; i++)
536 if (wim_to_find == ctx->wimboot.wims[i].wim)
537 return &ctx->wimboot.wims[i];
544 set_external_backing(HANDLE h, struct wim_inode *inode, struct win32_apply_ctx *ctx)
547 const struct wim_dentry *excluded_dentry;
548 const struct blob_descriptor *blob;
549 const struct wimboot_wim *wimboot_wim;
551 ret = will_externally_back_inode(inode, ctx, &excluded_dentry);
552 if (ret > 0) /* Error. */
555 if (ret < 0 && ret != WIM_BACKING_EXCLUDED)
556 return 0; /* Not externally backing, other than due to exclusion. */
558 if (unlikely(ret == WIM_BACKING_EXCLUDED)) {
559 /* Not externally backing due to exclusion. */
560 union wimlib_progress_info info;
562 build_extraction_path(excluded_dentry, ctx);
564 info.wimboot_exclude.path_in_wim = excluded_dentry->_full_path;
565 info.wimboot_exclude.extraction_path = current_path(ctx);
567 return call_progress(ctx->common.progfunc,
568 WIMLIB_PROGRESS_MSG_WIMBOOT_EXCLUDE,
569 &info, ctx->common.progctx);
572 /* Externally backing. */
574 blob = inode_get_blob_for_unnamed_data_stream_resolved(inode);
575 wimboot_wim = find_wimboot_wim(blob->rdesc->wim, ctx);
577 if (unlikely(!wimboot_set_pointer(h,
579 wimboot_wim->data_source_id,
580 wimboot_wim->blob_table_hash,
581 ctx->wimboot.wof_running)))
583 const DWORD err = GetLastError();
585 build_extraction_path(inode_first_extraction_dentry(inode), ctx);
586 win32_error(err, L"\"%ls\": Couldn't set WIMBoot pointer data",
588 return WIMLIB_ERR_WIMBOOT;
593 /* Calculates the SHA-1 message digest of the WIM's blob table. */
595 hash_blob_table(WIMStruct *wim, u8 hash[SHA1_HASH_SIZE])
597 return wim_reshdr_to_hash(&wim->hdr.blob_table_reshdr, wim, hash);
601 register_wim_with_wof(WIMStruct *wim, struct win32_apply_ctx *ctx)
603 struct wimboot_wim *p;
606 /* Check if already registered */
607 for (size_t i = 0; i < ctx->wimboot.num_wims; i++)
608 if (wim == ctx->wimboot.wims[i].wim)
611 /* Not yet registered */
613 p = REALLOC(ctx->wimboot.wims,
614 (ctx->wimboot.num_wims + 1) * sizeof(ctx->wimboot.wims[0]));
616 return WIMLIB_ERR_NOMEM;
617 ctx->wimboot.wims = p;
619 ctx->wimboot.wims[ctx->wimboot.num_wims].wim = wim;
621 ret = hash_blob_table(wim, ctx->wimboot.wims[ctx->wimboot.num_wims].blob_table_hash);
625 ret = wimboot_alloc_data_source_id(wim->filename,
627 ctx->common.wim->current_image,
629 &ctx->wimboot.wims[ctx->wimboot.num_wims].data_source_id,
630 &ctx->wimboot.wof_running);
634 ctx->wimboot.num_wims++;
638 /* Prepare for doing a "WIMBoot" extraction by loading patterns from
639 * [PrepopulateList] of WimBootCompress.ini and registering each source WIM file
640 * with WOF on the target volume. */
642 start_wimboot_extraction(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
645 struct wim_dentry *dentry;
647 if (!ctx->wimboot.tried_to_load_prepopulate_list)
648 if (load_prepopulate_pats(ctx) == WIMLIB_ERR_NOMEM)
649 return WIMLIB_ERR_NOMEM;
651 if (!wim_info_get_wimboot(ctx->common.wim->wim_info,
652 ctx->common.wim->current_image))
653 WARNING("The WIM image is not marked as WIMBoot compatible. This usually\n"
654 " means it is not intended to be used to back a Windows operating\n"
655 " system. Proceeding anyway.");
657 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
658 struct blob_descriptor *blob;
660 ret = win32_will_externally_back(dentry, &ctx->common);
661 if (ret > 0) /* Error */
663 if (ret < 0) /* Won't externally back */
666 blob = inode_get_blob_for_unnamed_data_stream_resolved(dentry->d_inode);
667 ret = register_wim_with_wof(blob->rdesc->wim, ctx);
672 if (ctx->wimboot.have_wrong_version_wims) {
673 WARNING("At least one of the source WIM files uses a version of the WIM\n"
674 " file format that not supported by Microsoft's wof.sys driver.\n"
675 " Files whose data is contained in one of these WIM files will be\n"
676 " extracted as full files rather than externally backed.");
679 if (ctx->wimboot.have_uncompressed_wims) {
680 WARNING("At least one of the source WIM files is uncompressed. Files whose\n"
681 " data is contained in an uncompressed WIM file will be extracted as\n"
682 " full files rather than externally backed, since uncompressed WIM\n"
683 " files are not supported by Microsoft's wof.sys driver.");
686 if (ctx->wimboot.have_unsupported_compressed_resources) {
687 WARNING("At least one of the source WIM files uses a compression format that\n"
688 " is not supported by Microsoft's wof.sys driver. Files whose data is\n"
689 " contained in a compressed resource in one of these WIM files will be\n"
690 " extracted as full files rather than externally backed. (The\n"
691 " compression formats supported by wof.sys are: XPRESS 4K, XPRESS 8K,\n"
692 " XPRESS 16K, XPRESS 32K, and LZX 32K.)");
695 if (ctx->wimboot.have_huge_resources) {
696 WARNING("Some files exceeded 4.2 GB in size. Such files will be extracted\n"
697 " as full files rather than externally backed, since very large files\n"
698 " are not supported by Microsoft's wof.sys driver.");
705 build_win32_extraction_path(const struct wim_dentry *dentry,
706 struct win32_apply_ctx *ctx);
708 /* Sets WimBoot=1 in the extracted SYSTEM registry hive.
710 * WIMGAPI does this, and it's possible that it's important.
711 * But I don't know exactly what this value means to Windows. */
713 end_wimboot_extraction(struct win32_apply_ctx *ctx)
715 struct wim_dentry *dentry;
716 wchar_t subkeyname[32];
722 dentry = get_dentry(ctx->common.wim, L"\\Windows\\System32\\config\\SYSTEM",
723 WIMLIB_CASE_INSENSITIVE);
725 if (!dentry || !will_extract_dentry(dentry))
728 if (!will_extract_dentry(wim_get_current_root_dentry(ctx->common.wim)))
731 /* Not bothering to use the native routines (e.g. NtLoadKey()) for this.
732 * If this doesn't work, you probably also have many other problems. */
734 build_win32_extraction_path(dentry, ctx);
736 randomize_char_array_with_alnum(subkeyname, 20);
737 subkeyname[20] = L'\0';
739 res = RegLoadKey(HKEY_LOCAL_MACHINE, subkeyname, ctx->pathbuf.Buffer);
743 wcscpy(&subkeyname[20], L"\\Setup");
745 res = RegCreateKeyEx(HKEY_LOCAL_MACHINE, subkeyname, 0, NULL,
746 REG_OPTION_BACKUP_RESTORE, 0, NULL, &key, NULL);
752 res = RegSetValueEx(key, L"WimBoot", 0, REG_DWORD,
753 (const BYTE *)&value, sizeof(DWORD));
757 res = RegFlushKey(key);
760 res2 = RegCloseKey(key);
764 subkeyname[20] = L'\0';
765 RegUnLoadKey(HKEY_LOCAL_MACHINE, subkeyname);
769 win32_warning(res, L"Failed to set \\Setup: dword \"WimBoot\"=1 "
770 "value in registry hive \"%ls\"",
771 ctx->pathbuf.Buffer);
777 /* Returns the number of wide characters needed to represent the path to the
778 * specified @dentry, relative to the target directory, when extracted.
780 * Does not include null terminator (not needed for NtCreateFile). */
782 dentry_extraction_path_length(const struct wim_dentry *dentry)
785 const struct wim_dentry *d;
789 len += d->d_extraction_name_nchars + 1;
791 } while (!dentry_is_root(d) && will_extract_dentry(d));
793 return --len; /* No leading slash */
796 /* Returns the length of the longest string that might need to be appended to
797 * the path to an alias of an inode to open or create a named data stream.
799 * If the inode has no named data streams, this will be 0. Otherwise, this will
800 * be 1 plus the length of the longest-named data stream, since the data stream
801 * name must be separated from the path by the ':' character. */
803 inode_longest_named_data_stream_spec(const struct wim_inode *inode)
806 for (unsigned i = 0; i < inode->i_num_streams; i++) {
807 const struct wim_inode_stream *strm = &inode->i_streams[i];
808 if (!stream_is_named_data_stream(strm))
810 size_t len = utf16le_len_chars(strm->stream_name);
819 /* Find the length, in wide characters, of the longest path needed for
820 * extraction of any file in @dentry_list relative to the target directory.
822 * Accounts for named data streams, but does not include null terminator (not
823 * needed for NtCreateFile). */
825 compute_path_max(struct list_head *dentry_list)
828 const struct wim_dentry *dentry;
830 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
833 len = dentry_extraction_path_length(dentry);
835 /* Account for named data streams */
836 len += inode_longest_named_data_stream_spec(dentry->d_inode);
845 /* Build the path at which to extract the @dentry, relative to the target
848 * The path is saved in ctx->pathbuf. */
850 build_extraction_path(const struct wim_dentry *dentry,
851 struct win32_apply_ctx *ctx)
855 const struct wim_dentry *d;
857 len = dentry_extraction_path_length(dentry);
859 ctx->pathbuf.Length = len * sizeof(wchar_t);
860 p = ctx->pathbuf.Buffer + len;
862 !dentry_is_root(d->d_parent) && will_extract_dentry(d->d_parent);
865 p -= d->d_extraction_name_nchars;
866 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
869 /* No leading slash */
870 p -= d->d_extraction_name_nchars;
871 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
874 /* Build the path at which to extract the @dentry, relative to the target
875 * directory, adding the suffix for a named data stream.
877 * The path is saved in ctx->pathbuf. */
879 build_extraction_path_with_ads(const struct wim_dentry *dentry,
880 struct win32_apply_ctx *ctx,
881 const wchar_t *stream_name,
882 size_t stream_name_nchars)
886 build_extraction_path(dentry, ctx);
888 /* Add :NAME for named data stream */
889 p = ctx->pathbuf.Buffer + (ctx->pathbuf.Length / sizeof(wchar_t));
891 wmemcpy(p, stream_name, stream_name_nchars);
892 ctx->pathbuf.Length += (1 + stream_name_nchars) * sizeof(wchar_t);
895 /* Build the Win32 namespace path to the specified @dentry when extracted.
897 * The path is saved in ctx->pathbuf and will be null terminated.
899 * XXX: We could get rid of this if it wasn't needed for the file encryption
900 * APIs, and the registry manipulation in WIMBoot mode. */
902 build_win32_extraction_path(const struct wim_dentry *dentry,
903 struct win32_apply_ctx *ctx)
905 build_extraction_path(dentry, ctx);
907 /* Prepend target_ntpath to our relative path, then change \??\ into \\?\ */
909 memmove(ctx->pathbuf.Buffer +
910 (ctx->target_ntpath.Length / sizeof(wchar_t)) + 1,
911 ctx->pathbuf.Buffer, ctx->pathbuf.Length);
912 memcpy(ctx->pathbuf.Buffer, ctx->target_ntpath.Buffer,
913 ctx->target_ntpath.Length);
914 ctx->pathbuf.Buffer[ctx->target_ntpath.Length / sizeof(wchar_t)] = L'\\';
915 ctx->pathbuf.Length += ctx->target_ntpath.Length + sizeof(wchar_t);
916 ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)] = L'\0';
918 wimlib_assert(ctx->pathbuf.Length >= 4 * sizeof(wchar_t) &&
919 !wmemcmp(ctx->pathbuf.Buffer, L"\\??\\", 4));
921 ctx->pathbuf.Buffer[1] = L'\\';
925 /* Returns a "printable" representation of the last relative NT path that was
926 * constructed with build_extraction_path() or build_extraction_path_with_ads().
928 * This will be overwritten by the next call to this function. */
929 static const wchar_t *
930 current_path(struct win32_apply_ctx *ctx)
932 wchar_t *p = ctx->print_buffer;
934 p = wmempcpy(p, ctx->common.target, ctx->common.target_nchars);
936 p = wmempcpy(p, ctx->pathbuf.Buffer, ctx->pathbuf.Length / sizeof(wchar_t));
938 return ctx->print_buffer;
941 /* Open handle to the target directory if it is not already open. If the target
942 * directory does not exist, this creates it. */
944 open_target_directory(struct win32_apply_ctx *ctx)
951 ctx->attr.Length = sizeof(ctx->attr);
952 ctx->attr.RootDirectory = NULL;
953 ctx->attr.ObjectName = &ctx->target_ntpath;
954 status = (*func_NtCreateFile)(&ctx->h_target,
960 FILE_SHARE_VALID_FLAGS,
962 FILE_DIRECTORY_FILE |
963 FILE_OPEN_REPARSE_POINT |
964 FILE_OPEN_FOR_BACKUP_INTENT,
967 if (!NT_SUCCESS(status)) {
968 winnt_error(status, L"Can't open or create directory \"%ls\"",
970 return WIMLIB_ERR_OPENDIR;
972 ctx->attr.RootDirectory = ctx->h_target;
973 ctx->attr.ObjectName = &ctx->pathbuf;
978 close_target_directory(struct win32_apply_ctx *ctx)
981 (*func_NtClose)(ctx->h_target);
982 ctx->h_target = NULL;
983 ctx->attr.RootDirectory = NULL;
988 * Ensures the target directory exists and opens a handle to it, in preparation
989 * of using paths relative to it.
992 prepare_target(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
997 ret = win32_path_to_nt_path(ctx->common.target, &ctx->target_ntpath);
1001 ret = open_target_directory(ctx);
1005 path_max = compute_path_max(dentry_list);
1006 /* Add some extra for building Win32 paths for the file encryption APIs,
1007 * and ensure we have at least enough to potentially use a 8.3 name for
1008 * the last component. */
1009 path_max += max(2 + (ctx->target_ntpath.Length / sizeof(wchar_t)),
1012 ctx->pathbuf.MaximumLength = path_max * sizeof(wchar_t);
1013 ctx->pathbuf.Buffer = MALLOC(ctx->pathbuf.MaximumLength);
1014 if (!ctx->pathbuf.Buffer)
1015 return WIMLIB_ERR_NOMEM;
1017 ctx->print_buffer = MALLOC((ctx->common.target_nchars + 1 + path_max + 1) *
1019 if (!ctx->print_buffer)
1020 return WIMLIB_ERR_NOMEM;
1025 /* When creating an inode that will have a short (DOS) name, we create it using
1026 * the long name associated with the short name. This ensures that the short
1027 * name gets associated with the correct long name. */
1028 static struct wim_dentry *
1029 first_extraction_alias(const struct wim_inode *inode)
1031 struct list_head *next = inode->i_extraction_aliases.next;
1032 struct wim_dentry *dentry;
1035 dentry = list_entry(next, struct wim_dentry,
1036 d_extraction_alias_node);
1037 if (dentry_has_short_name(dentry))
1040 } while (next != &inode->i_extraction_aliases);
1045 * Set or clear FILE_ATTRIBUTE_COMPRESSED if the inherited value is different
1046 * from the desired value.
1048 * Note that you can NOT override the inherited value of
1049 * FILE_ATTRIBUTE_COMPRESSED directly with NtCreateFile().
1052 adjust_compression_attribute(HANDLE h, const struct wim_dentry *dentry,
1053 struct win32_apply_ctx *ctx)
1055 const bool compressed = (dentry->d_inode->i_attributes &
1056 FILE_ATTRIBUTE_COMPRESSED);
1058 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
1061 if (!ctx->common.supported_features.compressed_files)
1064 FILE_BASIC_INFORMATION info;
1066 USHORT compression_state;
1068 /* Get current attributes */
1069 status = (*func_NtQueryInformationFile)(h, &ctx->iosb,
1070 &info, sizeof(info),
1071 FileBasicInformation);
1072 if (NT_SUCCESS(status) &&
1073 compressed == !!(info.FileAttributes & FILE_ATTRIBUTE_COMPRESSED))
1075 /* Nothing needs to be done. */
1079 /* Set the new compression state */
1082 compression_state = COMPRESSION_FORMAT_DEFAULT;
1084 compression_state = COMPRESSION_FORMAT_NONE;
1086 status = (*func_NtFsControlFile)(h,
1091 FSCTL_SET_COMPRESSION,
1096 if (NT_SUCCESS(status))
1099 winnt_error(status, L"Can't %s compression attribute on \"%ls\"",
1100 (compressed ? "set" : "clear"), current_path(ctx));
1101 return WIMLIB_ERR_SET_ATTRIBUTES;
1104 /* Try to enable short name support on the target volume. If successful, return
1105 * true. If unsuccessful, issue a warning and return false. */
1107 try_to_enable_short_names(const wchar_t *volume)
1110 FILE_FS_PERSISTENT_VOLUME_INFORMATION info;
1112 DWORD bytesReturned;
1114 h = CreateFile(volume, GENERIC_WRITE,
1115 FILE_SHARE_VALID_FLAGS, NULL, OPEN_EXISTING,
1116 FILE_FLAG_BACKUP_SEMANTICS, NULL);
1117 if (h == INVALID_HANDLE_VALUE)
1120 info.VolumeFlags = 0;
1121 info.FlagMask = PERSISTENT_VOLUME_STATE_SHORT_NAME_CREATION_DISABLED;
1125 bret = DeviceIoControl(h, FSCTL_SET_PERSISTENT_VOLUME_STATE,
1126 &info, sizeof(info), NULL, 0,
1127 &bytesReturned, NULL);
1136 win32_warning(GetLastError(),
1137 L"Failed to enable short name support on %ls",
1143 remove_conflicting_short_name(const struct wim_dentry *dentry, struct win32_apply_ctx *ctx)
1149 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1150 (13 * sizeof(wchar_t));
1151 u8 buf[bufsize] _aligned_attribute(8);
1152 bool retried = false;
1153 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1155 memset(buf, 0, bufsize);
1157 /* Build the path with the short name. */
1158 name = &ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)];
1159 while (name != ctx->pathbuf.Buffer && *(name - 1) != L'\\')
1161 end = mempcpy(name, dentry->short_name, dentry->short_name_nbytes);
1162 ctx->pathbuf.Length = ((u8 *)end - (u8 *)ctx->pathbuf.Buffer);
1164 /* Open the conflicting file (by short name). */
1165 status = (*func_NtOpenFile)(&h, GENERIC_WRITE | DELETE,
1166 &ctx->attr, &ctx->iosb,
1167 FILE_SHARE_VALID_FLAGS,
1168 FILE_OPEN_REPARSE_POINT | FILE_OPEN_FOR_BACKUP_INTENT);
1169 if (!NT_SUCCESS(status)) {
1170 winnt_warning(status, L"Can't open \"%ls\"", current_path(ctx));
1175 WARNING("Overriding conflicting short name; path=\"%ls\"",
1179 /* Try to remove the short name on the conflicting file. */
1182 status = (*func_NtSetInformationFile)(h, &ctx->iosb, info, bufsize,
1183 FileShortNameInformation);
1185 if (status == STATUS_INVALID_PARAMETER && !retried) {
1187 /* Microsoft forgot to make it possible to remove short names
1188 * until Windows 7. Oops. Use a random short name instead. */
1190 info->FileNameLength = 12 * sizeof(wchar_t);
1191 for (int i = 0; i < 8; i++)
1192 info->FileName[i] = 'A' + (rand() % 26);
1193 info->FileName[8] = L'.';
1194 info->FileName[9] = L'W';
1195 info->FileName[10] = L'L';
1196 info->FileName[11] = L'B';
1197 info->FileName[12] = L'\0';
1203 build_extraction_path(dentry, ctx);
1207 /* Set the short name on the open file @h which has been created at the location
1208 * indicated by @dentry.
1210 * Note that this may add, change, or remove the short name.
1212 * @h must be opened with DELETE access.
1214 * Returns 0 or WIMLIB_ERR_SET_SHORT_NAME. The latter only happens in
1215 * STRICT_SHORT_NAMES mode.
1218 set_short_name(HANDLE h, const struct wim_dentry *dentry,
1219 struct win32_apply_ctx *ctx)
1222 if (!ctx->common.supported_features.short_names)
1226 * Note: The size of the FILE_NAME_INFORMATION buffer must be such that
1227 * FileName contains at least 2 wide characters (4 bytes). Otherwise,
1228 * NtSetInformationFile() will return STATUS_INFO_LENGTH_MISMATCH. This
1229 * is despite the fact that FileNameLength can validly be 0 or 2 bytes,
1230 * with the former case being removing the existing short name if
1231 * present, rather than setting one.
1233 * The null terminator is seemingly optional, but to be safe we include
1234 * space for it and zero all unused space.
1237 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1238 max(dentry->short_name_nbytes, sizeof(wchar_t)) +
1240 u8 buf[bufsize] _aligned_attribute(8);
1241 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1243 bool tried_to_remove_existing = false;
1245 memset(buf, 0, bufsize);
1247 info->FileNameLength = dentry->short_name_nbytes;
1248 memcpy(info->FileName, dentry->short_name, dentry->short_name_nbytes);
1251 status = (*func_NtSetInformationFile)(h, &ctx->iosb, info, bufsize,
1252 FileShortNameInformation);
1253 if (NT_SUCCESS(status))
1256 if (status == STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME) {
1257 if (dentry->short_name_nbytes == 0)
1259 if (!ctx->tried_to_enable_short_names) {
1263 ctx->tried_to_enable_short_names = true;
1265 ret = win32_get_drive_path(ctx->common.target,
1269 if (try_to_enable_short_names(volume))
1275 * Short names can conflict in several cases:
1277 * - a file being extracted has a short name conflicting with an
1280 * - a file being extracted has a short name conflicting with another
1281 * file being extracted (possible, but shouldn't happen)
1283 * - a file being extracted has a short name that conflicts with the
1284 * automatically generated short name of a file we previously
1285 * extracted, but failed to set the short name for. Sounds unlikely,
1286 * but this actually does happen fairly often on versions of Windows
1287 * prior to Windows 7 because they do not support removing short names
1290 if (unlikely(status == STATUS_OBJECT_NAME_COLLISION) &&
1291 dentry->short_name_nbytes && !tried_to_remove_existing)
1293 tried_to_remove_existing = true;
1294 status = remove_conflicting_short_name(dentry, ctx);
1295 if (NT_SUCCESS(status))
1299 /* By default, failure to set short names is not an error (since short
1300 * names aren't too important anymore...). */
1301 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES)) {
1302 if (dentry->short_name_nbytes)
1303 ctx->num_set_short_name_failures++;
1305 ctx->num_remove_short_name_failures++;
1309 winnt_error(status, L"Can't set short name on \"%ls\"", current_path(ctx));
1310 return WIMLIB_ERR_SET_SHORT_NAME;
1314 * A wrapper around NtCreateFile() to make it slightly more usable...
1315 * This uses the path currently constructed in ctx->pathbuf.
1317 * Also, we always specify FILE_OPEN_FOR_BACKUP_INTENT and
1318 * FILE_OPEN_REPARSE_POINT.
1321 do_create_file(PHANDLE FileHandle,
1322 ACCESS_MASK DesiredAccess,
1323 PLARGE_INTEGER AllocationSize,
1324 ULONG FileAttributes,
1325 ULONG CreateDisposition,
1326 ULONG CreateOptions,
1327 struct win32_apply_ctx *ctx)
1329 return (*func_NtCreateFile)(FileHandle,
1335 FILE_SHARE_VALID_FLAGS,
1338 FILE_OPEN_FOR_BACKUP_INTENT |
1339 FILE_OPEN_REPARSE_POINT,
1344 /* Like do_create_file(), but builds the extraction path of the @dentry first.
1347 create_file(PHANDLE FileHandle,
1348 ACCESS_MASK DesiredAccess,
1349 PLARGE_INTEGER AllocationSize,
1350 ULONG FileAttributes,
1351 ULONG CreateDisposition,
1352 ULONG CreateOptions,
1353 const struct wim_dentry *dentry,
1354 struct win32_apply_ctx *ctx)
1356 build_extraction_path(dentry, ctx);
1357 return do_create_file(FileHandle,
1367 delete_file_or_stream(struct win32_apply_ctx *ctx)
1371 FILE_DISPOSITION_INFORMATION disposition_info;
1372 FILE_BASIC_INFORMATION basic_info;
1373 bool retried = false;
1375 status = do_create_file(&h,
1380 FILE_NON_DIRECTORY_FILE,
1382 if (unlikely(!NT_SUCCESS(status))) {
1383 winnt_error(status, L"Can't open \"%ls\" for deletion",
1385 return WIMLIB_ERR_OPEN;
1389 disposition_info.DoDeleteFile = TRUE;
1390 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1392 sizeof(disposition_info),
1393 FileDispositionInformation);
1395 if (likely(NT_SUCCESS(status)))
1398 if (status == STATUS_CANNOT_DELETE && !retried) {
1399 /* Clear file attributes and try again. This is necessary for
1400 * FILE_ATTRIBUTE_READONLY files. */
1401 status = do_create_file(&h,
1402 FILE_WRITE_ATTRIBUTES | DELETE,
1406 FILE_NON_DIRECTORY_FILE,
1408 if (!NT_SUCCESS(status)) {
1410 L"Can't open \"%ls\" to reset attributes",
1412 return WIMLIB_ERR_OPEN;
1414 memset(&basic_info, 0, sizeof(basic_info));
1415 basic_info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1416 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1419 FileBasicInformation);
1420 if (!NT_SUCCESS(status)) {
1422 L"Can't reset file attributes on \"%ls\"",
1425 return WIMLIB_ERR_SET_ATTRIBUTES;
1430 winnt_error(status, L"Can't delete \"%ls\"", current_path(ctx));
1431 return WIMLIB_ERR_OPEN;
1435 * Create a nondirectory file or named data stream at the current path,
1436 * superseding any that already exists at that path. If successful, return an
1437 * open handle to the file or named data stream.
1440 supersede_file_or_stream(struct win32_apply_ctx *ctx, HANDLE *h_ret)
1443 bool retried = false;
1445 /* FILE_ATTRIBUTE_SYSTEM is needed to ensure that
1446 * FILE_ATTRIBUTE_ENCRYPTED doesn't get set before we want it to be. */
1448 status = do_create_file(h_ret,
1449 GENERIC_READ | GENERIC_WRITE | DELETE,
1451 FILE_ATTRIBUTE_SYSTEM,
1453 FILE_NON_DIRECTORY_FILE,
1455 if (likely(NT_SUCCESS(status)))
1458 /* STATUS_OBJECT_NAME_COLLISION means that the file or stream already
1459 * exists. Delete the existing file or stream, then try again.
1461 * Note: we don't use FILE_OVERWRITE_IF or FILE_SUPERSEDE because of
1462 * problems with certain file attributes, especially
1463 * FILE_ATTRIBUTE_ENCRYPTED. FILE_SUPERSEDE is also broken in the
1464 * Windows PE ramdisk. */
1465 if (status == STATUS_OBJECT_NAME_COLLISION && !retried) {
1466 int ret = delete_file_or_stream(ctx);
1472 winnt_error(status, L"Can't create \"%ls\"", current_path(ctx));
1473 return WIMLIB_ERR_OPEN;
1477 * Create empty named data streams for the specified file, if there are any.
1479 * Since these won't have blob descriptors, they won't show up in the call to
1480 * extract_blob_list(). Hence the need for the special case.
1483 create_empty_named_data_streams(const struct wim_dentry *dentry,
1484 struct win32_apply_ctx *ctx)
1486 const struct wim_inode *inode = dentry->d_inode;
1487 bool path_modified = false;
1490 if (!ctx->common.supported_features.named_data_streams)
1493 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1494 const struct wim_inode_stream *strm = &inode->i_streams[i];
1497 if (!stream_is_named_data_stream(strm) ||
1498 stream_blob_resolved(strm) != NULL)
1501 build_extraction_path_with_ads(dentry, ctx,
1503 utf16le_len_chars(strm->stream_name));
1504 path_modified = true;
1505 ret = supersede_file_or_stream(ctx, &h);
1510 /* Restore the path to the dentry itself */
1512 build_extraction_path(dentry, ctx);
1517 * Creates the directory named by @dentry, or uses an existing directory at that
1518 * location. If necessary, sets the short name and/or fixes compression and
1519 * encryption attributes.
1521 * Returns 0, WIMLIB_ERR_MKDIR, or WIMLIB_ERR_SET_SHORT_NAME.
1524 create_directory(const struct wim_dentry *dentry, struct win32_apply_ctx *ctx)
1531 /* DELETE is needed for set_short_name(); GENERIC_READ and GENERIC_WRITE
1532 * are needed for adjust_compression_attribute(). */
1533 perms = GENERIC_READ | GENERIC_WRITE;
1534 if (!dentry_is_root(dentry))
1537 /* FILE_ATTRIBUTE_SYSTEM is needed to ensure that
1538 * FILE_ATTRIBUTE_ENCRYPTED doesn't get set before we want it to be. */
1539 status = create_file(&h, perms, NULL, FILE_ATTRIBUTE_SYSTEM,
1540 FILE_OPEN_IF, FILE_DIRECTORY_FILE, dentry, ctx);
1541 if (!NT_SUCCESS(status)) {
1542 winnt_error(status, L"Can't create directory \"%ls\"",
1544 return WIMLIB_ERR_MKDIR;
1547 if (ctx->iosb.Information == FILE_OPENED) {
1548 /* If we opened an existing directory, try to clear its file
1549 * attributes. As far as I know, this only actually makes a
1550 * difference in the case where a FILE_ATTRIBUTE_READONLY
1551 * directory has a named data stream which needs to be
1552 * extracted. You cannot create a named data stream of such a
1553 * directory, even though this contradicts Microsoft's
1554 * documentation for FILE_ATTRIBUTE_READONLY which states it is
1555 * not honored for directories! */
1556 FILE_BASIC_INFORMATION basic_info = { .FileAttributes = FILE_ATTRIBUTE_NORMAL };
1557 (*func_NtSetInformationFile)(h, &ctx->iosb, &basic_info,
1558 sizeof(basic_info), FileBasicInformation);
1561 if (!dentry_is_root(dentry)) {
1562 ret = set_short_name(h, dentry, ctx);
1567 ret = adjust_compression_attribute(h, dentry, ctx);
1574 * Create all the directories being extracted, other than the target directory
1577 * Note: we don't honor directory hard links. However, we don't allow them to
1578 * exist in WIM images anyway (see inode_fixup.c).
1581 create_directories(struct list_head *dentry_list,
1582 struct win32_apply_ctx *ctx)
1584 const struct wim_dentry *dentry;
1587 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1589 if (!(dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY))
1592 /* Note: Here we include files with
1593 * FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT, but we
1594 * wait until later to actually set the reparse data. */
1596 ret = create_directory(dentry, ctx);
1599 ret = create_empty_named_data_streams(dentry, ctx);
1601 ret = check_apply_error(dentry, ctx, ret);
1605 ret = report_file_created(&ctx->common);
1613 * Creates the nondirectory file named by @dentry.
1615 * On success, returns an open handle to the file in @h_ret, with GENERIC_READ,
1616 * GENERIC_WRITE, and DELETE access. Also, the path to the file will be saved
1617 * in ctx->pathbuf. On failure, returns an error code.
1620 create_nondirectory_inode(HANDLE *h_ret, const struct wim_dentry *dentry,
1621 struct win32_apply_ctx *ctx)
1626 build_extraction_path(dentry, ctx);
1628 ret = supersede_file_or_stream(ctx, &h);
1632 ret = adjust_compression_attribute(h, dentry, ctx);
1636 ret = create_empty_named_data_streams(dentry, ctx);
1649 /* Creates a hard link at the location named by @dentry to the file represented
1650 * by the open handle @h. Or, if the target volume does not support hard links,
1651 * create a separate file instead. */
1653 create_link(HANDLE h, const struct wim_dentry *dentry,
1654 struct win32_apply_ctx *ctx)
1656 if (ctx->common.supported_features.hard_links) {
1658 build_extraction_path(dentry, ctx);
1660 size_t bufsize = offsetof(FILE_LINK_INFORMATION, FileName) +
1661 ctx->pathbuf.Length + sizeof(wchar_t);
1662 u8 buf[bufsize] _aligned_attribute(8);
1663 FILE_LINK_INFORMATION *info = (FILE_LINK_INFORMATION *)buf;
1666 info->ReplaceIfExists = TRUE;
1667 info->RootDirectory = ctx->attr.RootDirectory;
1668 info->FileNameLength = ctx->pathbuf.Length;
1669 memcpy(info->FileName, ctx->pathbuf.Buffer, ctx->pathbuf.Length);
1670 info->FileName[info->FileNameLength / 2] = L'\0';
1672 /* Note: the null terminator isn't actually necessary,
1673 * but if you don't add the extra character, you get
1674 * STATUS_INFO_LENGTH_MISMATCH when FileNameLength
1675 * happens to be 2 */
1677 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1679 FileLinkInformation);
1680 if (NT_SUCCESS(status))
1682 winnt_error(status, L"Failed to create link \"%ls\"",
1684 return WIMLIB_ERR_LINK;
1689 ret = create_nondirectory_inode(&h2, dentry, ctx);
1693 (*func_NtClose)(h2);
1698 /* Given an inode (represented by the open handle @h) for which one link has
1699 * been created (named by @first_dentry), create the other links.
1701 * Or, if the target volume does not support hard links, create separate files.
1703 * Note: This uses ctx->pathbuf and does not reset it.
1706 create_links(HANDLE h, const struct wim_dentry *first_dentry,
1707 struct win32_apply_ctx *ctx)
1709 const struct wim_inode *inode;
1710 const struct list_head *next;
1711 const struct wim_dentry *dentry;
1714 inode = first_dentry->d_inode;
1715 next = inode->i_extraction_aliases.next;
1717 dentry = list_entry(next, struct wim_dentry,
1718 d_extraction_alias_node);
1719 if (dentry != first_dentry) {
1720 ret = create_link(h, dentry, ctx);
1725 } while (next != &inode->i_extraction_aliases);
1729 /* Create a nondirectory file, including all links. */
1731 create_nondirectory(struct wim_inode *inode, struct win32_apply_ctx *ctx)
1733 struct wim_dentry *first_dentry;
1737 first_dentry = first_extraction_alias(inode);
1739 /* Create first link. */
1740 ret = create_nondirectory_inode(&h, first_dentry, ctx);
1744 /* Set short name. */
1745 ret = set_short_name(h, first_dentry, ctx);
1747 /* Create additional links, OR if hard links are not supported just
1748 * create more files. */
1750 ret = create_links(h, first_dentry, ctx);
1752 /* "WIMBoot" extraction: set external backing by the WIM file if needed. */
1753 if (!ret && unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
1754 ret = set_external_backing(h, inode, ctx);
1760 /* Create all the nondirectory files being extracted, including all aliases
1763 create_nondirectories(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1765 struct wim_dentry *dentry;
1766 struct wim_inode *inode;
1769 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1770 inode = dentry->d_inode;
1771 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1773 /* Call create_nondirectory() only once per inode */
1774 if (dentry == inode_first_extraction_dentry(inode)) {
1775 ret = create_nondirectory(inode, ctx);
1776 ret = check_apply_error(dentry, ctx, ret);
1780 ret = report_file_created(&ctx->common);
1788 close_handles(struct win32_apply_ctx *ctx)
1790 for (unsigned i = 0; i < ctx->num_open_handles; i++)
1791 (*func_NtClose)(ctx->open_handles[i]);
1794 /* Prepare to read the next blob, which has size @blob_size, into an in-memory
1797 prepare_data_buffer(struct win32_apply_ctx *ctx, u64 blob_size)
1799 if (blob_size > ctx->data_buffer_size) {
1800 /* Larger buffer needed. */
1802 if ((size_t)blob_size != blob_size)
1804 new_buffer = REALLOC(ctx->data_buffer, blob_size);
1807 ctx->data_buffer = new_buffer;
1808 ctx->data_buffer_size = blob_size;
1810 /* On the first call this changes data_buffer_ptr from NULL, which tells
1811 * extract_chunk() that the data buffer needs to be filled while reading
1812 * the stream data. */
1813 ctx->data_buffer_ptr = ctx->data_buffer;
1818 begin_extract_blob_instance(const struct blob_descriptor *blob,
1819 struct wim_dentry *dentry,
1820 const struct wim_inode_stream *strm,
1821 struct win32_apply_ctx *ctx)
1823 FILE_ALLOCATION_INFORMATION alloc_info;
1827 if (unlikely(strm->stream_type == STREAM_TYPE_REPARSE_POINT)) {
1828 /* We can't write the reparse point stream directly; we must set
1829 * it with FSCTL_SET_REPARSE_POINT, which requires that all the
1830 * data be available. So, stage the data in a buffer. */
1831 if (!prepare_data_buffer(ctx, blob->size))
1832 return WIMLIB_ERR_NOMEM;
1833 list_add_tail(&dentry->tmp_list, &ctx->reparse_dentries);
1837 if (unlikely(strm->stream_type == STREAM_TYPE_EFSRPC_RAW_DATA)) {
1838 /* We can't write encrypted files directly; we must use
1839 * WriteEncryptedFileRaw(), which requires providing the data
1840 * through a callback function. This can't easily be combined
1841 * with our own callback-based approach.
1843 * The current workaround is to simply read the blob into memory
1844 * and write the encrypted file from that.
1846 * TODO: This isn't sufficient for extremely large encrypted
1847 * files. Perhaps we should create an extra thread to write
1849 if (!prepare_data_buffer(ctx, blob->size))
1850 return WIMLIB_ERR_NOMEM;
1851 list_add_tail(&dentry->tmp_list, &ctx->encrypted_dentries);
1855 /* It's a data stream (may be unnamed or named). */
1856 wimlib_assert(strm->stream_type == STREAM_TYPE_DATA);
1858 if (ctx->num_open_handles == MAX_OPEN_FILES) {
1859 /* XXX: Fix this. But because of the checks in
1860 * extract_blob_list(), this can now only happen on a filesystem
1861 * that does not support hard links. */
1862 ERROR("Can't extract data: too many open files!");
1863 return WIMLIB_ERR_UNSUPPORTED;
1867 if (unlikely(stream_is_named(strm))) {
1868 build_extraction_path_with_ads(dentry, ctx,
1870 utf16le_len_chars(strm->stream_name));
1872 build_extraction_path(dentry, ctx);
1876 /* Open a new handle */
1877 status = do_create_file(&h,
1878 FILE_WRITE_DATA | SYNCHRONIZE,
1879 NULL, 0, FILE_OPEN_IF,
1880 FILE_SEQUENTIAL_ONLY |
1881 FILE_SYNCHRONOUS_IO_NONALERT,
1883 if (!NT_SUCCESS(status)) {
1884 winnt_error(status, L"Can't open \"%ls\" for writing",
1886 return WIMLIB_ERR_OPEN;
1889 ctx->open_handles[ctx->num_open_handles++] = h;
1891 /* Allocate space for the data. */
1892 alloc_info.AllocationSize.QuadPart = blob->size;
1893 (*func_NtSetInformationFile)(h, &ctx->iosb,
1894 &alloc_info, sizeof(alloc_info),
1895 FileAllocationInformation);
1899 /* Set the reparse data @rpbuf of length @rpbuflen on the extracted file
1900 * corresponding to the WIM dentry @dentry. */
1902 do_set_reparse_data(const struct wim_dentry *dentry,
1903 const void *rpbuf, u16 rpbuflen,
1904 struct win32_apply_ctx *ctx)
1909 status = create_file(&h, GENERIC_WRITE, NULL,
1910 0, FILE_OPEN, 0, dentry, ctx);
1911 if (!NT_SUCCESS(status))
1914 status = (*func_NtFsControlFile)(h, NULL, NULL, NULL,
1915 &ctx->iosb, FSCTL_SET_REPARSE_POINT,
1916 (void *)rpbuf, rpbuflen,
1920 if (NT_SUCCESS(status))
1923 /* On Windows, by default only the Administrator can create symbolic
1924 * links for some reason. By default we just issue a warning if this
1925 * appears to be the problem. Use WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS
1926 * to get a hard error. */
1927 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS)
1928 && (status == STATUS_PRIVILEGE_NOT_HELD ||
1929 status == STATUS_ACCESS_DENIED)
1930 && (dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1931 dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1933 WARNING("Can't create symbolic link \"%ls\"! \n"
1934 " (Need Administrator rights, or at least "
1936 " SeCreateSymbolicLink privilege.)",
1942 winnt_error(status, L"Can't set reparse data on \"%ls\"",
1944 return WIMLIB_ERR_SET_REPARSE_DATA;
1947 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1948 * pointer to the suffix of the path that begins with the device directly, such
1949 * as e:\Windows\System32. */
1950 static const wchar_t *
1951 skip_nt_toplevel_component(const wchar_t *path, size_t path_nchars)
1953 static const wchar_t * const dirs[] = {
1958 size_t first_dir_len = 0;
1959 const wchar_t * const end = path + path_nchars;
1961 for (size_t i = 0; i < ARRAY_LEN(dirs); i++) {
1962 size_t len = wcslen(dirs[i]);
1963 if (len <= (end - path) && !wcsnicmp(path, dirs[i], len)) {
1964 first_dir_len = len;
1968 if (first_dir_len == 0)
1970 path += first_dir_len;
1971 while (path != end && *path == L'\\')
1976 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1977 * pointer to the suffix of the path that is device-relative, such as
1980 * The path has an explicit length and is not necessarily null terminated.
1982 * If the path just something like \??\e: then the returned pointer will point
1983 * just past the colon. In this case the length of the result will be 0
1985 static const wchar_t *
1986 get_device_relative_path(const wchar_t *path, size_t path_nchars)
1988 const wchar_t * const orig_path = path;
1989 const wchar_t * const end = path + path_nchars;
1991 path = skip_nt_toplevel_component(path, path_nchars);
1992 if (path == orig_path)
1995 path = wmemchr(path, L'\\', (end - path));
2000 } while (path != end && *path == L'\\');
2005 * Given a reparse point buffer for a symbolic link or junction, adjust its
2006 * contents so that the target of the link is consistent with the new location
2010 try_rpfix(u8 *rpbuf, u16 *rpbuflen_p, struct win32_apply_ctx *ctx)
2012 struct reparse_data rpdata;
2013 size_t orig_subst_name_nchars;
2014 const wchar_t *relpath;
2015 size_t relpath_nchars;
2016 size_t target_ntpath_nchars;
2017 size_t fixed_subst_name_nchars;
2018 const wchar_t *fixed_print_name;
2019 size_t fixed_print_name_nchars;
2021 if (parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata)) {
2022 /* Do nothing if the reparse data is invalid. */
2026 if (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
2027 (rpdata.rpflags & SYMBOLIC_LINK_RELATIVE))
2029 /* Do nothing if it's a relative symbolic link. */
2033 /* Build the new substitute name from the NT namespace path to the
2034 * target directory, then a path separator, then the "device relative"
2035 * part of the old substitute name. */
2037 orig_subst_name_nchars = rpdata.substitute_name_nbytes / sizeof(wchar_t);
2039 relpath = get_device_relative_path(rpdata.substitute_name,
2040 orig_subst_name_nchars);
2041 relpath_nchars = orig_subst_name_nchars -
2042 (relpath - rpdata.substitute_name);
2044 target_ntpath_nchars = ctx->target_ntpath.Length / sizeof(wchar_t);
2046 fixed_subst_name_nchars = target_ntpath_nchars;
2048 fixed_subst_name_nchars += 1 + relpath_nchars;
2049 wchar_t fixed_subst_name[fixed_subst_name_nchars];
2051 wmemcpy(fixed_subst_name, ctx->target_ntpath.Buffer,
2052 target_ntpath_nchars);
2053 if (relpath_nchars) {
2054 fixed_subst_name[target_ntpath_nchars] = L'\\';
2055 wmemcpy(&fixed_subst_name[target_ntpath_nchars + 1],
2056 relpath, relpath_nchars);
2058 /* Doesn't need to be null-terminated. */
2060 /* Print name should be Win32, but not all NT names can even be
2061 * translated to Win32 names. But we can at least delete the top-level
2062 * directory, such as \??\, and this will have the expected result in
2063 * the usual case. */
2064 fixed_print_name = skip_nt_toplevel_component(fixed_subst_name,
2065 fixed_subst_name_nchars);
2066 fixed_print_name_nchars = fixed_subst_name_nchars - (fixed_print_name -
2069 rpdata.substitute_name = fixed_subst_name;
2070 rpdata.substitute_name_nbytes = fixed_subst_name_nchars * sizeof(wchar_t);
2071 rpdata.print_name = (wchar_t *)fixed_print_name;
2072 rpdata.print_name_nbytes = fixed_print_name_nchars * sizeof(wchar_t);
2073 make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
2076 /* Sets reparse data on the specified file. This handles "fixing" the targets
2077 * of absolute symbolic links and junctions if WIMLIB_EXTRACT_FLAG_RPFIX was
2080 set_reparse_data(const struct wim_dentry *dentry,
2081 const void *_rpbuf, u16 rpbuflen, struct win32_apply_ctx *ctx)
2083 const struct wim_inode *inode = dentry->d_inode;
2084 const void *rpbuf = _rpbuf;
2086 if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
2087 && !inode->i_not_rpfixed
2088 && (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
2089 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
2091 memcpy(&ctx->rpfixbuf, _rpbuf, rpbuflen);
2092 try_rpfix((u8 *)&ctx->rpfixbuf, &rpbuflen, ctx);
2093 rpbuf = &ctx->rpfixbuf;
2095 return do_set_reparse_data(dentry, rpbuf, rpbuflen, ctx);
2099 /* Import the next block of raw encrypted data */
2101 import_encrypted_data(PBYTE pbData, PVOID pvCallbackContext, PULONG Length)
2103 struct win32_apply_ctx *ctx = pvCallbackContext;
2106 copy_len = min(ctx->encrypted_size - ctx->encrypted_offset, *Length);
2107 memcpy(pbData, &ctx->data_buffer[ctx->encrypted_offset], copy_len);
2108 ctx->encrypted_offset += copy_len;
2110 return ERROR_SUCCESS;
2114 * Write the raw encrypted data to the already-created file (or directory)
2115 * corresponding to @dentry.
2117 * The raw encrypted data is provided in ctx->data_buffer, and its size is
2118 * ctx->encrypted_size.
2120 * This function may close the target directory, in which case the caller needs
2121 * to re-open it if needed.
2124 extract_encrypted_file(const struct wim_dentry *dentry,
2125 struct win32_apply_ctx *ctx)
2132 /* Temporarily build a Win32 path for OpenEncryptedFileRaw() */
2133 build_win32_extraction_path(dentry, ctx);
2135 flags = CREATE_FOR_IMPORT | OVERWRITE_HIDDEN;
2136 if (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
2137 flags |= CREATE_FOR_DIR;
2141 err = OpenEncryptedFileRaw(ctx->pathbuf.Buffer, flags, &rawctx);
2142 if (err == ERROR_SHARING_VIOLATION && !retried) {
2143 /* This can be caused by the handle we have open to the target
2144 * directory. Try closing it temporarily. */
2145 close_target_directory(ctx);
2150 /* Restore the NT namespace path */
2151 build_extraction_path(dentry, ctx);
2153 if (err != ERROR_SUCCESS) {
2154 win32_error(err, L"Can't open \"%ls\" for encrypted import",
2156 return WIMLIB_ERR_OPEN;
2159 ctx->encrypted_offset = 0;
2161 err = WriteEncryptedFileRaw(import_encrypted_data, ctx, rawctx);
2163 CloseEncryptedFileRaw(rawctx);
2165 if (err != ERROR_SUCCESS) {
2166 win32_error(err, L"Can't import encrypted file \"%ls\"",
2168 return WIMLIB_ERR_WRITE;
2174 /* Called when starting to read a blob for extraction on Windows */
2176 begin_extract_blob(struct blob_descriptor *blob, void *_ctx)
2178 struct win32_apply_ctx *ctx = _ctx;
2179 const struct blob_extraction_target *targets = blob_extraction_targets(blob);
2182 ctx->num_open_handles = 0;
2183 ctx->data_buffer_ptr = NULL;
2184 INIT_LIST_HEAD(&ctx->reparse_dentries);
2185 INIT_LIST_HEAD(&ctx->encrypted_dentries);
2187 for (u32 i = 0; i < blob->out_refcnt; i++) {
2188 const struct wim_inode *inode = targets[i].inode;
2189 const struct wim_inode_stream *strm = targets[i].stream;
2190 struct wim_dentry *dentry;
2192 /* A copy of the blob needs to be extracted to @inode. */
2194 if (ctx->common.supported_features.hard_links) {
2195 dentry = inode_first_extraction_dentry(inode);
2196 ret = begin_extract_blob_instance(blob, dentry, strm, ctx);
2197 ret = check_apply_error(dentry, ctx, ret);
2201 /* Hard links not supported. Extract the blob
2202 * separately to each alias of the inode. */
2203 struct list_head *next;
2205 next = inode->i_extraction_aliases.next;
2207 dentry = list_entry(next, struct wim_dentry,
2208 d_extraction_alias_node);
2209 ret = begin_extract_blob_instance(blob, dentry, strm, ctx);
2210 ret = check_apply_error(dentry, ctx, ret);
2214 } while (next != &inode->i_extraction_aliases);
2225 /* Called when the next chunk of a blob has been read for extraction on Windows
2228 extract_chunk(const void *chunk, size_t size, void *_ctx)
2230 struct win32_apply_ctx *ctx = _ctx;
2232 /* Write the data chunk to each open handle */
2233 for (unsigned i = 0; i < ctx->num_open_handles; i++) {
2234 u8 *bufptr = (u8 *)chunk;
2235 size_t bytes_remaining = size;
2237 while (bytes_remaining) {
2238 ULONG count = min(0xFFFFFFFF, bytes_remaining);
2240 status = (*func_NtWriteFile)(ctx->open_handles[i],
2242 &ctx->iosb, bufptr, count,
2244 if (!NT_SUCCESS(status)) {
2245 winnt_error(status, L"Error writing data to target volume");
2246 return WIMLIB_ERR_WRITE;
2248 bufptr += ctx->iosb.Information;
2249 bytes_remaining -= ctx->iosb.Information;
2253 /* Copy the data chunk into the buffer (if needed) */
2254 if (ctx->data_buffer_ptr)
2255 ctx->data_buffer_ptr = mempcpy(ctx->data_buffer_ptr,
2260 /* Called when a blob has been fully read for extraction on Windows */
2262 end_extract_blob(struct blob_descriptor *blob, int status, void *_ctx)
2264 struct win32_apply_ctx *ctx = _ctx;
2266 const struct wim_dentry *dentry;
2273 if (likely(!ctx->data_buffer_ptr))
2276 if (!list_empty(&ctx->reparse_dentries)) {
2277 if (blob->size > REPARSE_DATA_MAX_SIZE) {
2278 dentry = list_first_entry(&ctx->reparse_dentries,
2279 struct wim_dentry, tmp_list);
2280 build_extraction_path(dentry, ctx);
2281 ERROR("Reparse data of \"%ls\" has size "
2282 "%"PRIu64" bytes (exceeds %u bytes)",
2283 current_path(ctx), blob->size,
2284 REPARSE_DATA_MAX_SIZE);
2285 ret = WIMLIB_ERR_INVALID_REPARSE_DATA;
2286 return check_apply_error(dentry, ctx, ret);
2288 /* In the WIM format, reparse point streams are just the reparse
2289 * data and omit the header. But we can reconstruct the header.
2291 memcpy(ctx->rpbuf.rpdata, ctx->data_buffer, blob->size);
2292 ctx->rpbuf.rpdatalen = blob->size;
2293 ctx->rpbuf.rpreserved = 0;
2294 list_for_each_entry(dentry, &ctx->reparse_dentries, tmp_list) {
2295 ctx->rpbuf.rptag = dentry->d_inode->i_reparse_tag;
2296 ret = set_reparse_data(dentry, &ctx->rpbuf,
2297 blob->size + REPARSE_DATA_OFFSET,
2299 ret = check_apply_error(dentry, ctx, ret);
2305 if (!list_empty(&ctx->encrypted_dentries)) {
2306 ctx->encrypted_size = blob->size;
2307 list_for_each_entry(dentry, &ctx->encrypted_dentries, tmp_list) {
2308 ret = extract_encrypted_file(dentry, ctx);
2309 ret = check_apply_error(dentry, ctx, ret);
2312 /* Re-open the target directory if needed. */
2313 ret = open_target_directory(ctx);
2322 /* Attributes that can't be set directly */
2323 #define SPECIAL_ATTRIBUTES \
2324 (FILE_ATTRIBUTE_REPARSE_POINT | \
2325 FILE_ATTRIBUTE_DIRECTORY | \
2326 FILE_ATTRIBUTE_ENCRYPTED | \
2327 FILE_ATTRIBUTE_SPARSE_FILE | \
2328 FILE_ATTRIBUTE_COMPRESSED)
2330 /* Set the security descriptor @desc, of @desc_size bytes, on the file with open
2333 set_security_descriptor(HANDLE h, const void *_desc,
2334 size_t desc_size, struct win32_apply_ctx *ctx)
2336 SECURITY_INFORMATION info;
2338 SECURITY_DESCRIPTOR_RELATIVE *desc;
2341 * Ideally, we would just pass in the security descriptor buffer as-is.
2342 * But it turns out that Windows can mess up the security descriptor
2343 * even when using the low-level NtSetSecurityObject() function:
2345 * - Windows will clear SE_DACL_AUTO_INHERITED if it is set in the
2346 * passed buffer. To actually get Windows to set
2347 * SE_DACL_AUTO_INHERITED, the application must set the non-persistent
2348 * flag SE_DACL_AUTO_INHERIT_REQ. As usual, Microsoft didn't bother
2349 * to properly document either of these flags. It's unclear how
2350 * important SE_DACL_AUTO_INHERITED actually is, but to be safe we use
2351 * the SE_DACL_AUTO_INHERIT_REQ workaround to set it if needed.
2353 * - The above also applies to the equivalent SACL flags,
2354 * SE_SACL_AUTO_INHERITED and SE_SACL_AUTO_INHERIT_REQ.
2356 * - If the application says that it's setting
2357 * DACL_SECURITY_INFORMATION, then Windows sets SE_DACL_PRESENT in the
2358 * resulting security descriptor, even if the security descriptor the
2359 * application provided did not have a DACL. This seems to be
2360 * unavoidable, since omitting DACL_SECURITY_INFORMATION would cause a
2361 * default DACL to remain. Fortunately, this behavior seems harmless,
2362 * since the resulting DACL will still be "null" --- but it will be
2363 * "the other representation of null".
2365 * - The above also applies to SACL_SECURITY_INFORMATION and
2366 * SE_SACL_PRESENT. Again, it's seemingly unavoidable but "harmless"
2367 * that Windows changes the representation of a "null SACL".
2369 if (likely(desc_size <= STACK_MAX)) {
2370 desc = alloca(desc_size);
2372 desc = MALLOC(desc_size);
2374 return STATUS_NO_MEMORY;
2377 memcpy(desc, _desc, desc_size);
2379 if (likely(desc_size >= 4)) {
2381 if (desc->Control & SE_DACL_AUTO_INHERITED)
2382 desc->Control |= SE_DACL_AUTO_INHERIT_REQ;
2384 if (desc->Control & SE_SACL_AUTO_INHERITED)
2385 desc->Control |= SE_SACL_AUTO_INHERIT_REQ;
2389 * More API insanity. We want to set the entire security descriptor
2390 * as-is. But all available APIs require specifying the specific parts
2391 * of the security descriptor being set. Especially annoying is that
2392 * mandatory integrity labels are part of the SACL, but they aren't set
2393 * with SACL_SECURITY_INFORMATION. Instead, applications must also
2394 * specify LABEL_SECURITY_INFORMATION (Windows Vista, Windows 7) or
2395 * BACKUP_SECURITY_INFORMATION (Windows 8). But at least older versions
2396 * of Windows don't error out if you provide these newer flags...
2398 * Also, if the process isn't running as Administrator, then it probably
2399 * doesn't have SE_RESTORE_PRIVILEGE. In this case, it will always get
2400 * the STATUS_PRIVILEGE_NOT_HELD error by trying to set the SACL, even
2401 * if the security descriptor it provided did not have a SACL. By
2402 * default, in this case we try to recover and set as much of the
2403 * security descriptor as possible --- potentially excluding the DACL, and
2404 * even the owner, as well as the SACL.
2407 info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
2408 DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION |
2409 LABEL_SECURITY_INFORMATION | BACKUP_SECURITY_INFORMATION;
2413 * It's also worth noting that SetFileSecurity() is unusable because it
2414 * doesn't request "backup semantics" when it opens the file internally.
2415 * NtSetSecurityObject() seems to be the best function to use in backup
2416 * applications. (SetSecurityInfo() should also work, but it's harder
2417 * to use and must call NtSetSecurityObject() internally anyway.
2418 * BackupWrite() is theoretically usable as well, but it's inflexible
2419 * and poorly documented.)
2423 status = (*func_NtSetSecurityObject)(h, info, desc);
2424 if (NT_SUCCESS(status))
2425 goto out_maybe_free_desc;
2427 /* Failed to set the requested parts of the security descriptor. If the
2428 * error was permissions-related, try to set fewer parts of the security
2429 * descriptor, unless WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled. */
2430 if ((status == STATUS_PRIVILEGE_NOT_HELD ||
2431 status == STATUS_ACCESS_DENIED) &&
2432 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2434 if (info & SACL_SECURITY_INFORMATION) {
2435 info &= ~(SACL_SECURITY_INFORMATION |
2436 LABEL_SECURITY_INFORMATION |
2437 BACKUP_SECURITY_INFORMATION);
2438 ctx->partial_security_descriptors++;
2441 if (info & DACL_SECURITY_INFORMATION) {
2442 info &= ~DACL_SECURITY_INFORMATION;
2445 if (info & OWNER_SECURITY_INFORMATION) {
2446 info &= ~OWNER_SECURITY_INFORMATION;
2449 /* Nothing left except GROUP, and if we removed it we
2450 * wouldn't have anything at all. */
2453 /* No part of the security descriptor could be set, or
2454 * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled and the full security
2455 * descriptor could not be set. */
2456 if (!(info & SACL_SECURITY_INFORMATION))
2457 ctx->partial_security_descriptors--;
2458 ctx->no_security_descriptors++;
2460 out_maybe_free_desc:
2461 if (unlikely(desc_size > STACK_MAX))
2466 /* Set metadata on the open file @h from the WIM inode @inode. */
2468 do_apply_metadata_to_file(HANDLE h, const struct wim_inode *inode,
2469 struct win32_apply_ctx *ctx)
2471 FILE_BASIC_INFORMATION info;
2474 /* Set security descriptor if present and not in NO_ACLS mode */
2475 if (inode->i_security_id >= 0 &&
2476 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
2478 const struct wim_security_data *sd;
2482 sd = wim_get_current_security_data(ctx->common.wim);
2483 desc = sd->descriptors[inode->i_security_id];
2484 desc_size = sd->sizes[inode->i_security_id];
2486 status = set_security_descriptor(h, desc, desc_size, ctx);
2487 if (!NT_SUCCESS(status) &&
2488 (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2491 L"Can't set security descriptor on \"%ls\"",
2493 return WIMLIB_ERR_SET_SECURITY;
2497 /* Set attributes and timestamps */
2498 info.CreationTime.QuadPart = inode->i_creation_time;
2499 info.LastAccessTime.QuadPart = inode->i_last_access_time;
2500 info.LastWriteTime.QuadPart = inode->i_last_write_time;
2501 info.ChangeTime.QuadPart = 0;
2502 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES) {
2503 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
2505 info.FileAttributes = inode->i_attributes & ~SPECIAL_ATTRIBUTES;
2506 if (info.FileAttributes == 0)
2507 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
2510 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
2511 &info, sizeof(info),
2512 FileBasicInformation);
2513 /* On FAT volumes we get STATUS_INVALID_PARAMETER if we try to set
2514 * attributes on the root directory. (Apparently because FAT doesn't
2515 * actually have a place to store those attributes!) */
2516 if (!NT_SUCCESS(status)
2517 && !(status == STATUS_INVALID_PARAMETER &&
2518 dentry_is_root(inode_first_extraction_dentry(inode))))
2520 winnt_error(status, L"Can't set basic metadata on \"%ls\"",
2522 return WIMLIB_ERR_SET_ATTRIBUTES;
2529 apply_metadata_to_file(const struct wim_dentry *dentry,
2530 struct win32_apply_ctx *ctx)
2532 const struct wim_inode *inode = dentry->d_inode;
2538 perms = FILE_WRITE_ATTRIBUTES | WRITE_DAC |
2539 WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
2541 build_extraction_path(dentry, ctx);
2543 /* Open a handle with as many relevant permissions as possible. */
2544 while (!NT_SUCCESS(status = do_create_file(&h, perms, NULL,
2545 0, FILE_OPEN, 0, ctx)))
2547 if (status == STATUS_PRIVILEGE_NOT_HELD ||
2548 status == STATUS_ACCESS_DENIED)
2550 if (perms & ACCESS_SYSTEM_SECURITY) {
2551 perms &= ~ACCESS_SYSTEM_SECURITY;
2554 if (perms & WRITE_DAC) {
2555 perms &= ~WRITE_DAC;
2558 if (perms & WRITE_OWNER) {
2559 perms &= ~WRITE_OWNER;
2563 winnt_error(status, L"Can't open \"%ls\" to set metadata",
2565 return WIMLIB_ERR_OPEN;
2568 ret = do_apply_metadata_to_file(h, inode, ctx);
2576 apply_metadata(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
2578 const struct wim_dentry *dentry;
2581 /* We go in reverse so that metadata is set on all a directory's
2582 * children before the directory itself. This avoids any potential
2583 * problems with attributes, timestamps, or security descriptors. */
2584 list_for_each_entry_reverse(dentry, dentry_list, d_extraction_list_node)
2586 ret = apply_metadata_to_file(dentry, ctx);
2587 ret = check_apply_error(dentry, ctx, ret);
2590 ret = report_file_metadata_applied(&ctx->common);
2597 /* Issue warnings about problems during the extraction for which warnings were
2598 * not already issued (due to the high number of potential warnings if we issued
2599 * them per-file). */
2601 do_warnings(const struct win32_apply_ctx *ctx)
2603 if (ctx->partial_security_descriptors == 0
2604 && ctx->no_security_descriptors == 0
2605 && ctx->num_set_short_name_failures == 0
2607 && ctx->num_remove_short_name_failures == 0
2612 WARNING("Extraction to \"%ls\" complete, but with one or more warnings:",
2613 ctx->common.target);
2614 if (ctx->num_set_short_name_failures) {
2615 WARNING("- Could not set short names on %lu files or directories",
2616 ctx->num_set_short_name_failures);
2619 if (ctx->num_remove_short_name_failures) {
2620 WARNING("- Could not remove short names on %lu files or directories"
2621 " (This is expected on Vista and earlier)",
2622 ctx->num_remove_short_name_failures);
2625 if (ctx->partial_security_descriptors) {
2626 WARNING("- Could only partially set the security descriptor\n"
2627 " on %lu files or directories.",
2628 ctx->partial_security_descriptors);
2630 if (ctx->no_security_descriptors) {
2631 WARNING("- Could not set security descriptor at all\n"
2632 " on %lu files or directories.",
2633 ctx->no_security_descriptors);
2635 if (ctx->partial_security_descriptors || ctx->no_security_descriptors) {
2636 WARNING("To fully restore all security descriptors, run the program\n"
2637 " with Administrator rights.");
2642 count_dentries(const struct list_head *dentry_list)
2644 const struct list_head *cur;
2647 list_for_each(cur, dentry_list)
2653 /* Extract files from a WIM image to a directory on Windows */
2655 win32_extract(struct list_head *dentry_list, struct apply_ctx *_ctx)
2658 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
2661 ret = prepare_target(dentry_list, ctx);
2665 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
2666 ret = start_wimboot_extraction(dentry_list, ctx);
2671 dentry_count = count_dentries(dentry_list);
2673 ret = start_file_structure_phase(&ctx->common, dentry_count);
2677 ret = create_directories(dentry_list, ctx);
2681 ret = create_nondirectories(dentry_list, ctx);
2685 ret = end_file_structure_phase(&ctx->common);
2689 struct read_blob_list_callbacks cbs = {
2690 .begin_blob = begin_extract_blob,
2691 .begin_blob_ctx = ctx,
2692 .consume_chunk = extract_chunk,
2693 .consume_chunk_ctx = ctx,
2694 .end_blob = end_extract_blob,
2695 .end_blob_ctx = ctx,
2697 ret = extract_blob_list(&ctx->common, &cbs);
2701 ret = start_file_metadata_phase(&ctx->common, dentry_count);
2705 ret = apply_metadata(dentry_list, ctx);
2709 ret = end_file_metadata_phase(&ctx->common);
2713 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
2714 ret = end_wimboot_extraction(ctx);
2721 close_target_directory(ctx);
2722 if (ctx->target_ntpath.Buffer)
2723 HeapFree(GetProcessHeap(), 0, ctx->target_ntpath.Buffer);
2724 FREE(ctx->pathbuf.Buffer);
2725 FREE(ctx->print_buffer);
2726 FREE(ctx->wimboot.wims);
2727 if (ctx->wimboot.prepopulate_pats) {
2728 FREE(ctx->wimboot.prepopulate_pats->strings);
2729 FREE(ctx->wimboot.prepopulate_pats);
2731 FREE(ctx->wimboot.mem_prepopulate_pats);
2732 FREE(ctx->data_buffer);
2736 const struct apply_operations win32_apply_ops = {
2738 .get_supported_features = win32_get_supported_features,
2739 .extract = win32_extract,
2740 .will_externally_back = win32_will_externally_back,
2741 .context_size = sizeof(struct win32_apply_ctx),
2744 #endif /* __WIN32__ */