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 part of wimlib, a library for working with WIM files.
10 * wimlib is free software; you can redistribute it and/or modify it under the
11 * terms of the GNU General Public License as published by the Free
12 * Software Foundation; either version 3 of the License, or (at your option)
15 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 * A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with wimlib; if not, see http://www.gnu.org/licenses/.
30 #include "wimlib/win32_common.h"
32 #include "wimlib/apply.h"
33 #include "wimlib/capture.h" /* for mangle_pat() and match_pattern_list() */
34 #include "wimlib/dentry.h"
35 #include "wimlib/error.h"
36 #include "wimlib/lookup_table.h"
37 #include "wimlib/metadata.h"
38 #include "wimlib/reparse.h"
39 #include "wimlib/textfile.h"
40 #include "wimlib/xml.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];
58 /* Open handle to the target directory */
61 /* NT namespace path to the target directory (buffer allocated) */
62 UNICODE_STRING target_ntpath;
64 /* Temporary buffer for building paths (buffer allocated) */
65 UNICODE_STRING pathbuf;
67 /* Object attributes to reuse for opening files in the target directory.
68 * (attr.ObjectName == &pathbuf) and (attr.RootDirectory == h_target).
70 OBJECT_ATTRIBUTES attr;
72 /* Temporary I/O status block for system calls */
75 /* Allocated buffer for creating "printable" paths from our
76 * target-relative NT paths */
77 wchar_t *print_buffer;
79 /* Allocated buffer for reading stream data when it cannot be extracted
83 /* Pointer to the next byte in @data_buffer to fill */
86 /* Size allocated in @data_buffer */
87 size_t data_buffer_size;
89 /* Current offset in the raw encrypted file being written */
90 size_t encrypted_offset;
92 /* Current size of the raw encrypted file being written */
93 size_t encrypted_size;
95 /* Temporary buffer for reparse data */
96 struct reparse_buffer_disk rpbuf;
98 /* Temporary buffer for reparse data of "fixed" absolute symbolic links
100 struct reparse_buffer_disk rpfixbuf;
102 /* Array of open handles to filesystem streams currently being written
104 HANDLE open_handles[MAX_OPEN_STREAMS];
106 /* Number of handles in @open_handles currently open (filled in from the
107 * beginning of the array) */
108 unsigned num_open_handles;
110 /* List of dentries, joined by @tmp_list, that need to have reparse data
111 * extracted as soon as the whole stream has been read into
113 struct list_head reparse_dentries;
115 /* List of dentries, joined by @tmp_list, that need to have raw
116 * encrypted data extracted as soon as the whole stream has been read
117 * into @data_buffer. */
118 struct list_head encrypted_dentries;
120 /* Number of files for which we didn't have permission to set the full
121 * security descriptor. */
122 unsigned long partial_security_descriptors;
124 /* Number of files for which we didn't have permission to set any part
125 * of the security descriptor. */
126 unsigned long no_security_descriptors;
128 /* Number of files for which we couldn't set the short name. */
129 unsigned long num_short_name_failures;
131 /* Have we tried to enable short name support on the target volume yet?
133 bool tried_to_enable_short_names;
136 /* Get the drive letter from a Windows path, or return the null character if the
137 * path is relative. */
139 get_drive_letter(const wchar_t *path)
141 /* Skip \\?\ prefix */
142 if (!wcsncmp(path, L"\\\\?\\", 4))
145 /* Return drive letter if valid */
146 if (((path[0] >= L'a' && path[0] <= L'z') ||
147 (path[0] >= L'A' && path[0] <= L'Z')) && path[1] == L':')
154 get_vol_flags(const wchar_t *target, DWORD *vol_flags_ret,
155 bool *short_names_supported_ret)
157 wchar_t filesystem_name[MAX_PATH + 1];
159 wchar_t *volume = NULL;
162 *short_names_supported_ret = false;
164 drive[0] = get_drive_letter(target);
172 if (!GetVolumeInformation(volume, NULL, 0, NULL, NULL,
173 vol_flags_ret, filesystem_name,
174 ARRAY_LEN(filesystem_name)))
176 DWORD err = GetLastError();
177 set_errno_from_win32_error(err);
178 WARNING_WITH_ERRNO("Failed to get volume information for "
179 "\"%ls\" (err=%"PRIu32")",
184 if (wcsstr(filesystem_name, L"NTFS")) {
185 /* FILE_SUPPORTS_HARD_LINKS is only supported on Windows 7 and
186 * later. Force it on anyway if filesystem is NTFS. */
187 *vol_flags_ret |= FILE_SUPPORTS_HARD_LINKS;
189 /* There's no volume flag for short names, but according to the
190 * MS documentation they are only user-settable on NTFS. */
191 *short_names_supported_ret = true;
196 win32_get_supported_features(const wchar_t *target,
197 struct wim_features *supported_features)
200 bool short_names_supported;
202 /* Query the features of the target volume. */
204 get_vol_flags(target, &vol_flags, &short_names_supported);
206 supported_features->archive_files = 1;
207 supported_features->hidden_files = 1;
208 supported_features->system_files = 1;
210 if (vol_flags & FILE_FILE_COMPRESSION)
211 supported_features->compressed_files = 1;
213 if (vol_flags & FILE_SUPPORTS_ENCRYPTION) {
214 supported_features->encrypted_files = 1;
215 supported_features->encrypted_directories = 1;
218 supported_features->not_context_indexed_files = 1;
220 /* Don't do anything with FILE_SUPPORTS_SPARSE_FILES. */
222 if (vol_flags & FILE_NAMED_STREAMS)
223 supported_features->named_data_streams = 1;
225 if (vol_flags & FILE_SUPPORTS_HARD_LINKS)
226 supported_features->hard_links = 1;
228 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS)
229 supported_features->reparse_points = 1;
231 if (vol_flags & FILE_PERSISTENT_ACLS)
232 supported_features->security_descriptors = 1;
234 if (short_names_supported)
235 supported_features->short_names = 1;
237 supported_features->timestamps = 1;
239 /* Note: Windows does not support case sensitive filenames! At least
240 * not without changing the registry and rebooting... */
245 /* Load the patterns from [PrepopulateList] of WimBootCompress.ini in the WIM
246 * image being extracted. */
248 load_prepopulate_pats(struct win32_apply_ctx *ctx)
250 const wchar_t *path = L"\\Windows\\System32\\WimBootCompress.ini";
251 struct wim_dentry *dentry;
252 struct wim_lookup_table_entry *lte;
255 struct string_set *s;
257 struct text_file_section sec;
259 dentry = get_dentry(ctx->common.wim, path, WIMLIB_CASE_INSENSITIVE);
261 (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
262 FILE_ATTRIBUTE_REPARSE_POINT |
263 FILE_ATTRIBUTE_ENCRYPTED)) ||
264 !(lte = inode_unnamed_lte(dentry->d_inode, ctx->common.wim->lookup_table)))
266 WARNING("%ls does not exist in WIM image!", path);
267 return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
270 ret = read_full_stream_into_alloc_buf(lte, &buf);
274 s = CALLOC(1, sizeof(struct string_set));
277 return WIMLIB_ERR_NOMEM;
280 sec.name = T("PrepopulateList");
283 ret = do_load_text_file(path, buf, lte->size, &mem, &sec, 1,
284 LOAD_TEXT_FILE_REMOVE_QUOTES |
285 LOAD_TEXT_FILE_NO_WARNINGS,
287 BUILD_BUG_ON(OS_PREFERRED_PATH_SEPARATOR != WIM_PATH_SEPARATOR);
293 ctx->wimboot.prepopulate_pats = s;
294 ctx->wimboot.mem_prepopulate_pats = mem;
298 /* Returns %true if the path to @dentry matches a pattern in [PrepopulateList]
299 * of WimBootCompress.ini. Otherwise returns %false.
301 * @dentry must have had its full path calculated. */
303 in_prepopulate_list(struct wim_dentry *dentry,
304 const struct win32_apply_ctx *ctx)
306 const struct string_set *pats = ctx->wimboot.prepopulate_pats;
308 if (!pats || !pats->num_strings)
311 return match_pattern_list(dentry->_full_path,
312 wcslen(dentry->_full_path), pats);
315 /* Calculates the SHA-1 message digest of the WIM's lookup table. */
317 hash_lookup_table(WIMStruct *wim, u8 hash[SHA1_HASH_SIZE])
319 return wim_reshdr_to_hash(&wim->hdr.lookup_table_reshdr, wim, hash);
322 /* Prepare for doing a "WIMBoot" extraction by loading patterns from
323 * [PrepopulateList] of WimBootCompress.ini and allocating a WOF data source ID
324 * on the target volume. */
326 start_wimboot_extraction(struct win32_apply_ctx *ctx)
329 WIMStruct *wim = ctx->common.wim;
331 ret = load_prepopulate_pats(ctx);
332 if (ret == WIMLIB_ERR_NOMEM)
335 if (!wim_info_get_wimboot(wim->wim_info, wim->current_image))
336 WARNING("Image is not marked as WIMBoot compatible!");
338 ret = hash_lookup_table(ctx->common.wim,
339 ctx->wimboot.wim_lookup_table_hash);
343 return wimboot_alloc_data_source_id(wim->filename,
347 &ctx->wimboot.data_source_id,
348 &ctx->wimboot.wof_running);
352 build_win32_extraction_path(const struct wim_dentry *dentry,
353 struct win32_apply_ctx *ctx);
355 /* Sets WimBoot=1 in the extracted SYSTEM registry hive.
357 * WIMGAPI does this, and it's possible that it's important.
358 * But I don't know exactly what this value means to Windows. */
360 end_wimboot_extraction(struct win32_apply_ctx *ctx)
362 struct wim_dentry *dentry;
363 wchar_t subkeyname[32];
369 dentry = get_dentry(ctx->common.wim, L"\\Windows\\System32\\config\\SYSTEM",
370 WIMLIB_CASE_INSENSITIVE);
372 if (!dentry || !will_extract_dentry(dentry))
375 if (!will_extract_dentry(wim_get_current_root_dentry(ctx->common.wim)))
378 /* Not bothering to use the native routines (e.g. NtLoadKey()) for this.
379 * If this doesn't work, you probably also have many other problems. */
381 build_win32_extraction_path(dentry, ctx);
383 randomize_char_array_with_alnum(subkeyname, 20);
384 subkeyname[20] = L'\0';
386 res = RegLoadKey(HKEY_LOCAL_MACHINE, subkeyname, ctx->pathbuf.Buffer);
390 wcscpy(&subkeyname[20], L"\\Setup");
392 res = RegCreateKeyEx(HKEY_LOCAL_MACHINE, subkeyname, 0, NULL,
393 REG_OPTION_BACKUP_RESTORE, 0, NULL, &key, NULL);
399 res = RegSetValueEx(key, L"WimBoot", 0, REG_DWORD,
400 (const BYTE *)&value, sizeof(DWORD));
404 res = RegFlushKey(key);
407 res2 = RegCloseKey(key);
411 subkeyname[20] = L'\0';
412 RegUnLoadKey(HKEY_LOCAL_MACHINE, subkeyname);
416 set_errno_from_win32_error(res);
417 WARNING_WITH_ERRNO("Failed to set \\Setup: dword \"WimBoot\"=1 value "
418 "in registry hive \"%ls\" (err=%"PRIu32")",
419 ctx->pathbuf.Buffer, (u32)res);
425 /* Returns the number of wide characters needed to represent the path to the
426 * specified @dentry, relative to the target directory, when extracted.
428 * Does not include null terminator (not needed for NtCreateFile). */
430 dentry_extraction_path_length(const struct wim_dentry *dentry)
433 const struct wim_dentry *d;
437 len += d->d_extraction_name_nchars + 1;
439 } while (!dentry_is_root(d) && will_extract_dentry(d));
441 return --len; /* No leading slash */
444 /* Returns the length of the longest string that might need to be appended to
445 * the path to an alias of an inode to open or create a named data stream.
447 * If the inode has no named data streams, this will be 0. Otherwise, this will
448 * be 1 plus the length of the longest-named data stream, since the data stream
449 * name must be separated from the path by the ':' character. */
451 inode_longest_named_data_stream_spec(const struct wim_inode *inode)
454 for (u16 i = 0; i < inode->i_num_ads; i++) {
455 size_t len = inode->i_ads_entries[i].stream_name_nbytes;
460 max = 1 + (max / sizeof(wchar_t));
464 /* Find the length, in wide characters, of the longest path needed for
465 * extraction of any file in @dentry_list relative to the target directory.
467 * Accounts for named data streams, but does not include null terminator (not
468 * needed for NtCreateFile). */
470 compute_path_max(struct list_head *dentry_list)
473 const struct wim_dentry *dentry;
475 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
478 len = dentry_extraction_path_length(dentry);
480 /* Account for named data streams */
481 len += inode_longest_named_data_stream_spec(dentry->d_inode);
490 /* Build the path at which to extract the @dentry, relative to the target
493 * The path is saved in ctx->pathbuf. */
495 build_extraction_path(const struct wim_dentry *dentry,
496 struct win32_apply_ctx *ctx)
500 const struct wim_dentry *d;
502 len = dentry_extraction_path_length(dentry);
504 ctx->pathbuf.Length = len * sizeof(wchar_t);
505 p = ctx->pathbuf.Buffer + len;
507 !dentry_is_root(d->d_parent) && will_extract_dentry(d->d_parent);
510 p -= d->d_extraction_name_nchars;
511 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
514 /* No leading slash */
515 p -= d->d_extraction_name_nchars;
516 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
519 /* Build the path at which to extract the @dentry, relative to the target
520 * directory, adding the suffix for a named data stream.
522 * The path is saved in ctx->pathbuf. */
524 build_extraction_path_with_ads(const struct wim_dentry *dentry,
525 struct win32_apply_ctx *ctx,
526 const wchar_t *stream_name,
527 size_t stream_name_nchars)
531 build_extraction_path(dentry, ctx);
533 /* Add :NAME for named data stream */
534 p = ctx->pathbuf.Buffer + (ctx->pathbuf.Length / sizeof(wchar_t));
536 wmemcpy(p, stream_name, stream_name_nchars);
537 ctx->pathbuf.Length += (1 + stream_name_nchars) * sizeof(wchar_t);
540 /* Build the Win32 namespace path to the specified @dentry when extracted.
542 * The path is saved in ctx->pathbuf and will be null terminated.
544 * XXX: We could get rid of this if it wasn't needed for the file encryption
545 * APIs, and the registry manipulation in WIMBoot mode. */
547 build_win32_extraction_path(const struct wim_dentry *dentry,
548 struct win32_apply_ctx *ctx)
550 build_extraction_path(dentry, ctx);
552 /* Prepend target_ntpath to our relative path, then change \??\ into \\?\ */
554 memmove(ctx->pathbuf.Buffer +
555 (ctx->target_ntpath.Length / sizeof(wchar_t)) + 1,
556 ctx->pathbuf.Buffer, ctx->pathbuf.Length);
557 memcpy(ctx->pathbuf.Buffer, ctx->target_ntpath.Buffer,
558 ctx->target_ntpath.Length);
559 ctx->pathbuf.Buffer[ctx->target_ntpath.Length / sizeof(wchar_t)] = L'\\';
560 ctx->pathbuf.Length += ctx->target_ntpath.Length + sizeof(wchar_t);
561 ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)] = L'\0';
563 wimlib_assert(ctx->pathbuf.Length >= 4 * sizeof(wchar_t) &&
564 !wmemcmp(ctx->pathbuf.Buffer, L"\\??\\", 4));
566 ctx->pathbuf.Buffer[1] = L'\\';
570 /* Returns a "printable" representation of the last relative NT path that was
571 * constructed with build_extraction_path() or build_extraction_path_with_ads().
573 * This will be overwritten by the next call to this function. */
574 static const wchar_t *
575 current_path(struct win32_apply_ctx *ctx)
577 wchar_t *p = ctx->print_buffer;
579 p = wmempcpy(p, ctx->common.target, ctx->common.target_nchars);
581 p = wmempcpy(p, ctx->pathbuf.Buffer, ctx->pathbuf.Length / sizeof(wchar_t));
583 return ctx->print_buffer;
587 * Ensures the target directory exists and opens a handle to it, in preparation
588 * of using paths relative to it.
591 prepare_target(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
597 /* Open handle to the target directory (possibly creating it). */
599 ret = win32_path_to_nt_path(ctx->common.target, &ctx->target_ntpath);
603 ctx->attr.Length = sizeof(ctx->attr);
604 ctx->attr.ObjectName = &ctx->target_ntpath;
606 status = (*func_NtCreateFile)(&ctx->h_target,
612 FILE_SHARE_VALID_FLAGS,
614 FILE_DIRECTORY_FILE |
615 FILE_OPEN_REPARSE_POINT |
616 FILE_OPEN_FOR_BACKUP_INTENT,
620 if (!NT_SUCCESS(status)) {
621 set_errno_from_nt_status(status);
622 ERROR_WITH_ERRNO("Can't open or create directory \"%ls\" "
623 "(status=0x%08"PRIx32")",
624 ctx->common.target, (u32)status);
625 return WIMLIB_ERR_OPENDIR;
628 path_max = compute_path_max(dentry_list);
630 /* Add some extra for building Win32 paths for the file encryption APIs
632 path_max += 2 + (ctx->target_ntpath.Length / sizeof(wchar_t));
634 ctx->pathbuf.MaximumLength = path_max * sizeof(wchar_t);
635 ctx->pathbuf.Buffer = MALLOC(ctx->pathbuf.MaximumLength);
636 if (!ctx->pathbuf.Buffer)
637 return WIMLIB_ERR_NOMEM;
639 ctx->attr.RootDirectory = ctx->h_target;
640 ctx->attr.ObjectName = &ctx->pathbuf;
642 ctx->print_buffer = MALLOC((ctx->common.target_nchars + 1 + path_max + 1) *
644 if (!ctx->print_buffer)
645 return WIMLIB_ERR_NOMEM;
650 /* When creating an inode that will have a short (DOS) name, we create it using
651 * the long name associated with the short name. This ensures that the short
652 * name gets associated with the correct long name. */
653 static const struct wim_dentry *
654 first_extraction_alias(const struct wim_inode *inode)
656 const struct list_head *next = inode->i_extraction_aliases.next;
657 const struct wim_dentry *dentry;
660 dentry = list_entry(next, struct wim_dentry,
661 d_extraction_alias_node);
662 if (dentry_has_short_name(dentry))
665 } while (next != &inode->i_extraction_aliases);
670 * Set or clear FILE_ATTRIBUTE_COMPRESSED if the inherited value is different
671 * from the desired value.
673 * Note that you can NOT override the inherited value of
674 * FILE_ATTRIBUTE_COMPRESSED directly with NtCreateFile().
677 adjust_compression_attribute(HANDLE h, const struct wim_dentry *dentry,
678 struct win32_apply_ctx *ctx)
680 const bool compressed = (dentry->d_inode->i_attributes &
681 FILE_ATTRIBUTE_COMPRESSED);
683 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
686 if (!ctx->common.supported_features.compressed_files)
689 FILE_BASIC_INFORMATION info;
691 USHORT compression_state;
693 /* Get current attributes */
694 status = (*func_NtQueryInformationFile)(h, &ctx->iosb,
696 FileBasicInformation);
697 if (NT_SUCCESS(status) &&
698 compressed == !!(info.FileAttributes & FILE_ATTRIBUTE_COMPRESSED))
700 /* Nothing needs to be done. */
704 /* Set the new compression state */
707 compression_state = COMPRESSION_FORMAT_DEFAULT;
709 compression_state = COMPRESSION_FORMAT_NONE;
711 status = (*func_NtFsControlFile)(h,
716 FSCTL_SET_COMPRESSION,
721 if (NT_SUCCESS(status))
724 set_errno_from_nt_status(status);
725 ERROR_WITH_ERRNO("Can't %s compression attribute on \"%ls\" "
726 "(status=0x%08"PRIx32")",
727 (compressed ? "set" : "clear"),
728 current_path(ctx), status);
729 return WIMLIB_ERR_SET_ATTRIBUTES;
733 * Clear FILE_ATTRIBUTE_ENCRYPTED if the file or directory is not supposed to be
736 * You can provide FILE_ATTRIBUTE_ENCRYPTED to NtCreateFile() to set it on the
737 * created file. However, the file or directory will otherwise default to the
738 * encryption state of the parent directory. This function works around this
739 * limitation by using DecryptFile() to remove FILE_ATTRIBUTE_ENCRYPTED on files
740 * (and directories) that are not supposed to have it set.
742 * Regardless of whether it succeeds or fails, this function may close the
743 * handle to the file. If it does, it sets it to NULL.
746 maybe_clear_encryption_attribute(HANDLE *h_ptr, const struct wim_dentry *dentry,
747 struct win32_apply_ctx *ctx)
749 if (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)
752 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
755 if (!ctx->common.supported_features.encrypted_files)
758 FILE_BASIC_INFORMATION info;
762 /* Get current attributes */
763 status = (*func_NtQueryInformationFile)(*h_ptr, &ctx->iosb,
765 FileBasicInformation);
766 if (NT_SUCCESS(status) &&
767 !(info.FileAttributes & FILE_ATTRIBUTE_ENCRYPTED))
769 /* Nothing needs to be done. */
773 /* Set the new encryption state */
775 /* Due to Windows' crappy file encryption APIs, we need to close the
776 * handle to the file so we don't get ERROR_SHARING_VIOLATION. We also
777 * hack together a Win32 path, although we will use the \\?\ prefix so
778 * it will actually be a NT path in disguise... */
779 (*func_NtClose)(*h_ptr);
782 build_win32_extraction_path(dentry, ctx);
784 bret = DecryptFile(ctx->pathbuf.Buffer, 0);
786 /* Restore the NT namespace path */
787 build_extraction_path(dentry, ctx);
790 DWORD err = GetLastError();
791 set_errno_from_win32_error(err);
792 ERROR_WITH_ERRNO("Can't decrypt file \"%ls\" (err=%"PRIu32")",
793 current_path(ctx), (u32)err);
794 return WIMLIB_ERR_SET_ATTRIBUTES;
799 /* Try to enable short name support on the target volume. If successful, return
800 * true. If unsuccessful, issue a warning and return false. */
802 try_to_enable_short_names(struct win32_apply_ctx *ctx)
804 FILE_FS_PERSISTENT_VOLUME_INFORMATION info;
807 info.VolumeFlags = 0;
808 info.FlagMask = PERSISTENT_VOLUME_STATE_SHORT_NAME_CREATION_DISABLED;
812 status = (*func_NtFsControlFile)(ctx->h_target, NULL, NULL, NULL,
814 FSCTL_SET_PERSISTENT_VOLUME_STATE,
815 &info, sizeof(info), NULL, 0);
816 if (!NT_SUCCESS(status)) {
817 WARNING("Failed to enable short name support on target volume "
818 "(status=0x%08"PRIx32")", (u32)status);
825 /* Set the short name on the open file @h which has been created at the location
826 * indicated by @dentry.
828 * Note that this may add, change, or remove the short name.
830 * @h must be opened with DELETE access.
832 * Returns 0 or WIMLIB_ERR_SET_SHORT_NAME. The latter only happens in
833 * STRICT_SHORT_NAMES mode.
836 set_short_name(HANDLE h, const struct wim_dentry *dentry,
837 struct win32_apply_ctx *ctx)
840 if (!ctx->common.supported_features.short_names)
843 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
844 dentry->short_name_nbytes;
845 u8 buf[bufsize] _aligned_attribute(8);
846 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
849 info->FileNameLength = dentry->short_name_nbytes;
850 memcpy(info->FileName, dentry->short_name, dentry->short_name_nbytes);
854 status = (*func_NtSetInformationFile)(h, &ctx->iosb, info, bufsize,
855 FileShortNameInformation);
856 if (NT_SUCCESS(status))
859 if (status == STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME) {
860 if (dentry->short_name_nbytes == 0)
862 if (!ctx->tried_to_enable_short_names) {
863 ctx->tried_to_enable_short_names = true;
864 if (try_to_enable_short_names(ctx))
869 /* By default, failure to set short names is not an error (since short
870 * names aren't too important anymore...). */
871 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES)) {
872 ctx->num_short_name_failures++;
876 if (status == STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME) {
877 ERROR("Can't set short name when short "
878 "names are not enabled on the volume!");
880 ERROR("Can't set short name on \"%ls\" (status=0x%08"PRIx32")",
881 current_path(ctx), (u32)status);
883 return WIMLIB_ERR_SET_SHORT_NAME;
887 * A wrapper around NtCreateFile() to make it slightly more usable...
888 * This uses the path currently constructed in ctx->pathbuf.
890 * Also, we always specify FILE_OPEN_FOR_BACKUP_INTENT and
891 * FILE_OPEN_REPARSE_POINT.
894 do_create_file(PHANDLE FileHandle,
895 ACCESS_MASK DesiredAccess,
896 PLARGE_INTEGER AllocationSize,
897 ULONG FileAttributes,
898 ULONG CreateDisposition,
900 struct win32_apply_ctx *ctx)
902 return (*func_NtCreateFile)(FileHandle,
908 FILE_SHARE_VALID_FLAGS,
911 FILE_OPEN_FOR_BACKUP_INTENT |
912 FILE_OPEN_REPARSE_POINT,
917 /* Like do_create_file(), but builds the extraction path of the @dentry first.
920 create_file(PHANDLE FileHandle,
921 ACCESS_MASK DesiredAccess,
922 PLARGE_INTEGER AllocationSize,
923 ULONG FileAttributes,
924 ULONG CreateDisposition,
926 const struct wim_dentry *dentry,
927 struct win32_apply_ctx *ctx)
929 build_extraction_path(dentry, ctx);
930 return do_create_file(FileHandle,
939 /* Create empty named data streams.
941 * Since these won't have 'struct wim_lookup_table_entry's, they won't show up
942 * in the call to extract_stream_list(). Hence the need for the special case.
945 create_any_empty_ads(const struct wim_dentry *dentry,
946 struct win32_apply_ctx *ctx)
948 const struct wim_inode *inode = dentry->d_inode;
949 LARGE_INTEGER allocation_size;
950 bool path_modified = false;
953 if (!ctx->common.supported_features.named_data_streams)
956 for (u16 i = 0; i < inode->i_num_ads; i++) {
957 const struct wim_ads_entry *entry;
961 entry = &inode->i_ads_entries[i];
964 if (!entry->stream_name_nbytes)
971 /* Probably setting the allocation size to 0 has no effect, but
972 * we might as well try. */
973 allocation_size.QuadPart = 0;
975 build_extraction_path_with_ads(dentry, ctx,
977 entry->stream_name_nbytes /
979 path_modified = true;
980 status = do_create_file(&h, FILE_WRITE_DATA, &allocation_size,
981 0, FILE_SUPERSEDE, 0, ctx);
982 if (!NT_SUCCESS(status)) {
983 set_errno_from_nt_status(status);
984 ERROR_WITH_ERRNO("Can't create \"%ls\" "
985 "(status=0x%08"PRIx32")",
986 current_path(ctx), (u32)status);
987 ret = WIMLIB_ERR_OPEN;
992 /* Restore the path to the dentry itself */
994 build_extraction_path(dentry, ctx);
999 * Creates the directory named by @dentry, or uses an existing directory at that
1000 * location. If necessary, sets the short name and/or fixes compression and
1001 * encryption attributes.
1003 * Returns 0, WIMLIB_ERR_MKDIR, or WIMLIB_ERR_SET_SHORT_NAME.
1006 create_directory(const struct wim_dentry *dentry,
1007 struct win32_apply_ctx *ctx)
1014 /* Special attributes:
1016 * Use FILE_ATTRIBUTE_ENCRYPTED if the directory needs to have it set.
1017 * This doesn't work for FILE_ATTRIBUTE_COMPRESSED (unfortunately).
1019 * Don't specify FILE_ATTRIBUTE_DIRECTORY; it gets set anyway as a
1020 * result of the FILE_DIRECTORY_FILE option. */
1021 attrib = (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED);
1023 /* DELETE is needed for set_short_name().
1024 * GENERIC_READ and GENERIC_WRITE are needed for
1025 * adjust_compression_attribute(). */
1026 status = create_file(&h, GENERIC_READ | GENERIC_WRITE | DELETE, NULL,
1027 attrib, FILE_OPEN_IF, FILE_DIRECTORY_FILE,
1029 if (!NT_SUCCESS(status)) {
1030 set_errno_from_nt_status(status);
1031 ERROR_WITH_ERRNO("Can't create directory \"%ls\" "
1032 "(status=0x%08"PRIx32")",
1033 current_path(ctx), (u32)status);
1034 return WIMLIB_ERR_MKDIR;
1037 ret = set_short_name(h, dentry, ctx);
1040 ret = adjust_compression_attribute(h, dentry, ctx);
1043 ret = maybe_clear_encryption_attribute(&h, dentry, ctx);
1044 /* May close the handle!!! */
1052 * Create all the directories being extracted, other than the target directory
1055 * Note: we don't honor directory hard links. However, we don't allow them to
1056 * exist in WIM images anyway (see inode_fixup.c).
1059 create_directories(struct list_head *dentry_list,
1060 struct win32_apply_ctx *ctx)
1062 const struct wim_dentry *dentry;
1065 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1067 if (!(dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY))
1070 /* Note: Here we include files with
1071 * FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT, but we
1072 * wait until later to actually set the reparse data. */
1074 /* If the root dentry is being extracted, it was already done so
1075 * in prepare_target(). */
1076 if (dentry_is_root(dentry))
1079 ret = create_directory(dentry, ctx);
1083 ret = create_any_empty_ads(dentry, ctx);
1087 ret = report_file_created(&ctx->common);
1095 * Creates the nondirectory file named by @dentry.
1097 * On success, returns an open handle to the file in @h_ret, with GENERIC_READ,
1098 * GENERIC_WRITE, and DELETE access. Also, the path to the file will be saved
1099 * in ctx->pathbuf. On failure, returns WIMLIB_ERR_OPEN.
1102 create_nondirectory_inode(HANDLE *h_ret, const struct wim_dentry *dentry,
1103 struct win32_apply_ctx *ctx)
1105 const struct wim_inode *inode;
1108 bool retried = false;
1110 inode = dentry->d_inode;
1112 /* If the file already exists and has FILE_ATTRIBUTE_SYSTEM and/or
1113 * FILE_ATTRIBUTE_HIDDEN, these must be specified in order to supersede
1116 * Normally the user shouldn't be trying to overwrite such files anyway,
1117 * but we at least provide FILE_ATTRIBUTE_SYSTEM and
1118 * FILE_ATTRIBUTE_HIDDEN if the WIM inode has those attributes so that
1119 * we catch the case where the user extracts the same files to the same
1120 * location more than one time.
1122 * Also specify FILE_ATTRIBUTE_ENCRYPTED if the file needs to be
1125 * In NO_ATTRIBUTES mode just don't specify any attributes at all.
1127 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES) {
1130 attrib = (inode->i_attributes & (FILE_ATTRIBUTE_SYSTEM |
1131 FILE_ATTRIBUTE_HIDDEN |
1132 FILE_ATTRIBUTE_ENCRYPTED));
1134 build_extraction_path(dentry, ctx);
1136 status = do_create_file(h_ret, GENERIC_READ | GENERIC_WRITE | DELETE,
1137 NULL, attrib, FILE_SUPERSEDE,
1138 FILE_NON_DIRECTORY_FILE, ctx);
1139 if (NT_SUCCESS(status)) {
1142 ret = adjust_compression_attribute(*h_ret, dentry, ctx);
1144 (*func_NtClose)(*h_ret);
1148 ret = maybe_clear_encryption_attribute(h_ret, dentry, ctx);
1149 /* May close the handle!!! */
1153 (*func_NtClose)(*h_ret);
1158 /* Re-open the handle so that we can return it on
1160 status = do_create_file(h_ret,
1162 GENERIC_WRITE | DELETE,
1164 FILE_NON_DIRECTORY_FILE, ctx);
1165 if (!NT_SUCCESS(status))
1169 ret = create_any_empty_ads(dentry, ctx);
1171 (*func_NtClose)(*h_ret);
1177 if (status == STATUS_ACCESS_DENIED && !retried) {
1178 /* We also can't supersede an existing file that has
1179 * FILE_ATTRIBUTE_READONLY set; doing so causes NtCreateFile()
1180 * to return STATUS_ACCESS_DENIED . The only workaround seems
1181 * to be to explicitly remove FILE_ATTRIBUTE_READONLY on the
1182 * existing file, then try again. */
1184 FILE_BASIC_INFORMATION info;
1187 status = do_create_file(&h, FILE_WRITE_ATTRIBUTES, NULL, 0,
1188 FILE_OPEN, FILE_NON_DIRECTORY_FILE, ctx);
1189 if (!NT_SUCCESS(status))
1192 memset(&info, 0, sizeof(info));
1193 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1195 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1196 &info, sizeof(info),
1197 FileBasicInformation);
1199 if (!NT_SUCCESS(status))
1205 set_errno_from_nt_status(status);
1206 ERROR_WITH_ERRNO("Can't create file \"%ls\" (status=0x%08"PRIx32")",
1207 current_path(ctx), (u32)status);
1208 return WIMLIB_ERR_OPEN;
1211 /* Creates a hard link at the location named by @dentry to the file represented
1212 * by the open handle @h. Or, if the target volume does not support hard links,
1213 * create a separate file instead. */
1215 create_link(HANDLE h, const struct wim_dentry *dentry,
1216 struct win32_apply_ctx *ctx)
1218 if (ctx->common.supported_features.hard_links) {
1220 build_extraction_path(dentry, ctx);
1222 size_t bufsize = offsetof(FILE_LINK_INFORMATION, FileName) +
1223 ctx->pathbuf.Length + sizeof(wchar_t);
1224 u8 buf[bufsize] _aligned_attribute(8);
1225 FILE_LINK_INFORMATION *info = (FILE_LINK_INFORMATION *)buf;
1228 info->ReplaceIfExists = TRUE;
1229 info->RootDirectory = ctx->attr.RootDirectory;
1230 info->FileNameLength = ctx->pathbuf.Length;
1231 memcpy(info->FileName, ctx->pathbuf.Buffer, ctx->pathbuf.Length);
1232 info->FileName[info->FileNameLength / 2] = L'\0';
1234 /* Note: the null terminator isn't actually necessary,
1235 * but if you don't add the extra character, you get
1236 * STATUS_INFO_LENGTH_MISMATCH when FileNameLength
1237 * happens to be 2 */
1239 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1241 FileLinkInformation);
1242 if (NT_SUCCESS(status))
1244 ERROR("Failed to create link \"%ls\" (status=0x%08"PRIx32")",
1245 current_path(ctx), (u32)status);
1246 return WIMLIB_ERR_LINK;
1251 ret = create_nondirectory_inode(&h2, dentry, ctx);
1255 (*func_NtClose)(h2);
1260 /* Given an inode (represented by the open handle @h) for which one link has
1261 * been created (named by @first_dentry), create the other links.
1263 * Or, if the target volume does not support hard links, create separate files.
1265 * Note: This uses ctx->pathbuf and does not reset it.
1268 create_links(HANDLE h, const struct wim_dentry *first_dentry,
1269 struct win32_apply_ctx *ctx)
1271 const struct wim_inode *inode;
1272 const struct list_head *next;
1273 const struct wim_dentry *dentry;
1276 inode = first_dentry->d_inode;
1277 next = inode->i_extraction_aliases.next;
1279 dentry = list_entry(next, struct wim_dentry,
1280 d_extraction_alias_node);
1281 if (dentry != first_dentry) {
1282 ret = create_link(h, dentry, ctx);
1287 } while (next != &inode->i_extraction_aliases);
1291 /* Create a nondirectory file, including all links. */
1293 create_nondirectory(const struct wim_inode *inode, struct win32_apply_ctx *ctx)
1295 const struct wim_dentry *first_dentry;
1299 first_dentry = first_extraction_alias(inode);
1301 /* Create first link. */
1302 ret = create_nondirectory_inode(&h, first_dentry, ctx);
1306 /* Set short name. */
1307 ret = set_short_name(h, first_dentry, ctx);
1309 /* Create additional links, OR if hard links are not supported just
1310 * create more files. */
1312 ret = create_links(h, first_dentry, ctx);
1318 /* Create all the nondirectory files being extracted, including all aliases
1321 create_nondirectories(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1323 const struct wim_dentry *dentry;
1324 const struct wim_inode *inode;
1327 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1328 inode = dentry->d_inode;
1329 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1331 /* Call create_nondirectory() only once per inode */
1332 if (dentry != inode_first_extraction_dentry(inode))
1334 ret = create_nondirectory(inode, ctx);
1337 ret = report_file_created(&ctx->common);
1345 close_handles(struct win32_apply_ctx *ctx)
1347 for (unsigned i = 0; i < ctx->num_open_handles; i++)
1348 (*func_NtClose)(ctx->open_handles[i]);
1351 /* Prepare to read the next stream, which has size @stream_size, into an
1352 * in-memory buffer. */
1354 prepare_data_buffer(struct win32_apply_ctx *ctx, u64 stream_size)
1356 if (stream_size > ctx->data_buffer_size) {
1357 /* Larger buffer needed. */
1359 if ((size_t)stream_size != stream_size)
1360 return WIMLIB_ERR_NOMEM;
1361 new_buffer = REALLOC(ctx->data_buffer, stream_size);
1363 return WIMLIB_ERR_NOMEM;
1364 ctx->data_buffer = new_buffer;
1365 ctx->data_buffer_size = stream_size;
1367 /* On the first call this changes data_buffer_ptr from NULL, which tells
1368 * extract_chunk() that the data buffer needs to be filled while reading
1369 * the stream data. */
1370 ctx->data_buffer_ptr = ctx->data_buffer;
1375 begin_extract_stream_instance(const struct wim_lookup_table_entry *stream,
1376 struct wim_dentry *dentry,
1377 const wchar_t *stream_name,
1378 struct win32_apply_ctx *ctx)
1380 const struct wim_inode *inode = dentry->d_inode;
1381 size_t stream_name_nchars = 0;
1382 FILE_ALLOCATION_INFORMATION alloc_info;
1386 if (unlikely(stream_name))
1387 stream_name_nchars = wcslen(stream_name);
1389 if (unlikely(stream_name_nchars)) {
1390 build_extraction_path_with_ads(dentry, ctx,
1391 stream_name, stream_name_nchars);
1393 build_extraction_path(dentry, ctx);
1396 /* Reparse point? */
1397 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1398 && (stream_name_nchars == 0))
1400 if (!ctx->common.supported_features.reparse_points)
1403 /* We can't write the reparse stream directly; we must set it
1404 * with FSCTL_SET_REPARSE_POINT, which requires that all the
1405 * data be available. So, stage the data in a buffer. */
1407 list_add_tail(&dentry->tmp_list, &ctx->reparse_dentries);
1408 return prepare_data_buffer(ctx, stream->size);
1411 /* Encrypted file? */
1412 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)
1413 && (stream_name_nchars == 0))
1415 if (!ctx->common.supported_features.encrypted_files)
1418 /* We can't write encrypted file streams directly; we must use
1419 * WriteEncryptedFileRaw(), which requires providing the data
1420 * through a callback function. This can't easily be combined
1421 * with our own callback-based approach.
1423 * The current workaround is to simply read the stream into
1424 * memory and write the encrypted file from that.
1426 * TODO: This isn't sufficient for extremely large encrypted
1427 * files. Perhaps we should create an extra thread to write
1429 list_add_tail(&dentry->tmp_list, &ctx->encrypted_dentries);
1430 return prepare_data_buffer(ctx, stream->size);
1433 /* Extracting unnamed data stream in WIMBoot mode? */
1434 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)
1435 && (stream_name_nchars == 0)
1436 && (stream->resource_location == RESOURCE_IN_WIM)
1437 && (stream->rspec->wim == ctx->common.wim)
1438 && (stream->size == stream->rspec->uncompressed_size))
1440 int ret = calculate_dentry_full_path(dentry);
1443 if (in_prepopulate_list(dentry, ctx)) {
1444 union wimlib_progress_info info;
1446 info.wimboot_exclude.path_in_wim = dentry->_full_path;
1447 info.wimboot_exclude.extraction_path = current_path(ctx);
1449 ret = call_progress(ctx->common.progfunc,
1450 WIMLIB_PROGRESS_MSG_WIMBOOT_EXCLUDE,
1451 &info, ctx->common.progctx);
1452 FREE(dentry->_full_path);
1453 dentry->_full_path = NULL;
1456 /* Go on and open the file for normal extraction. */
1458 FREE(dentry->_full_path);
1459 dentry->_full_path = NULL;
1460 return wimboot_set_pointer(&ctx->attr,
1463 ctx->wimboot.data_source_id,
1464 ctx->wimboot.wim_lookup_table_hash,
1465 ctx->wimboot.wof_running);
1469 if (ctx->num_open_handles == MAX_OPEN_STREAMS) {
1470 /* XXX: Fix this. But because of the checks in
1471 * extract_stream_list(), this can now only happen on a
1472 * filesystem that does not support hard links. */
1473 ERROR("Can't extract data: too many open files!");
1474 return WIMLIB_ERR_UNSUPPORTED;
1477 /* Open a new handle */
1478 status = do_create_file(&h,
1479 FILE_WRITE_DATA | SYNCHRONIZE,
1480 NULL, 0, FILE_OPEN_IF,
1481 FILE_SEQUENTIAL_ONLY |
1482 FILE_SYNCHRONOUS_IO_NONALERT,
1484 if (!NT_SUCCESS(status)) {
1485 set_errno_from_nt_status(status);
1486 ERROR_WITH_ERRNO("Can't open \"%ls\" for writing "
1487 "(status=0x%08"PRIx32")",
1488 current_path(ctx), (u32)status);
1489 return WIMLIB_ERR_OPEN;
1492 ctx->open_handles[ctx->num_open_handles++] = h;
1494 /* Allocate space for the data. */
1495 alloc_info.AllocationSize.QuadPart = stream->size;
1496 (*func_NtSetInformationFile)(h, &ctx->iosb,
1497 &alloc_info, sizeof(alloc_info),
1498 FileAllocationInformation);
1502 /* Set the reparse data @rpbuf of length @rpbuflen on the extracted file
1503 * corresponding to the WIM dentry @dentry. */
1505 do_set_reparse_data(const struct wim_dentry *dentry,
1506 const void *rpbuf, u16 rpbuflen,
1507 struct win32_apply_ctx *ctx)
1512 status = create_file(&h, GENERIC_WRITE, NULL,
1513 0, FILE_OPEN, 0, dentry, ctx);
1514 if (!NT_SUCCESS(status))
1517 status = (*func_NtFsControlFile)(h, NULL, NULL, NULL,
1518 &ctx->iosb, FSCTL_SET_REPARSE_POINT,
1519 (void *)rpbuf, rpbuflen,
1523 if (NT_SUCCESS(status))
1526 /* On Windows, by default only the Administrator can create symbolic
1527 * links for some reason. By default we just issue a warning if this
1528 * appears to be the problem. Use WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS
1529 * to get a hard error. */
1530 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS)
1531 && (status == STATUS_PRIVILEGE_NOT_HELD ||
1532 status == STATUS_ACCESS_DENIED)
1533 && (dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1534 dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1536 WARNING("Can't create symbolic link \"%ls\"! \n"
1537 " (Need Administrator rights, or at least "
1539 " SeCreateSymbolicLink privilege.)",
1545 set_errno_from_nt_status(status);
1546 ERROR_WITH_ERRNO("Can't set reparse data on \"%ls\" "
1547 "(status=0x%08"PRIx32")",
1548 current_path(ctx), (u32)status);
1549 return WIMLIB_ERR_SET_REPARSE_DATA;
1552 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1553 * pointer to the suffix of the path that begins with the device directly, such
1554 * as e:\Windows\System32. */
1555 static const wchar_t *
1556 skip_nt_toplevel_component(const wchar_t *path, size_t path_nchars)
1558 static const wchar_t * const dirs[] = {
1563 size_t first_dir_len = 0;
1564 const wchar_t * const end = path + path_nchars;
1566 for (size_t i = 0; i < ARRAY_LEN(dirs); i++) {
1567 size_t len = wcslen(dirs[i]);
1568 if (len <= (end - path) && !wcsnicmp(path, dirs[i], len)) {
1569 first_dir_len = len;
1573 if (first_dir_len == 0)
1575 path += first_dir_len;
1576 while (path != end && *path == L'\\')
1581 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1582 * pointer to the suffix of the path that is device-relative, such as
1585 * The path has an explicit length and is not necessarily null terminated.
1587 * If the path just something like \??\e: then the returned pointer will point
1588 * just past the colon. In this case the length of the result will be 0
1590 static const wchar_t *
1591 get_device_relative_path(const wchar_t *path, size_t path_nchars)
1593 const wchar_t * const orig_path = path;
1594 const wchar_t * const end = path + path_nchars;
1596 path = skip_nt_toplevel_component(path, path_nchars);
1597 if (path == orig_path)
1600 path = wmemchr(path, L'\\', (end - path));
1605 } while (path != end && *path == L'\\');
1610 * Given a reparse point buffer for a symbolic link or junction, adjust its
1611 * contents so that the target of the link is consistent with the new location
1615 try_rpfix(u8 *rpbuf, u16 *rpbuflen_p, struct win32_apply_ctx *ctx)
1617 struct reparse_data rpdata;
1618 size_t orig_subst_name_nchars;
1619 const wchar_t *relpath;
1620 size_t relpath_nchars;
1621 size_t target_ntpath_nchars;
1622 size_t fixed_subst_name_nchars;
1623 const wchar_t *fixed_print_name;
1624 size_t fixed_print_name_nchars;
1626 if (parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata)) {
1627 /* Do nothing if the reparse data is invalid. */
1631 if (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
1632 (rpdata.rpflags & SYMBOLIC_LINK_RELATIVE))
1634 /* Do nothing if it's a relative symbolic link. */
1638 /* Build the new substitute name from the NT namespace path to the
1639 * target directory, then a path separator, then the "device relative"
1640 * part of the old substitute name. */
1642 orig_subst_name_nchars = rpdata.substitute_name_nbytes / sizeof(wchar_t);
1644 relpath = get_device_relative_path(rpdata.substitute_name,
1645 orig_subst_name_nchars);
1646 relpath_nchars = orig_subst_name_nchars -
1647 (relpath - rpdata.substitute_name);
1649 target_ntpath_nchars = ctx->target_ntpath.Length / sizeof(wchar_t);
1651 fixed_subst_name_nchars = target_ntpath_nchars;
1653 fixed_subst_name_nchars += 1 + relpath_nchars;
1654 wchar_t fixed_subst_name[fixed_subst_name_nchars];
1656 wmemcpy(fixed_subst_name, ctx->target_ntpath.Buffer,
1657 target_ntpath_nchars);
1658 if (relpath_nchars) {
1659 fixed_subst_name[target_ntpath_nchars] = L'\\';
1660 wmemcpy(&fixed_subst_name[target_ntpath_nchars + 1],
1661 relpath, relpath_nchars);
1663 /* Doesn't need to be null-terminated. */
1665 /* Print name should be Win32, but not all NT names can even be
1666 * translated to Win32 names. But we can at least delete the top-level
1667 * directory, such as \??\, and this will have the expected result in
1668 * the usual case. */
1669 fixed_print_name = skip_nt_toplevel_component(fixed_subst_name,
1670 fixed_subst_name_nchars);
1671 fixed_print_name_nchars = fixed_subst_name_nchars - (fixed_print_name -
1674 rpdata.substitute_name = fixed_subst_name;
1675 rpdata.substitute_name_nbytes = fixed_subst_name_nchars * sizeof(wchar_t);
1676 rpdata.print_name = (wchar_t *)fixed_print_name;
1677 rpdata.print_name_nbytes = fixed_print_name_nchars * sizeof(wchar_t);
1678 make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
1681 /* Sets reparse data on the specified file. This handles "fixing" the targets
1682 * of absolute symbolic links and junctions if WIMLIB_EXTRACT_FLAG_RPFIX was
1685 set_reparse_data(const struct wim_dentry *dentry,
1686 const void *_rpbuf, u16 rpbuflen, struct win32_apply_ctx *ctx)
1688 const struct wim_inode *inode = dentry->d_inode;
1689 const void *rpbuf = _rpbuf;
1691 if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
1692 && !inode->i_not_rpfixed
1693 && (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1694 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1696 memcpy(&ctx->rpfixbuf, _rpbuf, rpbuflen);
1697 try_rpfix((u8 *)&ctx->rpfixbuf, &rpbuflen, ctx);
1698 rpbuf = &ctx->rpfixbuf;
1700 return do_set_reparse_data(dentry, rpbuf, rpbuflen, ctx);
1704 /* Import the next block of raw encrypted data */
1706 import_encrypted_data(PBYTE pbData, PVOID pvCallbackContext, PULONG Length)
1708 struct win32_apply_ctx *ctx = pvCallbackContext;
1711 copy_len = min(ctx->encrypted_size - ctx->encrypted_offset, *Length);
1712 memcpy(pbData, &ctx->data_buffer[ctx->encrypted_offset], copy_len);
1713 ctx->encrypted_offset += copy_len;
1715 return ERROR_SUCCESS;
1718 /* Write the raw encrypted data to the already-created file corresponding to
1721 * The raw encrypted data is provided in ctx->data_buffer, and its size is
1722 * ctx->encrypted_size. */
1724 extract_encrypted_file(const struct wim_dentry *dentry,
1725 struct win32_apply_ctx *ctx)
1730 /* Temporarily build a Win32 path for OpenEncryptedFileRaw() */
1731 build_win32_extraction_path(dentry, ctx);
1733 err = OpenEncryptedFileRaw(ctx->pathbuf.Buffer,
1734 CREATE_FOR_IMPORT, &rawctx);
1736 /* Restore the NT namespace path */
1737 build_extraction_path(dentry, ctx);
1739 if (err != ERROR_SUCCESS) {
1740 set_errno_from_win32_error(err);
1741 ERROR_WITH_ERRNO("Can't open \"%ls\" for encrypted import "
1742 "(err=%"PRIu32")", current_path(ctx), (u32)err);
1743 return WIMLIB_ERR_OPEN;
1746 ctx->encrypted_offset = 0;
1748 err = WriteEncryptedFileRaw(import_encrypted_data, ctx, rawctx);
1750 CloseEncryptedFileRaw(rawctx);
1752 if (err != ERROR_SUCCESS) {
1753 set_errno_from_win32_error(err);
1754 ERROR_WITH_ERRNO("Can't import encrypted file \"%ls\" "
1755 "(err=%"PRIu32")", current_path(ctx), (u32)err);
1756 return WIMLIB_ERR_WRITE;
1762 /* Called when starting to read a stream for extraction on Windows */
1764 begin_extract_stream(struct wim_lookup_table_entry *stream, void *_ctx)
1766 struct win32_apply_ctx *ctx = _ctx;
1767 const struct stream_owner *owners = stream_owners(stream);
1770 ctx->num_open_handles = 0;
1771 ctx->data_buffer_ptr = NULL;
1772 INIT_LIST_HEAD(&ctx->reparse_dentries);
1773 INIT_LIST_HEAD(&ctx->encrypted_dentries);
1775 for (u32 i = 0; i < stream->out_refcnt; i++) {
1776 const struct wim_inode *inode = owners[i].inode;
1777 const wchar_t *stream_name = owners[i].stream_name;
1778 struct wim_dentry *dentry;
1780 /* A copy of the stream needs to be extracted to @inode. */
1782 if (ctx->common.supported_features.hard_links) {
1783 dentry = inode_first_extraction_dentry(inode);
1784 ret = begin_extract_stream_instance(stream, dentry,
1789 /* Hard links not supported. Extract the stream
1790 * separately to each alias of the inode. */
1791 struct list_head *next;
1793 next = inode->i_extraction_aliases.next;
1795 dentry = list_entry(next, struct wim_dentry,
1796 d_extraction_alias_node);
1797 ret = begin_extract_stream_instance(stream,
1804 } while (next != &inode->i_extraction_aliases);
1815 /* Called when the next chunk of a stream has been read for extraction on
1818 extract_chunk(const void *chunk, size_t size, void *_ctx)
1820 struct win32_apply_ctx *ctx = _ctx;
1822 /* Write the data chunk to each open handle */
1823 for (unsigned i = 0; i < ctx->num_open_handles; i++) {
1824 u8 *bufptr = (u8 *)chunk;
1825 size_t bytes_remaining = size;
1827 while (bytes_remaining) {
1828 ULONG count = min(0xFFFFFFFF, bytes_remaining);
1830 status = (*func_NtWriteFile)(ctx->open_handles[i],
1832 &ctx->iosb, bufptr, count,
1834 if (!NT_SUCCESS(status)) {
1835 set_errno_from_nt_status(status);
1836 ERROR_WITH_ERRNO("Error writing data to target "
1837 "volume (status=0x%08"PRIx32")",
1839 return WIMLIB_ERR_WRITE;
1841 bufptr += ctx->iosb.Information;
1842 bytes_remaining -= ctx->iosb.Information;
1846 /* Copy the data chunk into the buffer (if needed) */
1847 if (ctx->data_buffer_ptr)
1848 ctx->data_buffer_ptr = mempcpy(ctx->data_buffer_ptr,
1853 /* Called when a stream has been fully read for extraction on Windows */
1855 end_extract_stream(struct wim_lookup_table_entry *stream, int status, void *_ctx)
1857 struct win32_apply_ctx *ctx = _ctx;
1859 const struct wim_dentry *dentry;
1866 if (likely(!ctx->data_buffer_ptr))
1869 if (!list_empty(&ctx->reparse_dentries)) {
1870 if (stream->size > REPARSE_DATA_MAX_SIZE) {
1871 dentry = list_first_entry(&ctx->reparse_dentries,
1872 struct wim_dentry, tmp_list);
1873 build_extraction_path(dentry, ctx);
1874 ERROR("Reparse data of \"%ls\" has size "
1875 "%"PRIu64" bytes (exceeds %u bytes)",
1876 current_path(ctx), stream->size,
1877 REPARSE_DATA_MAX_SIZE);
1878 return WIMLIB_ERR_INVALID_REPARSE_DATA;
1880 /* In the WIM format, reparse streams are just the reparse data
1881 * and omit the header. But we can reconstruct the header. */
1882 memcpy(ctx->rpbuf.rpdata, ctx->data_buffer, stream->size);
1883 ctx->rpbuf.rpdatalen = stream->size;
1884 ctx->rpbuf.rpreserved = 0;
1885 list_for_each_entry(dentry, &ctx->reparse_dentries, tmp_list) {
1886 ctx->rpbuf.rptag = dentry->d_inode->i_reparse_tag;
1887 ret = set_reparse_data(dentry, &ctx->rpbuf,
1888 stream->size + REPARSE_DATA_OFFSET,
1895 if (!list_empty(&ctx->encrypted_dentries)) {
1896 ctx->encrypted_size = stream->size;
1897 list_for_each_entry(dentry, &ctx->encrypted_dentries, tmp_list) {
1898 ret = extract_encrypted_file(dentry, ctx);
1907 /* Attributes that can't be set directly */
1908 #define SPECIAL_ATTRIBUTES \
1909 (FILE_ATTRIBUTE_REPARSE_POINT | \
1910 FILE_ATTRIBUTE_DIRECTORY | \
1911 FILE_ATTRIBUTE_ENCRYPTED | \
1912 FILE_ATTRIBUTE_SPARSE_FILE | \
1913 FILE_ATTRIBUTE_COMPRESSED)
1915 /* Set the security descriptor @desc, of @desc_size bytes, on the file with open
1918 set_security_descriptor(HANDLE h, const void *desc,
1919 size_t desc_size, struct win32_apply_ctx *ctx)
1921 SECURITY_INFORMATION info;
1924 /* We really just want to set entire the security descriptor as-is, but
1925 * all available APIs require specifying the specific parts of the
1926 * descriptor being set. Start out by requesting all parts be set. If
1927 * permissions problems are encountered, fall back to omitting some
1928 * parts (first the SACL, then the DACL, then the owner), unless the
1929 * WIMLIB_EXTRACT_FLAG_STRICT_ACLS flag has been enabled. */
1930 info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
1931 DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION;
1933 /* Prefer NtSetSecurityObject() to SetFileSecurity(). SetFileSecurity()
1934 * itself necessarily uses NtSetSecurityObject() as the latter is the
1935 * underlying system call for setting security information, but
1936 * SetFileSecurity() opens the handle with NtCreateFile() without
1937 * FILE_OPEN_FILE_BACKUP_INTENT. Hence, access checks are done and due
1938 * to the Windows security model, even a process running as the
1939 * Administrator can have access denied. (Of course, this not mentioned
1940 * in the MS "documentation".) */
1942 status = (*func_NtSetSecurityObject)(h, info, (PSECURITY_DESCRIPTOR)desc);
1943 if (NT_SUCCESS(status))
1945 /* Failed to set the requested parts of the security descriptor. If the
1946 * error was permissions-related, try to set fewer parts of the security
1947 * descriptor, unless WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled. */
1948 if ((status == STATUS_PRIVILEGE_NOT_HELD ||
1949 status == STATUS_ACCESS_DENIED) &&
1950 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
1952 if (info & SACL_SECURITY_INFORMATION) {
1953 info &= ~SACL_SECURITY_INFORMATION;
1954 ctx->partial_security_descriptors++;
1957 if (info & DACL_SECURITY_INFORMATION) {
1958 info &= ~DACL_SECURITY_INFORMATION;
1961 if (info & OWNER_SECURITY_INFORMATION) {
1962 info &= ~OWNER_SECURITY_INFORMATION;
1965 /* Nothing left except GROUP, and if we removed it we
1966 * wouldn't have anything at all. */
1969 /* No part of the security descriptor could be set, or
1970 * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled and the full security
1971 * descriptor could not be set. */
1972 if (!(info & SACL_SECURITY_INFORMATION))
1973 ctx->partial_security_descriptors--;
1974 ctx->no_security_descriptors++;
1978 /* Set metadata on the open file @h from the WIM inode @inode. */
1980 do_apply_metadata_to_file(HANDLE h, const struct wim_inode *inode,
1981 struct win32_apply_ctx *ctx)
1983 FILE_BASIC_INFORMATION info;
1986 /* Set security descriptor if present and not in NO_ACLS mode */
1987 if (inode->i_security_id >= 0 &&
1988 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
1990 const struct wim_security_data *sd;
1994 sd = wim_get_current_security_data(ctx->common.wim);
1995 desc = sd->descriptors[inode->i_security_id];
1996 desc_size = sd->sizes[inode->i_security_id];
1998 status = set_security_descriptor(h, desc, desc_size, ctx);
1999 if (!NT_SUCCESS(status) &&
2000 (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2002 set_errno_from_nt_status(status);
2003 ERROR_WITH_ERRNO("Can't set security descriptor "
2004 "on \"%ls\" (status=0x%08"PRIx32")",
2005 current_path(ctx), (u32)status);
2006 return WIMLIB_ERR_SET_SECURITY;
2010 /* Set attributes and timestamps */
2011 info.CreationTime.QuadPart = inode->i_creation_time;
2012 info.LastAccessTime.QuadPart = inode->i_last_access_time;
2013 info.LastWriteTime.QuadPart = inode->i_last_write_time;
2014 info.ChangeTime.QuadPart = 0;
2015 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
2016 info.FileAttributes = 0;
2018 info.FileAttributes = inode->i_attributes & ~SPECIAL_ATTRIBUTES;
2020 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
2021 &info, sizeof(info),
2022 FileBasicInformation);
2023 /* On FAT volumes we get STATUS_INVALID_PARAMETER if we try to set
2024 * attributes on the root directory. (Apparently because FAT doesn't
2025 * actually have a place to store those attributes!) */
2026 if (!NT_SUCCESS(status)
2027 && !(status == STATUS_INVALID_PARAMETER &&
2028 dentry_is_root(inode_first_extraction_dentry(inode))))
2030 set_errno_from_nt_status(status);
2031 ERROR_WITH_ERRNO("Can't set basic metadata on \"%ls\" "
2032 "(status=0x%08"PRIx32")",
2033 current_path(ctx), (u32)status);
2034 return WIMLIB_ERR_SET_ATTRIBUTES;
2041 apply_metadata_to_file(const struct wim_dentry *dentry,
2042 struct win32_apply_ctx *ctx)
2044 const struct wim_inode *inode = dentry->d_inode;
2050 perms = FILE_WRITE_ATTRIBUTES | WRITE_DAC |
2051 WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
2053 build_extraction_path(dentry, ctx);
2055 /* Open a handle with as many relevant permissions as possible. */
2056 while (!NT_SUCCESS(status = do_create_file(&h, perms, NULL,
2057 0, FILE_OPEN, 0, ctx)))
2059 if (status == STATUS_PRIVILEGE_NOT_HELD ||
2060 status == STATUS_ACCESS_DENIED)
2062 if (perms & ACCESS_SYSTEM_SECURITY) {
2063 perms &= ~ACCESS_SYSTEM_SECURITY;
2066 if (perms & WRITE_DAC) {
2067 perms &= ~WRITE_DAC;
2070 if (perms & WRITE_OWNER) {
2071 perms &= ~WRITE_OWNER;
2075 set_errno_from_nt_status(status);
2076 ERROR_WITH_ERRNO("Can't open \"%ls\" to set metadata "
2077 "(status=0x%08"PRIx32")",
2078 current_path(ctx), (u32)status);
2079 return WIMLIB_ERR_OPEN;
2082 ret = do_apply_metadata_to_file(h, inode, ctx);
2090 apply_metadata(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
2092 const struct wim_dentry *dentry;
2095 /* We go in reverse so that metadata is set on all a directory's
2096 * children before the directory itself. This avoids any potential
2097 * problems with attributes, timestamps, or security descriptors. */
2098 list_for_each_entry_reverse(dentry, dentry_list, d_extraction_list_node)
2100 ret = apply_metadata_to_file(dentry, ctx);
2103 ret = report_file_metadata_applied(&ctx->common);
2110 /* Issue warnings about problems during the extraction for which warnings were
2111 * not already issued (due to the high number of potential warnings if we issued
2112 * them per-file). */
2114 do_warnings(const struct win32_apply_ctx *ctx)
2116 if (ctx->partial_security_descriptors == 0 &&
2117 ctx->no_security_descriptors == 0 &&
2118 ctx->num_short_name_failures == 0)
2121 WARNING("Extraction to \"%ls\" complete, but with one or more warnings:",
2122 ctx->common.target);
2123 if (ctx->num_short_name_failures) {
2124 WARNING("- Could not set short names on %lu files or directories",
2125 ctx->num_short_name_failures);
2127 if (ctx->partial_security_descriptors) {
2128 WARNING("- Could only partially set the security descriptor\n"
2129 " on %lu files or directories.",
2130 ctx->partial_security_descriptors);
2132 if (ctx->no_security_descriptors) {
2133 WARNING("- Could not set security descriptor at all\n"
2134 " on %lu files or directories.",
2135 ctx->no_security_descriptors);
2137 if (ctx->partial_security_descriptors || ctx->no_security_descriptors) {
2138 WARNING("To fully restore all security descriptors, run the program\n"
2139 " with Administrator rights.");
2143 /* Extract files from a WIM image to a directory on Windows */
2145 win32_extract(struct list_head *dentry_list, struct apply_ctx *_ctx)
2148 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
2150 ret = prepare_target(dentry_list, ctx);
2154 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
2155 ret = start_wimboot_extraction(ctx);
2160 reset_file_progress(&ctx->common);
2162 ret = create_directories(dentry_list, ctx);
2166 ret = create_nondirectories(dentry_list, ctx);
2170 struct read_stream_list_callbacks cbs = {
2171 .begin_stream = begin_extract_stream,
2172 .begin_stream_ctx = ctx,
2173 .consume_chunk = extract_chunk,
2174 .consume_chunk_ctx = ctx,
2175 .end_stream = end_extract_stream,
2176 .end_stream_ctx = ctx,
2178 ret = extract_stream_list(&ctx->common, &cbs);
2182 reset_file_progress(&ctx->common);
2184 ret = apply_metadata(dentry_list, ctx);
2188 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
2189 ret = end_wimboot_extraction(ctx);
2197 (*func_NtClose)(ctx->h_target);
2198 if (ctx->target_ntpath.Buffer)
2199 HeapFree(GetProcessHeap(), 0, ctx->target_ntpath.Buffer);
2200 FREE(ctx->pathbuf.Buffer);
2201 FREE(ctx->print_buffer);
2202 if (ctx->wimboot.prepopulate_pats) {
2203 FREE(ctx->wimboot.prepopulate_pats->strings);
2204 FREE(ctx->wimboot.prepopulate_pats);
2206 FREE(ctx->wimboot.mem_prepopulate_pats);
2207 FREE(ctx->data_buffer);
2211 const struct apply_operations win32_apply_ops = {
2213 .get_supported_features = win32_get_supported_features,
2214 .extract = win32_extract,
2215 .context_size = sizeof(struct win32_apply_ctx),
2218 #endif /* __WIN32__ */