2 * win32_apply.c - Windows-specific code for applying files from a WIM image.
6 * Copyright (C) 2013, 2014 Eric Biggers
8 * This file is 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/capture.h" /* for mangle_pat() and match_pattern_list() */
32 #include "wimlib/dentry.h"
33 #include "wimlib/error.h"
34 #include "wimlib/lookup_table.h"
35 #include "wimlib/metadata.h"
36 #include "wimlib/paths.h"
37 #include "wimlib/reparse.h"
38 #include "wimlib/textfile.h"
39 #include "wimlib/xml.h"
40 #include "wimlib/wildcard.h"
41 #include "wimlib/wimboot.h"
43 struct win32_apply_ctx {
45 /* Extract flags, the pointer to the WIMStruct, etc. */
46 struct apply_ctx common;
48 /* WIMBoot information, only filled in if WIMLIB_EXTRACT_FLAG_WIMBOOT
52 struct string_set *prepopulate_pats;
53 void *mem_prepopulate_pats;
54 u8 wim_lookup_table_hash[SHA1_HASH_SIZE];
56 bool tried_to_load_prepopulate_list;
59 /* Open handle to the target directory */
62 /* NT namespace path to the target directory (buffer allocated) */
63 UNICODE_STRING target_ntpath;
65 /* Temporary buffer for building paths (buffer allocated) */
66 UNICODE_STRING pathbuf;
68 /* Object attributes to reuse for opening files in the target directory.
69 * (attr.ObjectName == &pathbuf) and (attr.RootDirectory == h_target).
71 OBJECT_ATTRIBUTES attr;
73 /* Temporary I/O status block for system calls */
76 /* Allocated buffer for creating "printable" paths from our
77 * target-relative NT paths */
78 wchar_t *print_buffer;
80 /* Allocated buffer for reading stream data when it cannot be extracted
84 /* Pointer to the next byte in @data_buffer to fill */
87 /* Size allocated in @data_buffer */
88 size_t data_buffer_size;
90 /* Current offset in the raw encrypted file being written */
91 size_t encrypted_offset;
93 /* Current size of the raw encrypted file being written */
94 size_t encrypted_size;
96 /* Temporary buffer for reparse data */
97 struct reparse_buffer_disk rpbuf;
99 /* Temporary buffer for reparse data of "fixed" absolute symbolic links
101 struct reparse_buffer_disk rpfixbuf;
103 /* Array of open handles to filesystem streams currently being written
105 HANDLE open_handles[MAX_OPEN_STREAMS];
107 /* Number of handles in @open_handles currently open (filled in from the
108 * beginning of the array) */
109 unsigned num_open_handles;
111 /* List of dentries, joined by @tmp_list, that need to have reparse data
112 * extracted as soon as the whole stream has been read into
114 struct list_head reparse_dentries;
116 /* List of dentries, joined by @tmp_list, that need to have raw
117 * encrypted data extracted as soon as the whole stream has been read
118 * into @data_buffer. */
119 struct list_head encrypted_dentries;
121 /* Number of files for which we didn't have permission to set the full
122 * security descriptor. */
123 unsigned long partial_security_descriptors;
125 /* Number of files for which we didn't have permission to set any part
126 * of the security descriptor. */
127 unsigned long no_security_descriptors;
129 /* Number of files for which we couldn't set the short name. */
130 unsigned long num_set_short_name_failures;
132 /* Number of files for which we couldn't remove the short name. */
133 unsigned long num_remove_short_name_failures;
135 /* Have we tried to enable short name support on the target volume yet?
137 bool tried_to_enable_short_names;
140 /* Get the drive letter from a Windows path, or return the null character if the
141 * path is relative. */
143 get_drive_letter(const wchar_t *path)
145 /* Skip \\?\ prefix */
146 if (!wcsncmp(path, L"\\\\?\\", 4))
149 /* Return drive letter if valid */
150 if (((path[0] >= L'a' && path[0] <= L'z') ||
151 (path[0] >= L'A' && path[0] <= L'Z')) && path[1] == L':')
158 get_vol_flags(const wchar_t *target, DWORD *vol_flags_ret,
159 bool *short_names_supported_ret)
161 wchar_t filesystem_name[MAX_PATH + 1];
163 wchar_t *volume = NULL;
166 *short_names_supported_ret = false;
168 drive[0] = get_drive_letter(target);
176 if (!GetVolumeInformation(volume, NULL, 0, NULL, NULL,
177 vol_flags_ret, filesystem_name,
178 ARRAY_LEN(filesystem_name)))
180 DWORD err = GetLastError();
181 set_errno_from_win32_error(err);
182 WARNING_WITH_ERRNO("Failed to get volume information for "
183 "\"%ls\" (err=%"PRIu32")",
188 if (wcsstr(filesystem_name, L"NTFS")) {
189 /* FILE_SUPPORTS_HARD_LINKS is only supported on Windows 7 and
190 * later. Force it on anyway if filesystem is NTFS. */
191 *vol_flags_ret |= FILE_SUPPORTS_HARD_LINKS;
193 /* There's no volume flag for short names, but according to the
194 * MS documentation they are only user-settable on NTFS. */
195 *short_names_supported_ret = true;
199 static const wchar_t *
200 current_path(struct win32_apply_ctx *ctx);
203 build_extraction_path(const struct wim_dentry *dentry,
204 struct win32_apply_ctx *ctx);
207 report_dentry_apply_error(const struct wim_dentry *dentry,
208 struct win32_apply_ctx *ctx, int ret)
210 build_extraction_path(dentry, ctx);
211 return report_apply_error(&ctx->common, ret, current_path(ctx));
215 check_apply_error(const struct wim_dentry *dentry,
216 struct win32_apply_ctx *ctx, int ret)
219 ret = report_dentry_apply_error(dentry, ctx, ret);
224 win32_get_supported_features(const wchar_t *target,
225 struct wim_features *supported_features)
228 bool short_names_supported;
230 /* Query the features of the target volume. */
232 get_vol_flags(target, &vol_flags, &short_names_supported);
234 supported_features->archive_files = 1;
235 supported_features->hidden_files = 1;
236 supported_features->system_files = 1;
238 if (vol_flags & FILE_FILE_COMPRESSION)
239 supported_features->compressed_files = 1;
241 if (vol_flags & FILE_SUPPORTS_ENCRYPTION) {
242 supported_features->encrypted_files = 1;
243 supported_features->encrypted_directories = 1;
246 supported_features->not_context_indexed_files = 1;
248 /* Don't do anything with FILE_SUPPORTS_SPARSE_FILES. */
250 if (vol_flags & FILE_NAMED_STREAMS)
251 supported_features->named_data_streams = 1;
253 if (vol_flags & FILE_SUPPORTS_HARD_LINKS)
254 supported_features->hard_links = 1;
256 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS)
257 supported_features->reparse_points = 1;
259 if (vol_flags & FILE_PERSISTENT_ACLS)
260 supported_features->security_descriptors = 1;
262 if (short_names_supported)
263 supported_features->short_names = 1;
265 supported_features->timestamps = 1;
267 /* Note: Windows does not support case sensitive filenames! At least
268 * not without changing the registry and rebooting... */
273 /* Load the patterns from [PrepopulateList] of WimBootCompress.ini in the WIM
274 * image being extracted. */
276 load_prepopulate_pats(struct win32_apply_ctx *ctx)
278 const wchar_t *path = L"\\Windows\\System32\\WimBootCompress.ini";
279 struct wim_dentry *dentry;
280 struct wim_lookup_table_entry *lte;
283 struct string_set *s;
285 struct text_file_section sec;
287 ctx->wimboot.tried_to_load_prepopulate_list = true;
289 dentry = get_dentry(ctx->common.wim, path, WIMLIB_CASE_INSENSITIVE);
291 (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
292 FILE_ATTRIBUTE_REPARSE_POINT |
293 FILE_ATTRIBUTE_ENCRYPTED)) ||
294 !(lte = inode_unnamed_lte(dentry->d_inode, ctx->common.wim->lookup_table)))
296 WARNING("%ls does not exist in WIM image!", path);
297 return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
300 ret = read_full_stream_into_alloc_buf(lte, &buf);
304 s = CALLOC(1, sizeof(struct string_set));
307 return WIMLIB_ERR_NOMEM;
310 sec.name = T("PrepopulateList");
313 ret = do_load_text_file(path, buf, lte->size, &mem, &sec, 1,
314 LOAD_TEXT_FILE_REMOVE_QUOTES |
315 LOAD_TEXT_FILE_NO_WARNINGS,
317 BUILD_BUG_ON(OS_PREFERRED_PATH_SEPARATOR != WIM_PATH_SEPARATOR);
323 ctx->wimboot.prepopulate_pats = s;
324 ctx->wimboot.mem_prepopulate_pats = mem;
328 /* Returns %true if the specified absolute path to a file in the WIM image
329 * matches a pattern in [PrepopulateList] of WimBootCompress.ini. Otherwise
332 in_prepopulate_list(const wchar_t *path, size_t path_nchars,
333 const struct win32_apply_ctx *ctx)
335 const struct string_set *pats = ctx->wimboot.prepopulate_pats;
337 if (!pats || !pats->num_strings)
340 return match_pattern_list(path, path_nchars, pats);
343 /* Returns %true if the specified absolute path to a file in the WIM image can
344 * be subject to external backing when extracted. Otherwise returns %false. */
346 can_externally_back_path(const wchar_t *path, size_t path_nchars,
347 const struct win32_apply_ctx *ctx)
349 if (in_prepopulate_list(path, path_nchars, ctx))
352 /* Since we attempt to modify the SYSTEM registry after it's extracted
353 * (see end_wimboot_extraction()), it can't be extracted as externally
354 * backed. This extends to associated files such as SYSTEM.LOG that
355 * also must be writable in order to write to the registry. Normally,
356 * SYSTEM is in [PrepopulateList], and the SYSTEM.* files match patterns
357 * in [ExclusionList] and therefore are not captured in the WIM at all.
358 * However, a WIM that wasn't specifically captured in "WIMBoot mode"
359 * may contain SYSTEM.* files. So to make things "just work", hard-code
361 if (match_path(path, path_nchars, L"\\Windows\\System32\\config\\SYSTEM*",
362 OS_PREFERRED_PATH_SEPARATOR, false))
368 #define WIM_BACKING_NOT_ENABLED -1
369 #define WIM_BACKING_NOT_POSSIBLE -2
370 #define WIM_BACKING_EXCLUDED -3
373 will_externally_back_inode(struct wim_inode *inode, struct win32_apply_ctx *ctx,
374 const struct wim_dentry **excluded_dentry_ret)
376 struct list_head *next;
377 struct wim_dentry *dentry;
378 struct wim_lookup_table_entry *stream;
381 if (inode->i_can_externally_back)
384 /* This may do redundant checks because the cached value
385 * i_can_externally_back is 2-state (as opposed to 3-state:
386 * unknown/no/yes). But most files can be externally backed, so this
389 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
390 FILE_ATTRIBUTE_REPARSE_POINT |
391 FILE_ATTRIBUTE_ENCRYPTED))
392 return WIM_BACKING_NOT_POSSIBLE;
394 stream = inode_unnamed_lte_resolved(inode);
397 stream->resource_location != RESOURCE_IN_WIM ||
398 stream->rspec->wim != ctx->common.wim ||
399 stream->size != stream->rspec->uncompressed_size)
400 return WIM_BACKING_NOT_POSSIBLE;
403 * We need to check the patterns in [PrepopulateList] against every name
404 * of the inode, in case any of them match.
406 next = inode->i_extraction_aliases.next;
408 dentry = list_entry(next, struct wim_dentry,
409 d_extraction_alias_node);
411 ret = calculate_dentry_full_path(dentry);
415 if (!can_externally_back_path(dentry->_full_path,
416 wcslen(dentry->_full_path), ctx))
418 if (excluded_dentry_ret)
419 *excluded_dentry_ret = dentry;
420 return WIM_BACKING_EXCLUDED;
423 } while (next != &inode->i_extraction_aliases);
425 inode->i_can_externally_back = 1;
430 * Determines if the unnamed data stream of a file will be created as an
431 * external backing, as opposed to a standard extraction.
434 win32_will_externally_back(struct wim_dentry *dentry, struct apply_ctx *_ctx)
436 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
438 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
439 return WIM_BACKING_NOT_ENABLED;
441 if (!ctx->wimboot.tried_to_load_prepopulate_list)
442 if (load_prepopulate_pats(ctx) == WIMLIB_ERR_NOMEM)
443 return WIMLIB_ERR_NOMEM;
445 return will_externally_back_inode(dentry->d_inode, ctx, NULL);
449 set_external_backing(HANDLE h, struct wim_inode *inode, struct win32_apply_ctx *ctx)
452 const struct wim_dentry *excluded_dentry;
454 ret = will_externally_back_inode(inode, ctx, &excluded_dentry);
455 if (ret > 0) /* Error. */
458 if (ret < 0 && ret != WIM_BACKING_EXCLUDED)
459 return 0; /* Not externally backing, other than due to exclusion. */
461 if (unlikely(ret == WIM_BACKING_EXCLUDED)) {
462 /* Not externally backing due to exclusion. */
463 union wimlib_progress_info info;
465 build_extraction_path(excluded_dentry, ctx);
467 info.wimboot_exclude.path_in_wim = excluded_dentry->_full_path;
468 info.wimboot_exclude.extraction_path = current_path(ctx);
470 return call_progress(ctx->common.progfunc,
471 WIMLIB_PROGRESS_MSG_WIMBOOT_EXCLUDE,
472 &info, ctx->common.progctx);
474 /* Externally backing. */
475 if (unlikely(!wimboot_set_pointer(h,
476 inode_unnamed_lte_resolved(inode),
477 ctx->wimboot.data_source_id,
478 ctx->wimboot.wim_lookup_table_hash,
479 ctx->wimboot.wof_running)))
481 const DWORD err = GetLastError();
483 build_extraction_path(inode_first_extraction_dentry(inode), ctx);
484 set_errno_from_win32_error(err);
485 ERROR_WITH_ERRNO("\"%ls\": Couldn't set WIMBoot "
486 "pointer data (err=%"PRIu32")",
487 current_path(ctx), (u32)err);
488 return WIMLIB_ERR_WIMBOOT;
494 /* Calculates the SHA-1 message digest of the WIM's lookup table. */
496 hash_lookup_table(WIMStruct *wim, u8 hash[SHA1_HASH_SIZE])
498 return wim_reshdr_to_hash(&wim->hdr.lookup_table_reshdr, wim, hash);
501 /* Prepare for doing a "WIMBoot" extraction by loading patterns from
502 * [PrepopulateList] of WimBootCompress.ini and allocating a WOF data source ID
503 * on the target volume. */
505 start_wimboot_extraction(struct win32_apply_ctx *ctx)
508 WIMStruct *wim = ctx->common.wim;
510 if (!ctx->wimboot.tried_to_load_prepopulate_list)
511 if (load_prepopulate_pats(ctx) == WIMLIB_ERR_NOMEM)
512 return WIMLIB_ERR_NOMEM;
514 if (!wim_info_get_wimboot(wim->wim_info, wim->current_image))
515 WARNING("Image is not marked as WIMBoot compatible!");
517 ret = hash_lookup_table(ctx->common.wim,
518 ctx->wimboot.wim_lookup_table_hash);
522 return wimboot_alloc_data_source_id(wim->filename,
526 &ctx->wimboot.data_source_id,
527 &ctx->wimboot.wof_running);
531 build_win32_extraction_path(const struct wim_dentry *dentry,
532 struct win32_apply_ctx *ctx);
534 /* Sets WimBoot=1 in the extracted SYSTEM registry hive.
536 * WIMGAPI does this, and it's possible that it's important.
537 * But I don't know exactly what this value means to Windows. */
539 end_wimboot_extraction(struct win32_apply_ctx *ctx)
541 struct wim_dentry *dentry;
542 wchar_t subkeyname[32];
548 dentry = get_dentry(ctx->common.wim, L"\\Windows\\System32\\config\\SYSTEM",
549 WIMLIB_CASE_INSENSITIVE);
551 if (!dentry || !will_extract_dentry(dentry))
554 if (!will_extract_dentry(wim_get_current_root_dentry(ctx->common.wim)))
557 /* Not bothering to use the native routines (e.g. NtLoadKey()) for this.
558 * If this doesn't work, you probably also have many other problems. */
560 build_win32_extraction_path(dentry, ctx);
562 randomize_char_array_with_alnum(subkeyname, 20);
563 subkeyname[20] = L'\0';
565 res = RegLoadKey(HKEY_LOCAL_MACHINE, subkeyname, ctx->pathbuf.Buffer);
569 wcscpy(&subkeyname[20], L"\\Setup");
571 res = RegCreateKeyEx(HKEY_LOCAL_MACHINE, subkeyname, 0, NULL,
572 REG_OPTION_BACKUP_RESTORE, 0, NULL, &key, NULL);
578 res = RegSetValueEx(key, L"WimBoot", 0, REG_DWORD,
579 (const BYTE *)&value, sizeof(DWORD));
583 res = RegFlushKey(key);
586 res2 = RegCloseKey(key);
590 subkeyname[20] = L'\0';
591 RegUnLoadKey(HKEY_LOCAL_MACHINE, subkeyname);
595 set_errno_from_win32_error(res);
596 WARNING_WITH_ERRNO("Failed to set \\Setup: dword \"WimBoot\"=1 value "
597 "in registry hive \"%ls\" (err=%"PRIu32")",
598 ctx->pathbuf.Buffer, (u32)res);
604 /* Returns the number of wide characters needed to represent the path to the
605 * specified @dentry, relative to the target directory, when extracted.
607 * Does not include null terminator (not needed for NtCreateFile). */
609 dentry_extraction_path_length(const struct wim_dentry *dentry)
612 const struct wim_dentry *d;
616 len += d->d_extraction_name_nchars + 1;
618 } while (!dentry_is_root(d) && will_extract_dentry(d));
620 return --len; /* No leading slash */
623 /* Returns the length of the longest string that might need to be appended to
624 * the path to an alias of an inode to open or create a named data stream.
626 * If the inode has no named data streams, this will be 0. Otherwise, this will
627 * be 1 plus the length of the longest-named data stream, since the data stream
628 * name must be separated from the path by the ':' character. */
630 inode_longest_named_data_stream_spec(const struct wim_inode *inode)
633 for (u16 i = 0; i < inode->i_num_ads; i++) {
634 size_t len = inode->i_ads_entries[i].stream_name_nbytes;
639 max = 1 + (max / sizeof(wchar_t));
643 /* Find the length, in wide characters, of the longest path needed for
644 * extraction of any file in @dentry_list relative to the target directory.
646 * Accounts for named data streams, but does not include null terminator (not
647 * needed for NtCreateFile). */
649 compute_path_max(struct list_head *dentry_list)
652 const struct wim_dentry *dentry;
654 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
657 len = dentry_extraction_path_length(dentry);
659 /* Account for named data streams */
660 len += inode_longest_named_data_stream_spec(dentry->d_inode);
669 /* Build the path at which to extract the @dentry, relative to the target
672 * The path is saved in ctx->pathbuf. */
674 build_extraction_path(const struct wim_dentry *dentry,
675 struct win32_apply_ctx *ctx)
679 const struct wim_dentry *d;
681 len = dentry_extraction_path_length(dentry);
683 ctx->pathbuf.Length = len * sizeof(wchar_t);
684 p = ctx->pathbuf.Buffer + len;
686 !dentry_is_root(d->d_parent) && will_extract_dentry(d->d_parent);
689 p -= d->d_extraction_name_nchars;
690 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
693 /* No leading slash */
694 p -= d->d_extraction_name_nchars;
695 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
698 /* Build the path at which to extract the @dentry, relative to the target
699 * directory, adding the suffix for a named data stream.
701 * The path is saved in ctx->pathbuf. */
703 build_extraction_path_with_ads(const struct wim_dentry *dentry,
704 struct win32_apply_ctx *ctx,
705 const wchar_t *stream_name,
706 size_t stream_name_nchars)
710 build_extraction_path(dentry, ctx);
712 /* Add :NAME for named data stream */
713 p = ctx->pathbuf.Buffer + (ctx->pathbuf.Length / sizeof(wchar_t));
715 wmemcpy(p, stream_name, stream_name_nchars);
716 ctx->pathbuf.Length += (1 + stream_name_nchars) * sizeof(wchar_t);
719 /* Build the Win32 namespace path to the specified @dentry when extracted.
721 * The path is saved in ctx->pathbuf and will be null terminated.
723 * XXX: We could get rid of this if it wasn't needed for the file encryption
724 * APIs, and the registry manipulation in WIMBoot mode. */
726 build_win32_extraction_path(const struct wim_dentry *dentry,
727 struct win32_apply_ctx *ctx)
729 build_extraction_path(dentry, ctx);
731 /* Prepend target_ntpath to our relative path, then change \??\ into \\?\ */
733 memmove(ctx->pathbuf.Buffer +
734 (ctx->target_ntpath.Length / sizeof(wchar_t)) + 1,
735 ctx->pathbuf.Buffer, ctx->pathbuf.Length);
736 memcpy(ctx->pathbuf.Buffer, ctx->target_ntpath.Buffer,
737 ctx->target_ntpath.Length);
738 ctx->pathbuf.Buffer[ctx->target_ntpath.Length / sizeof(wchar_t)] = L'\\';
739 ctx->pathbuf.Length += ctx->target_ntpath.Length + sizeof(wchar_t);
740 ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)] = L'\0';
742 wimlib_assert(ctx->pathbuf.Length >= 4 * sizeof(wchar_t) &&
743 !wmemcmp(ctx->pathbuf.Buffer, L"\\??\\", 4));
745 ctx->pathbuf.Buffer[1] = L'\\';
749 /* Returns a "printable" representation of the last relative NT path that was
750 * constructed with build_extraction_path() or build_extraction_path_with_ads().
752 * This will be overwritten by the next call to this function. */
753 static const wchar_t *
754 current_path(struct win32_apply_ctx *ctx)
756 wchar_t *p = ctx->print_buffer;
758 p = wmempcpy(p, ctx->common.target, ctx->common.target_nchars);
760 p = wmempcpy(p, ctx->pathbuf.Buffer, ctx->pathbuf.Length / sizeof(wchar_t));
762 return ctx->print_buffer;
766 * Ensures the target directory exists and opens a handle to it, in preparation
767 * of using paths relative to it.
770 prepare_target(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
776 /* Open handle to the target directory (possibly creating it). */
778 ret = win32_path_to_nt_path(ctx->common.target, &ctx->target_ntpath);
782 ctx->attr.Length = sizeof(ctx->attr);
783 ctx->attr.ObjectName = &ctx->target_ntpath;
785 status = (*func_NtCreateFile)(&ctx->h_target,
791 FILE_SHARE_VALID_FLAGS,
793 FILE_DIRECTORY_FILE |
794 FILE_OPEN_REPARSE_POINT |
795 FILE_OPEN_FOR_BACKUP_INTENT,
799 if (!NT_SUCCESS(status)) {
800 set_errno_from_nt_status(status);
801 ERROR_WITH_ERRNO("Can't open or create directory \"%ls\" "
802 "(status=0x%08"PRIx32")",
803 ctx->common.target, (u32)status);
804 return WIMLIB_ERR_OPENDIR;
807 path_max = compute_path_max(dentry_list);
809 /* Add some extra for building Win32 paths for the file encryption APIs,
810 * and ensure we have at least enough to potentially use a 8.3 name for
811 * the last component. */
812 path_max += max(2 + (ctx->target_ntpath.Length / sizeof(wchar_t)),
815 ctx->pathbuf.MaximumLength = path_max * sizeof(wchar_t);
816 ctx->pathbuf.Buffer = MALLOC(ctx->pathbuf.MaximumLength);
817 if (!ctx->pathbuf.Buffer)
818 return WIMLIB_ERR_NOMEM;
820 ctx->attr.RootDirectory = ctx->h_target;
821 ctx->attr.ObjectName = &ctx->pathbuf;
823 ctx->print_buffer = MALLOC((ctx->common.target_nchars + 1 + path_max + 1) *
825 if (!ctx->print_buffer)
826 return WIMLIB_ERR_NOMEM;
831 /* When creating an inode that will have a short (DOS) name, we create it using
832 * the long name associated with the short name. This ensures that the short
833 * name gets associated with the correct long name. */
834 static struct wim_dentry *
835 first_extraction_alias(const struct wim_inode *inode)
837 struct list_head *next = inode->i_extraction_aliases.next;
838 struct wim_dentry *dentry;
841 dentry = list_entry(next, struct wim_dentry,
842 d_extraction_alias_node);
843 if (dentry_has_short_name(dentry))
846 } while (next != &inode->i_extraction_aliases);
851 * Set or clear FILE_ATTRIBUTE_COMPRESSED if the inherited value is different
852 * from the desired value.
854 * Note that you can NOT override the inherited value of
855 * FILE_ATTRIBUTE_COMPRESSED directly with NtCreateFile().
858 adjust_compression_attribute(HANDLE h, const struct wim_dentry *dentry,
859 struct win32_apply_ctx *ctx)
861 const bool compressed = (dentry->d_inode->i_attributes &
862 FILE_ATTRIBUTE_COMPRESSED);
864 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
867 if (!ctx->common.supported_features.compressed_files)
870 FILE_BASIC_INFORMATION info;
872 USHORT compression_state;
874 /* Get current attributes */
875 status = (*func_NtQueryInformationFile)(h, &ctx->iosb,
877 FileBasicInformation);
878 if (NT_SUCCESS(status) &&
879 compressed == !!(info.FileAttributes & FILE_ATTRIBUTE_COMPRESSED))
881 /* Nothing needs to be done. */
885 /* Set the new compression state */
888 compression_state = COMPRESSION_FORMAT_DEFAULT;
890 compression_state = COMPRESSION_FORMAT_NONE;
892 status = (*func_NtFsControlFile)(h,
897 FSCTL_SET_COMPRESSION,
902 if (NT_SUCCESS(status))
905 set_errno_from_nt_status(status);
906 ERROR_WITH_ERRNO("Can't %s compression attribute on \"%ls\" "
907 "(status=0x%08"PRIx32")",
908 (compressed ? "set" : "clear"),
909 current_path(ctx), status);
910 return WIMLIB_ERR_SET_ATTRIBUTES;
914 * Clear FILE_ATTRIBUTE_ENCRYPTED if the file or directory is not supposed to be
917 * You can provide FILE_ATTRIBUTE_ENCRYPTED to NtCreateFile() to set it on the
918 * created file. However, the file or directory will otherwise default to the
919 * encryption state of the parent directory. This function works around this
920 * limitation by using DecryptFile() to remove FILE_ATTRIBUTE_ENCRYPTED on files
921 * (and directories) that are not supposed to have it set.
923 * Regardless of whether it succeeds or fails, this function may close the
924 * handle to the file. If it does, it sets it to NULL.
927 maybe_clear_encryption_attribute(HANDLE *h_ptr, const struct wim_dentry *dentry,
928 struct win32_apply_ctx *ctx)
930 if (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)
933 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
936 if (!ctx->common.supported_features.encrypted_files)
939 FILE_BASIC_INFORMATION info;
943 /* Get current attributes */
944 status = (*func_NtQueryInformationFile)(*h_ptr, &ctx->iosb,
946 FileBasicInformation);
947 if (NT_SUCCESS(status) &&
948 !(info.FileAttributes & FILE_ATTRIBUTE_ENCRYPTED))
950 /* Nothing needs to be done. */
954 /* Set the new encryption state */
956 /* Due to Windows' crappy file encryption APIs, we need to close the
957 * handle to the file so we don't get ERROR_SHARING_VIOLATION. We also
958 * hack together a Win32 path, although we will use the \\?\ prefix so
959 * it will actually be a NT path in disguise... */
960 (*func_NtClose)(*h_ptr);
963 build_win32_extraction_path(dentry, ctx);
965 bret = DecryptFile(ctx->pathbuf.Buffer, 0);
967 /* Restore the NT namespace path */
968 build_extraction_path(dentry, ctx);
971 DWORD err = GetLastError();
972 set_errno_from_win32_error(err);
973 ERROR_WITH_ERRNO("Can't decrypt file \"%ls\" (err=%"PRIu32")",
974 current_path(ctx), (u32)err);
975 return WIMLIB_ERR_SET_ATTRIBUTES;
980 /* Try to enable short name support on the target volume. If successful, return
981 * true. If unsuccessful, issue a warning and return false. */
983 try_to_enable_short_names(const wchar_t *volume)
986 FILE_FS_PERSISTENT_VOLUME_INFORMATION info;
990 h = CreateFile(volume, GENERIC_WRITE,
991 FILE_SHARE_VALID_FLAGS, NULL, OPEN_EXISTING,
992 FILE_FLAG_BACKUP_SEMANTICS, NULL);
993 if (h == INVALID_HANDLE_VALUE)
996 info.VolumeFlags = 0;
997 info.FlagMask = PERSISTENT_VOLUME_STATE_SHORT_NAME_CREATION_DISABLED;
1001 bret = DeviceIoControl(h, FSCTL_SET_PERSISTENT_VOLUME_STATE,
1002 &info, sizeof(info), NULL, 0,
1003 &bytesReturned, NULL);
1012 WARNING("Failed to enable short name support on %ls "
1013 "(err=%"PRIu32")", volume + 4, (u32)GetLastError());
1018 remove_conflicting_short_name(const struct wim_dentry *dentry, struct win32_apply_ctx *ctx)
1024 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1025 (13 * sizeof(wchar_t));
1026 u8 buf[bufsize] _aligned_attribute(8);
1027 bool retried = false;
1028 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1030 memset(buf, 0, bufsize);
1032 /* Build the path with the short name. */
1033 name = &ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)];
1034 while (name != ctx->pathbuf.Buffer && *(name - 1) != L'\\')
1036 end = mempcpy(name, dentry->short_name, dentry->short_name_nbytes);
1037 ctx->pathbuf.Length = ((u8 *)end - (u8 *)ctx->pathbuf.Buffer);
1039 /* Open the conflicting file (by short name). */
1040 status = (*func_NtOpenFile)(&h, GENERIC_WRITE | DELETE,
1041 &ctx->attr, &ctx->iosb,
1042 FILE_SHARE_VALID_FLAGS,
1043 FILE_OPEN_REPARSE_POINT | FILE_OPEN_FOR_BACKUP_INTENT);
1044 if (!NT_SUCCESS(status)) {
1045 WARNING("Can't open \"%ls\" (status=0x%08"PRIx32")",
1046 current_path(ctx), (u32)status);
1051 WARNING("Overriding conflicting short name; path=\"%ls\"",
1055 /* Try to remove the short name on the conflicting file. */
1058 status = (*func_NtSetInformationFile)(h, &ctx->iosb, info, bufsize,
1059 FileShortNameInformation);
1061 if (status == STATUS_INVALID_PARAMETER && !retried) {
1063 /* Microsoft forgot to make it possible to remove short names
1064 * until Windows 7. Oops. Use a random short name instead. */
1066 info->FileNameLength = 12 * sizeof(wchar_t);
1067 for (int i = 0; i < 8; i++)
1068 info->FileName[i] = 'A' + (rand() % 26);
1069 info->FileName[8] = L'.';
1070 info->FileName[9] = L'W';
1071 info->FileName[10] = L'L';
1072 info->FileName[11] = L'B';
1073 info->FileName[12] = L'\0';
1079 build_extraction_path(dentry, ctx);
1083 /* Set the short name on the open file @h which has been created at the location
1084 * indicated by @dentry.
1086 * Note that this may add, change, or remove the short name.
1088 * @h must be opened with DELETE access.
1090 * Returns 0 or WIMLIB_ERR_SET_SHORT_NAME. The latter only happens in
1091 * STRICT_SHORT_NAMES mode.
1094 set_short_name(HANDLE h, const struct wim_dentry *dentry,
1095 struct win32_apply_ctx *ctx)
1098 if (!ctx->common.supported_features.short_names)
1102 * Note: The size of the FILE_NAME_INFORMATION buffer must be such that
1103 * FileName contains at least 2 wide characters (4 bytes). Otherwise,
1104 * NtSetInformationFile() will return STATUS_INFO_LENGTH_MISMATCH. This
1105 * is despite the fact that FileNameLength can validly be 0 or 2 bytes,
1106 * with the former case being removing the existing short name if
1107 * present, rather than setting one.
1109 * The null terminator is seemingly optional, but to be safe we include
1110 * space for it and zero all unused space.
1113 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1114 max(dentry->short_name_nbytes, sizeof(wchar_t)) +
1116 u8 buf[bufsize] _aligned_attribute(8);
1117 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1119 bool tried_to_remove_existing = false;
1121 memset(buf, 0, bufsize);
1123 info->FileNameLength = dentry->short_name_nbytes;
1124 memcpy(info->FileName, dentry->short_name, dentry->short_name_nbytes);
1127 status = (*func_NtSetInformationFile)(h, &ctx->iosb, info, bufsize,
1128 FileShortNameInformation);
1129 if (NT_SUCCESS(status))
1132 if (status == STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME) {
1133 if (dentry->short_name_nbytes == 0)
1135 if (!ctx->tried_to_enable_short_names) {
1139 ctx->tried_to_enable_short_names = true;
1141 ret = win32_get_drive_path(ctx->common.target,
1145 if (try_to_enable_short_names(volume))
1151 * Short names can conflict in several cases:
1153 * - a file being extracted has a short name conflicting with an
1156 * - a file being extracted has a short name conflicting with another
1157 * file being extracted (possible, but shouldn't happen)
1159 * - a file being extracted has a short name that conflicts with the
1160 * automatically generated short name of a file we previously
1161 * extracted, but failed to set the short name for. Sounds unlikely,
1162 * but this actually does happen fairly often on versions of Windows
1163 * prior to Windows 7 because they do not support removing short names
1166 if (unlikely(status == STATUS_OBJECT_NAME_COLLISION) &&
1167 dentry->short_name_nbytes && !tried_to_remove_existing)
1169 tried_to_remove_existing = true;
1170 status = remove_conflicting_short_name(dentry, ctx);
1171 if (NT_SUCCESS(status))
1175 /* By default, failure to set short names is not an error (since short
1176 * names aren't too important anymore...). */
1177 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES)) {
1178 if (dentry->short_name_nbytes)
1179 ctx->num_set_short_name_failures++;
1181 ctx->num_remove_short_name_failures++;
1185 if (status == STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME) {
1186 ERROR("Can't set short name when short "
1187 "names are not enabled on the volume!");
1189 ERROR("Can't set short name on \"%ls\" (status=0x%08"PRIx32")",
1190 current_path(ctx), (u32)status);
1192 return WIMLIB_ERR_SET_SHORT_NAME;
1196 * A wrapper around NtCreateFile() to make it slightly more usable...
1197 * This uses the path currently constructed in ctx->pathbuf.
1199 * Also, we always specify FILE_OPEN_FOR_BACKUP_INTENT and
1200 * FILE_OPEN_REPARSE_POINT.
1203 do_create_file(PHANDLE FileHandle,
1204 ACCESS_MASK DesiredAccess,
1205 PLARGE_INTEGER AllocationSize,
1206 ULONG FileAttributes,
1207 ULONG CreateDisposition,
1208 ULONG CreateOptions,
1209 struct win32_apply_ctx *ctx)
1211 return (*func_NtCreateFile)(FileHandle,
1217 FILE_SHARE_VALID_FLAGS,
1220 FILE_OPEN_FOR_BACKUP_INTENT |
1221 FILE_OPEN_REPARSE_POINT,
1226 /* Like do_create_file(), but builds the extraction path of the @dentry first.
1229 create_file(PHANDLE FileHandle,
1230 ACCESS_MASK DesiredAccess,
1231 PLARGE_INTEGER AllocationSize,
1232 ULONG FileAttributes,
1233 ULONG CreateDisposition,
1234 ULONG CreateOptions,
1235 const struct wim_dentry *dentry,
1236 struct win32_apply_ctx *ctx)
1238 build_extraction_path(dentry, ctx);
1239 return do_create_file(FileHandle,
1248 /* Create empty named data streams.
1250 * Since these won't have 'struct wim_lookup_table_entry's, they won't show up
1251 * in the call to extract_stream_list(). Hence the need for the special case.
1254 create_any_empty_ads(const struct wim_dentry *dentry,
1255 struct win32_apply_ctx *ctx)
1257 const struct wim_inode *inode = dentry->d_inode;
1258 LARGE_INTEGER allocation_size;
1259 bool path_modified = false;
1262 if (!ctx->common.supported_features.named_data_streams)
1265 for (u16 i = 0; i < inode->i_num_ads; i++) {
1266 const struct wim_ads_entry *entry;
1272 entry = &inode->i_ads_entries[i];
1275 if (!entry->stream_name_nbytes)
1282 /* Probably setting the allocation size to 0 has no effect, but
1283 * we might as well try. */
1284 allocation_size.QuadPart = 0;
1286 build_extraction_path_with_ads(dentry, ctx,
1288 entry->stream_name_nbytes /
1290 path_modified = true;
1293 disposition = FILE_SUPERSEDE;
1295 status = do_create_file(&h, FILE_WRITE_DATA, &allocation_size,
1296 0, disposition, 0, ctx);
1297 if (unlikely(!NT_SUCCESS(status))) {
1298 if (status == STATUS_OBJECT_NAME_NOT_FOUND && !retried) {
1299 /* Workaround for defect in the Windows PE
1300 * in-memory filesystem implementation:
1301 * FILE_SUPERSEDE does not create the file, as
1302 * expected and documented, when the named file
1303 * does not exist. */
1305 disposition = FILE_CREATE;
1308 set_errno_from_nt_status(status);
1309 ERROR_WITH_ERRNO("Can't create \"%ls\" "
1310 "(status=0x%08"PRIx32")",
1311 current_path(ctx), (u32)status);
1312 ret = WIMLIB_ERR_OPEN;
1317 /* Restore the path to the dentry itself */
1319 build_extraction_path(dentry, ctx);
1324 * Creates the directory named by @dentry, or uses an existing directory at that
1325 * location. If necessary, sets the short name and/or fixes compression and
1326 * encryption attributes.
1328 * Returns 0, WIMLIB_ERR_MKDIR, or WIMLIB_ERR_SET_SHORT_NAME.
1331 create_directory(const struct wim_dentry *dentry,
1332 struct win32_apply_ctx *ctx)
1339 /* Special attributes:
1341 * Use FILE_ATTRIBUTE_ENCRYPTED if the directory needs to have it set.
1342 * This doesn't work for FILE_ATTRIBUTE_COMPRESSED (unfortunately).
1344 * Don't specify FILE_ATTRIBUTE_DIRECTORY; it gets set anyway as a
1345 * result of the FILE_DIRECTORY_FILE option. */
1346 attrib = (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED);
1348 /* DELETE is needed for set_short_name().
1349 * GENERIC_READ and GENERIC_WRITE are needed for
1350 * adjust_compression_attribute(). */
1351 status = create_file(&h, GENERIC_READ | GENERIC_WRITE | DELETE, NULL,
1352 attrib, FILE_OPEN_IF, FILE_DIRECTORY_FILE,
1354 if (!NT_SUCCESS(status)) {
1355 set_errno_from_nt_status(status);
1356 ERROR_WITH_ERRNO("Can't create directory \"%ls\" "
1357 "(status=0x%08"PRIx32")",
1358 current_path(ctx), (u32)status);
1359 return WIMLIB_ERR_MKDIR;
1362 ret = set_short_name(h, dentry, ctx);
1365 ret = adjust_compression_attribute(h, dentry, ctx);
1368 ret = maybe_clear_encryption_attribute(&h, dentry, ctx);
1369 /* May close the handle!!! */
1377 * Create all the directories being extracted, other than the target directory
1380 * Note: we don't honor directory hard links. However, we don't allow them to
1381 * exist in WIM images anyway (see inode_fixup.c).
1384 create_directories(struct list_head *dentry_list,
1385 struct win32_apply_ctx *ctx)
1387 const struct wim_dentry *dentry;
1390 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1392 if (!(dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY))
1395 /* Note: Here we include files with
1396 * FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT, but we
1397 * wait until later to actually set the reparse data. */
1399 /* If the root dentry is being extracted, it was already done so
1400 * in prepare_target(). */
1401 if (!dentry_is_root(dentry)) {
1402 ret = create_directory(dentry, ctx);
1403 ret = check_apply_error(dentry, ctx, ret);
1407 ret = create_any_empty_ads(dentry, ctx);
1408 ret = check_apply_error(dentry, ctx, ret);
1413 ret = report_file_created(&ctx->common);
1421 * Creates the nondirectory file named by @dentry.
1423 * On success, returns an open handle to the file in @h_ret, with GENERIC_READ,
1424 * GENERIC_WRITE, and DELETE access. Also, the path to the file will be saved
1425 * in ctx->pathbuf. On failure, returns WIMLIB_ERR_OPEN.
1428 create_nondirectory_inode(HANDLE *h_ret, const struct wim_dentry *dentry,
1429 struct win32_apply_ctx *ctx)
1431 const struct wim_inode *inode;
1434 bool retried = false;
1437 inode = dentry->d_inode;
1439 /* If the file already exists and has FILE_ATTRIBUTE_SYSTEM and/or
1440 * FILE_ATTRIBUTE_HIDDEN, these must be specified in order to supersede
1443 * Normally the user shouldn't be trying to overwrite such files anyway,
1444 * but we at least provide FILE_ATTRIBUTE_SYSTEM and
1445 * FILE_ATTRIBUTE_HIDDEN if the WIM inode has those attributes so that
1446 * we catch the case where the user extracts the same files to the same
1447 * location more than one time.
1449 * Also specify FILE_ATTRIBUTE_ENCRYPTED if the file needs to be
1452 * In NO_ATTRIBUTES mode just don't specify any attributes at all.
1454 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES) {
1457 attrib = (inode->i_attributes & (FILE_ATTRIBUTE_SYSTEM |
1458 FILE_ATTRIBUTE_HIDDEN |
1459 FILE_ATTRIBUTE_ENCRYPTED));
1461 build_extraction_path(dentry, ctx);
1462 disposition = FILE_SUPERSEDE;
1464 status = do_create_file(h_ret, GENERIC_READ | GENERIC_WRITE | DELETE,
1465 NULL, attrib, disposition,
1466 FILE_NON_DIRECTORY_FILE, ctx);
1467 if (likely(NT_SUCCESS(status))) {
1470 ret = adjust_compression_attribute(*h_ret, dentry, ctx);
1472 (*func_NtClose)(*h_ret);
1476 ret = maybe_clear_encryption_attribute(h_ret, dentry, ctx);
1477 /* May close the handle!!! */
1481 (*func_NtClose)(*h_ret);
1486 /* Re-open the handle so that we can return it on
1488 status = do_create_file(h_ret,
1490 GENERIC_WRITE | DELETE,
1492 FILE_NON_DIRECTORY_FILE, ctx);
1493 if (!NT_SUCCESS(status))
1497 ret = create_any_empty_ads(dentry, ctx);
1499 (*func_NtClose)(*h_ret);
1505 if (status == STATUS_OBJECT_NAME_NOT_FOUND && !retried) {
1506 /* Workaround for defect in the Windows PE in-memory filesystem
1507 * implementation: FILE_SUPERSEDE does not create the file, as
1508 * expected and documented, when the named file does not exist.
1511 disposition = FILE_CREATE;
1515 if (status == STATUS_ACCESS_DENIED && !retried) {
1516 /* We also can't supersede an existing file that has
1517 * FILE_ATTRIBUTE_READONLY set; doing so causes NtCreateFile()
1518 * to return STATUS_ACCESS_DENIED . The only workaround seems
1519 * to be to explicitly remove FILE_ATTRIBUTE_READONLY on the
1520 * existing file, then try again. */
1522 FILE_BASIC_INFORMATION info;
1525 status = do_create_file(&h, FILE_WRITE_ATTRIBUTES, NULL, 0,
1526 FILE_OPEN, FILE_NON_DIRECTORY_FILE, ctx);
1527 if (!NT_SUCCESS(status))
1530 memset(&info, 0, sizeof(info));
1531 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1533 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1534 &info, sizeof(info),
1535 FileBasicInformation);
1537 if (!NT_SUCCESS(status))
1543 set_errno_from_nt_status(status);
1544 ERROR_WITH_ERRNO("Can't create file \"%ls\" (status=0x%08"PRIx32")",
1545 current_path(ctx), (u32)status);
1546 return WIMLIB_ERR_OPEN;
1549 /* Creates a hard link at the location named by @dentry to the file represented
1550 * by the open handle @h. Or, if the target volume does not support hard links,
1551 * create a separate file instead. */
1553 create_link(HANDLE h, const struct wim_dentry *dentry,
1554 struct win32_apply_ctx *ctx)
1556 if (ctx->common.supported_features.hard_links) {
1558 build_extraction_path(dentry, ctx);
1560 size_t bufsize = offsetof(FILE_LINK_INFORMATION, FileName) +
1561 ctx->pathbuf.Length + sizeof(wchar_t);
1562 u8 buf[bufsize] _aligned_attribute(8);
1563 FILE_LINK_INFORMATION *info = (FILE_LINK_INFORMATION *)buf;
1566 info->ReplaceIfExists = TRUE;
1567 info->RootDirectory = ctx->attr.RootDirectory;
1568 info->FileNameLength = ctx->pathbuf.Length;
1569 memcpy(info->FileName, ctx->pathbuf.Buffer, ctx->pathbuf.Length);
1570 info->FileName[info->FileNameLength / 2] = L'\0';
1572 /* Note: the null terminator isn't actually necessary,
1573 * but if you don't add the extra character, you get
1574 * STATUS_INFO_LENGTH_MISMATCH when FileNameLength
1575 * happens to be 2 */
1577 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1579 FileLinkInformation);
1580 if (NT_SUCCESS(status))
1582 ERROR("Failed to create link \"%ls\" (status=0x%08"PRIx32")",
1583 current_path(ctx), (u32)status);
1584 return WIMLIB_ERR_LINK;
1589 ret = create_nondirectory_inode(&h2, dentry, ctx);
1593 (*func_NtClose)(h2);
1598 /* Given an inode (represented by the open handle @h) for which one link has
1599 * been created (named by @first_dentry), create the other links.
1601 * Or, if the target volume does not support hard links, create separate files.
1603 * Note: This uses ctx->pathbuf and does not reset it.
1606 create_links(HANDLE h, const struct wim_dentry *first_dentry,
1607 struct win32_apply_ctx *ctx)
1609 const struct wim_inode *inode;
1610 const struct list_head *next;
1611 const struct wim_dentry *dentry;
1614 inode = first_dentry->d_inode;
1615 next = inode->i_extraction_aliases.next;
1617 dentry = list_entry(next, struct wim_dentry,
1618 d_extraction_alias_node);
1619 if (dentry != first_dentry) {
1620 ret = create_link(h, dentry, ctx);
1625 } while (next != &inode->i_extraction_aliases);
1629 /* Create a nondirectory file, including all links. */
1631 create_nondirectory(struct wim_inode *inode, struct win32_apply_ctx *ctx)
1633 struct wim_dentry *first_dentry;
1637 first_dentry = first_extraction_alias(inode);
1639 /* Create first link. */
1640 ret = create_nondirectory_inode(&h, first_dentry, ctx);
1644 /* Set short name. */
1645 ret = set_short_name(h, first_dentry, ctx);
1647 /* Create additional links, OR if hard links are not supported just
1648 * create more files. */
1650 ret = create_links(h, first_dentry, ctx);
1652 /* "WIMBoot" extraction: set external backing by the WIM file if needed. */
1653 if (!ret && unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
1654 ret = set_external_backing(h, inode, ctx);
1660 /* Create all the nondirectory files being extracted, including all aliases
1663 create_nondirectories(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1665 struct wim_dentry *dentry;
1666 struct wim_inode *inode;
1669 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1670 inode = dentry->d_inode;
1671 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1673 /* Call create_nondirectory() only once per inode */
1674 if (dentry == inode_first_extraction_dentry(inode)) {
1675 ret = create_nondirectory(inode, ctx);
1676 ret = check_apply_error(dentry, ctx, ret);
1680 ret = report_file_created(&ctx->common);
1688 close_handles(struct win32_apply_ctx *ctx)
1690 for (unsigned i = 0; i < ctx->num_open_handles; i++)
1691 (*func_NtClose)(ctx->open_handles[i]);
1694 /* Prepare to read the next stream, which has size @stream_size, into an
1695 * in-memory buffer. */
1697 prepare_data_buffer(struct win32_apply_ctx *ctx, u64 stream_size)
1699 if (stream_size > ctx->data_buffer_size) {
1700 /* Larger buffer needed. */
1702 if ((size_t)stream_size != stream_size)
1704 new_buffer = REALLOC(ctx->data_buffer, stream_size);
1707 ctx->data_buffer = new_buffer;
1708 ctx->data_buffer_size = stream_size;
1710 /* On the first call this changes data_buffer_ptr from NULL, which tells
1711 * extract_chunk() that the data buffer needs to be filled while reading
1712 * the stream data. */
1713 ctx->data_buffer_ptr = ctx->data_buffer;
1718 begin_extract_stream_instance(const struct wim_lookup_table_entry *stream,
1719 struct wim_dentry *dentry,
1720 const wchar_t *stream_name,
1721 struct win32_apply_ctx *ctx)
1723 const struct wim_inode *inode = dentry->d_inode;
1724 size_t stream_name_nchars = 0;
1725 FILE_ALLOCATION_INFORMATION alloc_info;
1729 if (unlikely(stream_name))
1730 stream_name_nchars = wcslen(stream_name);
1732 if (unlikely(stream_name_nchars)) {
1733 build_extraction_path_with_ads(dentry, ctx,
1734 stream_name, stream_name_nchars);
1736 build_extraction_path(dentry, ctx);
1739 /* Reparse point? */
1740 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1741 && (stream_name_nchars == 0))
1743 if (!ctx->common.supported_features.reparse_points)
1746 /* We can't write the reparse stream directly; we must set it
1747 * with FSCTL_SET_REPARSE_POINT, which requires that all the
1748 * data be available. So, stage the data in a buffer. */
1750 if (!prepare_data_buffer(ctx, stream->size))
1751 return WIMLIB_ERR_NOMEM;
1752 list_add_tail(&dentry->tmp_list, &ctx->reparse_dentries);
1756 /* Encrypted file? */
1757 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)
1758 && (stream_name_nchars == 0))
1760 if (!ctx->common.supported_features.encrypted_files)
1763 /* We can't write encrypted file streams directly; we must use
1764 * WriteEncryptedFileRaw(), which requires providing the data
1765 * through a callback function. This can't easily be combined
1766 * with our own callback-based approach.
1768 * The current workaround is to simply read the stream into
1769 * memory and write the encrypted file from that.
1771 * TODO: This isn't sufficient for extremely large encrypted
1772 * files. Perhaps we should create an extra thread to write
1774 if (!prepare_data_buffer(ctx, stream->size))
1775 return WIMLIB_ERR_NOMEM;
1776 list_add_tail(&dentry->tmp_list, &ctx->encrypted_dentries);
1780 if (ctx->num_open_handles == MAX_OPEN_STREAMS) {
1781 /* XXX: Fix this. But because of the checks in
1782 * extract_stream_list(), this can now only happen on a
1783 * filesystem that does not support hard links. */
1784 ERROR("Can't extract data: too many open files!");
1785 return WIMLIB_ERR_UNSUPPORTED;
1788 /* Open a new handle */
1789 status = do_create_file(&h,
1790 FILE_WRITE_DATA | SYNCHRONIZE,
1791 NULL, 0, FILE_OPEN_IF,
1792 FILE_SEQUENTIAL_ONLY |
1793 FILE_SYNCHRONOUS_IO_NONALERT,
1795 if (!NT_SUCCESS(status)) {
1796 set_errno_from_nt_status(status);
1797 ERROR_WITH_ERRNO("Can't open \"%ls\" for writing "
1798 "(status=0x%08"PRIx32")",
1799 current_path(ctx), (u32)status);
1800 return WIMLIB_ERR_OPEN;
1803 ctx->open_handles[ctx->num_open_handles++] = h;
1805 /* Allocate space for the data. */
1806 alloc_info.AllocationSize.QuadPart = stream->size;
1807 (*func_NtSetInformationFile)(h, &ctx->iosb,
1808 &alloc_info, sizeof(alloc_info),
1809 FileAllocationInformation);
1813 /* Set the reparse data @rpbuf of length @rpbuflen on the extracted file
1814 * corresponding to the WIM dentry @dentry. */
1816 do_set_reparse_data(const struct wim_dentry *dentry,
1817 const void *rpbuf, u16 rpbuflen,
1818 struct win32_apply_ctx *ctx)
1823 status = create_file(&h, GENERIC_WRITE, NULL,
1824 0, FILE_OPEN, 0, dentry, ctx);
1825 if (!NT_SUCCESS(status))
1828 status = (*func_NtFsControlFile)(h, NULL, NULL, NULL,
1829 &ctx->iosb, FSCTL_SET_REPARSE_POINT,
1830 (void *)rpbuf, rpbuflen,
1834 if (NT_SUCCESS(status))
1837 /* On Windows, by default only the Administrator can create symbolic
1838 * links for some reason. By default we just issue a warning if this
1839 * appears to be the problem. Use WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS
1840 * to get a hard error. */
1841 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS)
1842 && (status == STATUS_PRIVILEGE_NOT_HELD ||
1843 status == STATUS_ACCESS_DENIED)
1844 && (dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1845 dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1847 WARNING("Can't create symbolic link \"%ls\"! \n"
1848 " (Need Administrator rights, or at least "
1850 " SeCreateSymbolicLink privilege.)",
1856 set_errno_from_nt_status(status);
1857 ERROR_WITH_ERRNO("Can't set reparse data on \"%ls\" "
1858 "(status=0x%08"PRIx32")",
1859 current_path(ctx), (u32)status);
1860 return WIMLIB_ERR_SET_REPARSE_DATA;
1863 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1864 * pointer to the suffix of the path that begins with the device directly, such
1865 * as e:\Windows\System32. */
1866 static const wchar_t *
1867 skip_nt_toplevel_component(const wchar_t *path, size_t path_nchars)
1869 static const wchar_t * const dirs[] = {
1874 size_t first_dir_len = 0;
1875 const wchar_t * const end = path + path_nchars;
1877 for (size_t i = 0; i < ARRAY_LEN(dirs); i++) {
1878 size_t len = wcslen(dirs[i]);
1879 if (len <= (end - path) && !wcsnicmp(path, dirs[i], len)) {
1880 first_dir_len = len;
1884 if (first_dir_len == 0)
1886 path += first_dir_len;
1887 while (path != end && *path == L'\\')
1892 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1893 * pointer to the suffix of the path that is device-relative, such as
1896 * The path has an explicit length and is not necessarily null terminated.
1898 * If the path just something like \??\e: then the returned pointer will point
1899 * just past the colon. In this case the length of the result will be 0
1901 static const wchar_t *
1902 get_device_relative_path(const wchar_t *path, size_t path_nchars)
1904 const wchar_t * const orig_path = path;
1905 const wchar_t * const end = path + path_nchars;
1907 path = skip_nt_toplevel_component(path, path_nchars);
1908 if (path == orig_path)
1911 path = wmemchr(path, L'\\', (end - path));
1916 } while (path != end && *path == L'\\');
1921 * Given a reparse point buffer for a symbolic link or junction, adjust its
1922 * contents so that the target of the link is consistent with the new location
1926 try_rpfix(u8 *rpbuf, u16 *rpbuflen_p, struct win32_apply_ctx *ctx)
1928 struct reparse_data rpdata;
1929 size_t orig_subst_name_nchars;
1930 const wchar_t *relpath;
1931 size_t relpath_nchars;
1932 size_t target_ntpath_nchars;
1933 size_t fixed_subst_name_nchars;
1934 const wchar_t *fixed_print_name;
1935 size_t fixed_print_name_nchars;
1937 if (parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata)) {
1938 /* Do nothing if the reparse data is invalid. */
1942 if (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
1943 (rpdata.rpflags & SYMBOLIC_LINK_RELATIVE))
1945 /* Do nothing if it's a relative symbolic link. */
1949 /* Build the new substitute name from the NT namespace path to the
1950 * target directory, then a path separator, then the "device relative"
1951 * part of the old substitute name. */
1953 orig_subst_name_nchars = rpdata.substitute_name_nbytes / sizeof(wchar_t);
1955 relpath = get_device_relative_path(rpdata.substitute_name,
1956 orig_subst_name_nchars);
1957 relpath_nchars = orig_subst_name_nchars -
1958 (relpath - rpdata.substitute_name);
1960 target_ntpath_nchars = ctx->target_ntpath.Length / sizeof(wchar_t);
1962 fixed_subst_name_nchars = target_ntpath_nchars;
1964 fixed_subst_name_nchars += 1 + relpath_nchars;
1965 wchar_t fixed_subst_name[fixed_subst_name_nchars];
1967 wmemcpy(fixed_subst_name, ctx->target_ntpath.Buffer,
1968 target_ntpath_nchars);
1969 if (relpath_nchars) {
1970 fixed_subst_name[target_ntpath_nchars] = L'\\';
1971 wmemcpy(&fixed_subst_name[target_ntpath_nchars + 1],
1972 relpath, relpath_nchars);
1974 /* Doesn't need to be null-terminated. */
1976 /* Print name should be Win32, but not all NT names can even be
1977 * translated to Win32 names. But we can at least delete the top-level
1978 * directory, such as \??\, and this will have the expected result in
1979 * the usual case. */
1980 fixed_print_name = skip_nt_toplevel_component(fixed_subst_name,
1981 fixed_subst_name_nchars);
1982 fixed_print_name_nchars = fixed_subst_name_nchars - (fixed_print_name -
1985 rpdata.substitute_name = fixed_subst_name;
1986 rpdata.substitute_name_nbytes = fixed_subst_name_nchars * sizeof(wchar_t);
1987 rpdata.print_name = (wchar_t *)fixed_print_name;
1988 rpdata.print_name_nbytes = fixed_print_name_nchars * sizeof(wchar_t);
1989 make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
1992 /* Sets reparse data on the specified file. This handles "fixing" the targets
1993 * of absolute symbolic links and junctions if WIMLIB_EXTRACT_FLAG_RPFIX was
1996 set_reparse_data(const struct wim_dentry *dentry,
1997 const void *_rpbuf, u16 rpbuflen, struct win32_apply_ctx *ctx)
1999 const struct wim_inode *inode = dentry->d_inode;
2000 const void *rpbuf = _rpbuf;
2002 if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
2003 && !inode->i_not_rpfixed
2004 && (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
2005 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
2007 memcpy(&ctx->rpfixbuf, _rpbuf, rpbuflen);
2008 try_rpfix((u8 *)&ctx->rpfixbuf, &rpbuflen, ctx);
2009 rpbuf = &ctx->rpfixbuf;
2011 return do_set_reparse_data(dentry, rpbuf, rpbuflen, ctx);
2015 /* Import the next block of raw encrypted data */
2017 import_encrypted_data(PBYTE pbData, PVOID pvCallbackContext, PULONG Length)
2019 struct win32_apply_ctx *ctx = pvCallbackContext;
2022 copy_len = min(ctx->encrypted_size - ctx->encrypted_offset, *Length);
2023 memcpy(pbData, &ctx->data_buffer[ctx->encrypted_offset], copy_len);
2024 ctx->encrypted_offset += copy_len;
2026 return ERROR_SUCCESS;
2029 /* Write the raw encrypted data to the already-created file corresponding to
2032 * The raw encrypted data is provided in ctx->data_buffer, and its size is
2033 * ctx->encrypted_size. */
2035 extract_encrypted_file(const struct wim_dentry *dentry,
2036 struct win32_apply_ctx *ctx)
2041 /* Temporarily build a Win32 path for OpenEncryptedFileRaw() */
2042 build_win32_extraction_path(dentry, ctx);
2044 err = OpenEncryptedFileRaw(ctx->pathbuf.Buffer,
2045 CREATE_FOR_IMPORT, &rawctx);
2047 /* Restore the NT namespace path */
2048 build_extraction_path(dentry, ctx);
2050 if (err != ERROR_SUCCESS) {
2051 set_errno_from_win32_error(err);
2052 ERROR_WITH_ERRNO("Can't open \"%ls\" for encrypted import "
2053 "(err=%"PRIu32")", current_path(ctx), (u32)err);
2054 return WIMLIB_ERR_OPEN;
2057 ctx->encrypted_offset = 0;
2059 err = WriteEncryptedFileRaw(import_encrypted_data, ctx, rawctx);
2061 CloseEncryptedFileRaw(rawctx);
2063 if (err != ERROR_SUCCESS) {
2064 set_errno_from_win32_error(err);
2065 ERROR_WITH_ERRNO("Can't import encrypted file \"%ls\" "
2066 "(err=%"PRIu32")", current_path(ctx), (u32)err);
2067 return WIMLIB_ERR_WRITE;
2073 /* Called when starting to read a stream for extraction on Windows */
2075 begin_extract_stream(struct wim_lookup_table_entry *stream, void *_ctx)
2077 struct win32_apply_ctx *ctx = _ctx;
2078 const struct stream_owner *owners = stream_owners(stream);
2081 ctx->num_open_handles = 0;
2082 ctx->data_buffer_ptr = NULL;
2083 INIT_LIST_HEAD(&ctx->reparse_dentries);
2084 INIT_LIST_HEAD(&ctx->encrypted_dentries);
2086 for (u32 i = 0; i < stream->out_refcnt; i++) {
2087 const struct wim_inode *inode = owners[i].inode;
2088 const wchar_t *stream_name = owners[i].stream_name;
2089 struct wim_dentry *dentry;
2091 /* A copy of the stream needs to be extracted to @inode. */
2093 if (ctx->common.supported_features.hard_links) {
2094 dentry = inode_first_extraction_dentry(inode);
2095 ret = begin_extract_stream_instance(stream, dentry,
2097 ret = check_apply_error(dentry, ctx, ret);
2101 /* Hard links not supported. Extract the stream
2102 * separately to each alias of the inode. */
2103 struct list_head *next;
2105 next = inode->i_extraction_aliases.next;
2107 dentry = list_entry(next, struct wim_dentry,
2108 d_extraction_alias_node);
2109 ret = begin_extract_stream_instance(stream,
2113 ret = check_apply_error(dentry, ctx, ret);
2117 } while (next != &inode->i_extraction_aliases);
2128 /* Called when the next chunk of a stream has been read for extraction on
2131 extract_chunk(const void *chunk, size_t size, void *_ctx)
2133 struct win32_apply_ctx *ctx = _ctx;
2135 /* Write the data chunk to each open handle */
2136 for (unsigned i = 0; i < ctx->num_open_handles; i++) {
2137 u8 *bufptr = (u8 *)chunk;
2138 size_t bytes_remaining = size;
2140 while (bytes_remaining) {
2141 ULONG count = min(0xFFFFFFFF, bytes_remaining);
2143 status = (*func_NtWriteFile)(ctx->open_handles[i],
2145 &ctx->iosb, bufptr, count,
2147 if (!NT_SUCCESS(status)) {
2148 set_errno_from_nt_status(status);
2149 ERROR_WITH_ERRNO("Error writing data to target "
2150 "volume (status=0x%08"PRIx32")",
2152 return WIMLIB_ERR_WRITE;
2154 bufptr += ctx->iosb.Information;
2155 bytes_remaining -= ctx->iosb.Information;
2159 /* Copy the data chunk into the buffer (if needed) */
2160 if (ctx->data_buffer_ptr)
2161 ctx->data_buffer_ptr = mempcpy(ctx->data_buffer_ptr,
2166 /* Called when a stream has been fully read for extraction on Windows */
2168 end_extract_stream(struct wim_lookup_table_entry *stream, int status, void *_ctx)
2170 struct win32_apply_ctx *ctx = _ctx;
2172 const struct wim_dentry *dentry;
2179 if (likely(!ctx->data_buffer_ptr))
2182 if (!list_empty(&ctx->reparse_dentries)) {
2183 if (stream->size > REPARSE_DATA_MAX_SIZE) {
2184 dentry = list_first_entry(&ctx->reparse_dentries,
2185 struct wim_dentry, tmp_list);
2186 build_extraction_path(dentry, ctx);
2187 ERROR("Reparse data of \"%ls\" has size "
2188 "%"PRIu64" bytes (exceeds %u bytes)",
2189 current_path(ctx), stream->size,
2190 REPARSE_DATA_MAX_SIZE);
2191 ret = WIMLIB_ERR_INVALID_REPARSE_DATA;
2192 return check_apply_error(dentry, ctx, ret);
2194 /* In the WIM format, reparse streams are just the reparse data
2195 * and omit the header. But we can reconstruct the header. */
2196 memcpy(ctx->rpbuf.rpdata, ctx->data_buffer, stream->size);
2197 ctx->rpbuf.rpdatalen = stream->size;
2198 ctx->rpbuf.rpreserved = 0;
2199 list_for_each_entry(dentry, &ctx->reparse_dentries, tmp_list) {
2200 ctx->rpbuf.rptag = dentry->d_inode->i_reparse_tag;
2201 ret = set_reparse_data(dentry, &ctx->rpbuf,
2202 stream->size + REPARSE_DATA_OFFSET,
2204 ret = check_apply_error(dentry, ctx, ret);
2210 if (!list_empty(&ctx->encrypted_dentries)) {
2211 ctx->encrypted_size = stream->size;
2212 list_for_each_entry(dentry, &ctx->encrypted_dentries, tmp_list) {
2213 ret = extract_encrypted_file(dentry, ctx);
2214 ret = check_apply_error(dentry, ctx, ret);
2223 /* Attributes that can't be set directly */
2224 #define SPECIAL_ATTRIBUTES \
2225 (FILE_ATTRIBUTE_REPARSE_POINT | \
2226 FILE_ATTRIBUTE_DIRECTORY | \
2227 FILE_ATTRIBUTE_ENCRYPTED | \
2228 FILE_ATTRIBUTE_SPARSE_FILE | \
2229 FILE_ATTRIBUTE_COMPRESSED)
2231 /* Set the security descriptor @desc, of @desc_size bytes, on the file with open
2234 set_security_descriptor(HANDLE h, const void *_desc,
2235 size_t desc_size, struct win32_apply_ctx *ctx)
2237 SECURITY_INFORMATION info;
2239 SECURITY_DESCRIPTOR_RELATIVE *desc;
2242 * Ideally, we would just pass in the security descriptor buffer as-is.
2243 * But it turns out that Windows can mess up the security descriptor
2244 * even when using the low-level NtSetSecurityObject() function:
2246 * - Windows will clear SE_DACL_AUTO_INHERITED if it is set in the
2247 * passed buffer. To actually get Windows to set
2248 * SE_DACL_AUTO_INHERITED, the application must set the non-persistent
2249 * flag SE_DACL_AUTO_INHERIT_REQ. As usual, Microsoft didn't bother
2250 * to properly document either of these flags. It's unclear how
2251 * important SE_DACL_AUTO_INHERITED actually is, but to be safe we use
2252 * the SE_DACL_AUTO_INHERIT_REQ workaround to set it if needed.
2254 * - The above also applies to the equivalent SACL flags,
2255 * SE_SACL_AUTO_INHERITED and SE_SACL_AUTO_INHERIT_REQ.
2257 * - If the application says that it's setting
2258 * DACL_SECURITY_INFORMATION, then Windows sets SE_DACL_PRESENT in the
2259 * resulting security descriptor, even if the security descriptor the
2260 * application provided did not have a DACL. This seems to be
2261 * unavoidable, since omitting DACL_SECURITY_INFORMATION would cause a
2262 * default DACL to remain. Fortunately, this behavior seems harmless,
2263 * since the resulting DACL will still be "null" --- but it will be
2264 * "the other representation of null".
2266 * - The above also applies to SACL_SECURITY_INFORMATION and
2267 * SE_SACL_PRESENT. Again, it's seemingly unavoidable but "harmless"
2268 * that Windows changes the representation of a "null SACL".
2270 if (likely(desc_size <= STACK_MAX)) {
2271 desc = alloca(desc_size);
2273 desc = MALLOC(desc_size);
2275 return STATUS_NO_MEMORY;
2278 memcpy(desc, _desc, desc_size);
2280 if (likely(desc_size >= 4)) {
2282 if (desc->Control & SE_DACL_AUTO_INHERITED)
2283 desc->Control |= SE_DACL_AUTO_INHERIT_REQ;
2285 if (desc->Control & SE_SACL_AUTO_INHERITED)
2286 desc->Control |= SE_SACL_AUTO_INHERIT_REQ;
2290 * More API insanity. We want to set the entire security descriptor
2291 * as-is. But all available APIs require specifying the specific parts
2292 * of the security descriptor being set. Especially annoying is that
2293 * mandatory integrity labels are part of the SACL, but they aren't set
2294 * with SACL_SECURITY_INFORMATION. Instead, applications must also
2295 * specify LABEL_SECURITY_INFORMATION (Windows Vista, Windows 7) or
2296 * BACKUP_SECURITY_INFORMATION (Windows 8). But at least older versions
2297 * of Windows don't error out if you provide these newer flags...
2299 * Also, if the process isn't running as Administrator, then it probably
2300 * doesn't have SE_RESTORE_PRIVILEGE. In this case, it will always get
2301 * the STATUS_PRIVILEGE_NOT_HELD error by trying to set the SACL, even
2302 * if the security descriptor it provided did not have a SACL. By
2303 * default, in this case we try to recover and set as much of the
2304 * security descriptor as possible --- potentially excluding the DACL, and
2305 * even the owner, as well as the SACL.
2308 info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
2309 DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION |
2310 LABEL_SECURITY_INFORMATION | BACKUP_SECURITY_INFORMATION;
2314 * It's also worth noting that SetFileSecurity() is unusable because it
2315 * doesn't request "backup semantics" when it opens the file internally.
2316 * NtSetSecurityObject() seems to be the best function to use in backup
2317 * applications. (SetSecurityInfo() should also work, but it's harder
2318 * to use and must call NtSetSecurityObject() internally anyway.
2319 * BackupWrite() is theoretically usable as well, but it's inflexible
2320 * and poorly documented.)
2324 status = (*func_NtSetSecurityObject)(h, info, desc);
2325 if (NT_SUCCESS(status))
2326 goto out_maybe_free_desc;
2328 /* Failed to set the requested parts of the security descriptor. If the
2329 * error was permissions-related, try to set fewer parts of the security
2330 * descriptor, unless WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled. */
2331 if ((status == STATUS_PRIVILEGE_NOT_HELD ||
2332 status == STATUS_ACCESS_DENIED) &&
2333 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2335 if (info & SACL_SECURITY_INFORMATION) {
2336 info &= ~(SACL_SECURITY_INFORMATION |
2337 LABEL_SECURITY_INFORMATION |
2338 BACKUP_SECURITY_INFORMATION);
2339 ctx->partial_security_descriptors++;
2342 if (info & DACL_SECURITY_INFORMATION) {
2343 info &= ~DACL_SECURITY_INFORMATION;
2346 if (info & OWNER_SECURITY_INFORMATION) {
2347 info &= ~OWNER_SECURITY_INFORMATION;
2350 /* Nothing left except GROUP, and if we removed it we
2351 * wouldn't have anything at all. */
2354 /* No part of the security descriptor could be set, or
2355 * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled and the full security
2356 * descriptor could not be set. */
2357 if (!(info & SACL_SECURITY_INFORMATION))
2358 ctx->partial_security_descriptors--;
2359 ctx->no_security_descriptors++;
2361 out_maybe_free_desc:
2362 if (unlikely(desc_size > STACK_MAX))
2367 /* Set metadata on the open file @h from the WIM inode @inode. */
2369 do_apply_metadata_to_file(HANDLE h, const struct wim_inode *inode,
2370 struct win32_apply_ctx *ctx)
2372 FILE_BASIC_INFORMATION info;
2375 /* Set security descriptor if present and not in NO_ACLS mode */
2376 if (inode->i_security_id >= 0 &&
2377 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
2379 const struct wim_security_data *sd;
2383 sd = wim_get_current_security_data(ctx->common.wim);
2384 desc = sd->descriptors[inode->i_security_id];
2385 desc_size = sd->sizes[inode->i_security_id];
2387 status = set_security_descriptor(h, desc, desc_size, ctx);
2388 if (!NT_SUCCESS(status) &&
2389 (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2391 set_errno_from_nt_status(status);
2392 ERROR_WITH_ERRNO("Can't set security descriptor "
2393 "on \"%ls\" (status=0x%08"PRIx32")",
2394 current_path(ctx), (u32)status);
2395 return WIMLIB_ERR_SET_SECURITY;
2399 /* Set attributes and timestamps */
2400 info.CreationTime.QuadPart = inode->i_creation_time;
2401 info.LastAccessTime.QuadPart = inode->i_last_access_time;
2402 info.LastWriteTime.QuadPart = inode->i_last_write_time;
2403 info.ChangeTime.QuadPart = 0;
2404 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
2405 info.FileAttributes = 0;
2407 info.FileAttributes = inode->i_attributes & ~SPECIAL_ATTRIBUTES;
2409 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
2410 &info, sizeof(info),
2411 FileBasicInformation);
2412 /* On FAT volumes we get STATUS_INVALID_PARAMETER if we try to set
2413 * attributes on the root directory. (Apparently because FAT doesn't
2414 * actually have a place to store those attributes!) */
2415 if (!NT_SUCCESS(status)
2416 && !(status == STATUS_INVALID_PARAMETER &&
2417 dentry_is_root(inode_first_extraction_dentry(inode))))
2419 set_errno_from_nt_status(status);
2420 ERROR_WITH_ERRNO("Can't set basic metadata on \"%ls\" "
2421 "(status=0x%08"PRIx32")",
2422 current_path(ctx), (u32)status);
2423 return WIMLIB_ERR_SET_ATTRIBUTES;
2430 apply_metadata_to_file(const struct wim_dentry *dentry,
2431 struct win32_apply_ctx *ctx)
2433 const struct wim_inode *inode = dentry->d_inode;
2439 perms = FILE_WRITE_ATTRIBUTES | WRITE_DAC |
2440 WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
2442 build_extraction_path(dentry, ctx);
2444 /* Open a handle with as many relevant permissions as possible. */
2445 while (!NT_SUCCESS(status = do_create_file(&h, perms, NULL,
2446 0, FILE_OPEN, 0, ctx)))
2448 if (status == STATUS_PRIVILEGE_NOT_HELD ||
2449 status == STATUS_ACCESS_DENIED)
2451 if (perms & ACCESS_SYSTEM_SECURITY) {
2452 perms &= ~ACCESS_SYSTEM_SECURITY;
2455 if (perms & WRITE_DAC) {
2456 perms &= ~WRITE_DAC;
2459 if (perms & WRITE_OWNER) {
2460 perms &= ~WRITE_OWNER;
2464 set_errno_from_nt_status(status);
2465 ERROR_WITH_ERRNO("Can't open \"%ls\" to set metadata "
2466 "(status=0x%08"PRIx32")",
2467 current_path(ctx), (u32)status);
2468 return WIMLIB_ERR_OPEN;
2471 ret = do_apply_metadata_to_file(h, inode, ctx);
2479 apply_metadata(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
2481 const struct wim_dentry *dentry;
2484 /* We go in reverse so that metadata is set on all a directory's
2485 * children before the directory itself. This avoids any potential
2486 * problems with attributes, timestamps, or security descriptors. */
2487 list_for_each_entry_reverse(dentry, dentry_list, d_extraction_list_node)
2489 ret = apply_metadata_to_file(dentry, ctx);
2490 ret = check_apply_error(dentry, ctx, ret);
2493 ret = report_file_metadata_applied(&ctx->common);
2500 /* Issue warnings about problems during the extraction for which warnings were
2501 * not already issued (due to the high number of potential warnings if we issued
2502 * them per-file). */
2504 do_warnings(const struct win32_apply_ctx *ctx)
2506 if (ctx->partial_security_descriptors == 0
2507 && ctx->no_security_descriptors == 0
2508 && ctx->num_set_short_name_failures == 0
2510 && ctx->num_remove_short_name_failures == 0
2515 WARNING("Extraction to \"%ls\" complete, but with one or more warnings:",
2516 ctx->common.target);
2517 if (ctx->num_set_short_name_failures) {
2518 WARNING("- Could not set short names on %lu files or directories",
2519 ctx->num_set_short_name_failures);
2522 if (ctx->num_remove_short_name_failures) {
2523 WARNING("- Could not remove short names on %lu files or directories"
2524 " (This is expected on Vista and earlier)",
2525 ctx->num_remove_short_name_failures);
2528 if (ctx->partial_security_descriptors) {
2529 WARNING("- Could only partially set the security descriptor\n"
2530 " on %lu files or directories.",
2531 ctx->partial_security_descriptors);
2533 if (ctx->no_security_descriptors) {
2534 WARNING("- Could not set security descriptor at all\n"
2535 " on %lu files or directories.",
2536 ctx->no_security_descriptors);
2538 if (ctx->partial_security_descriptors || ctx->no_security_descriptors) {
2539 WARNING("To fully restore all security descriptors, run the program\n"
2540 " with Administrator rights.");
2545 count_dentries(const struct list_head *dentry_list)
2547 const struct list_head *cur;
2550 list_for_each(cur, dentry_list)
2556 /* Extract files from a WIM image to a directory on Windows */
2558 win32_extract(struct list_head *dentry_list, struct apply_ctx *_ctx)
2561 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
2562 uint64_t dentry_count;
2564 ret = prepare_target(dentry_list, ctx);
2568 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
2569 ret = start_wimboot_extraction(ctx);
2574 dentry_count = count_dentries(dentry_list);
2576 ret = start_file_structure_phase(&ctx->common, dentry_count);
2580 ret = create_directories(dentry_list, ctx);
2584 ret = create_nondirectories(dentry_list, ctx);
2588 ret = end_file_structure_phase(&ctx->common);
2592 struct read_stream_list_callbacks cbs = {
2593 .begin_stream = begin_extract_stream,
2594 .begin_stream_ctx = ctx,
2595 .consume_chunk = extract_chunk,
2596 .consume_chunk_ctx = ctx,
2597 .end_stream = end_extract_stream,
2598 .end_stream_ctx = ctx,
2600 ret = extract_stream_list(&ctx->common, &cbs);
2604 ret = start_file_metadata_phase(&ctx->common, dentry_count);
2608 ret = apply_metadata(dentry_list, ctx);
2612 ret = end_file_metadata_phase(&ctx->common);
2616 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
2617 ret = end_wimboot_extraction(ctx);
2625 (*func_NtClose)(ctx->h_target);
2626 if (ctx->target_ntpath.Buffer)
2627 HeapFree(GetProcessHeap(), 0, ctx->target_ntpath.Buffer);
2628 FREE(ctx->pathbuf.Buffer);
2629 FREE(ctx->print_buffer);
2630 if (ctx->wimboot.prepopulate_pats) {
2631 FREE(ctx->wimboot.prepopulate_pats->strings);
2632 FREE(ctx->wimboot.prepopulate_pats);
2634 FREE(ctx->wimboot.mem_prepopulate_pats);
2635 FREE(ctx->data_buffer);
2639 const struct apply_operations win32_apply_ops = {
2641 .get_supported_features = win32_get_supported_features,
2642 .extract = win32_extract,
2643 .will_externally_back = win32_will_externally_back,
2644 .context_size = sizeof(struct win32_apply_ctx),
2647 #endif /* __WIN32__ */