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;
129 /* Get the drive letter from a Windows path, or return the null character if the
130 * path is relative. */
132 get_drive_letter(const wchar_t *path)
134 /* Skip \\?\ prefix */
135 if (!wcsncmp(path, L"\\\\?\\", 4))
138 /* Return drive letter if valid */
139 if (((path[0] >= L'a' && path[0] <= L'z') ||
140 (path[0] >= L'A' && path[0] <= L'Z')) && path[1] == L':')
147 get_vol_flags(const wchar_t *target, DWORD *vol_flags_ret,
148 bool *short_names_supported_ret)
150 wchar_t filesystem_name[MAX_PATH + 1];
152 wchar_t *volume = NULL;
155 *short_names_supported_ret = false;
157 drive[0] = get_drive_letter(target);
165 if (!GetVolumeInformation(volume, NULL, 0, NULL, NULL,
166 vol_flags_ret, filesystem_name,
167 ARRAY_LEN(filesystem_name)))
169 DWORD err = GetLastError();
170 set_errno_from_win32_error(err);
171 WARNING_WITH_ERRNO("Failed to get volume information for "
172 "\"%ls\" (err=%"PRIu32")",
177 if (wcsstr(filesystem_name, L"NTFS")) {
178 /* FILE_SUPPORTS_HARD_LINKS is only supported on Windows 7 and
179 * later. Force it on anyway if filesystem is NTFS. */
180 *vol_flags_ret |= FILE_SUPPORTS_HARD_LINKS;
182 /* There's no volume flag for short names, but according to the
183 * MS documentation they are only user-settable on NTFS. */
184 *short_names_supported_ret = true;
189 win32_get_supported_features(const wchar_t *target,
190 struct wim_features *supported_features)
193 bool short_names_supported;
195 /* Query the features of the target volume. */
197 get_vol_flags(target, &vol_flags, &short_names_supported);
199 supported_features->archive_files = 1;
200 supported_features->hidden_files = 1;
201 supported_features->system_files = 1;
203 if (vol_flags & FILE_FILE_COMPRESSION)
204 supported_features->compressed_files = 1;
206 if (vol_flags & FILE_SUPPORTS_ENCRYPTION) {
207 supported_features->encrypted_files = 1;
208 supported_features->encrypted_directories = 1;
211 supported_features->not_context_indexed_files = 1;
213 /* Don't do anything with FILE_SUPPORTS_SPARSE_FILES. */
215 if (vol_flags & FILE_NAMED_STREAMS)
216 supported_features->named_data_streams = 1;
218 if (vol_flags & FILE_SUPPORTS_HARD_LINKS)
219 supported_features->hard_links = 1;
221 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS)
222 supported_features->reparse_points = 1;
224 if (vol_flags & FILE_PERSISTENT_ACLS)
225 supported_features->security_descriptors = 1;
227 if (short_names_supported)
228 supported_features->short_names = 1;
230 supported_features->timestamps = 1;
232 /* Note: Windows does not support case sensitive filenames! At least
233 * not without changing the registry and rebooting... */
238 /* Load the patterns from [PrepopulateList] of WimBootCompresse.ini in the WIM
239 * image being extracted. */
241 load_prepopulate_pats(struct win32_apply_ctx *ctx)
243 const wchar_t *path = L"\\Windows\\System32\\WimBootCompress.ini";
244 struct wim_dentry *dentry;
245 struct wim_lookup_table_entry *lte;
248 struct string_set *s;
250 struct text_file_section sec;
252 dentry = get_dentry(ctx->common.wim, path, WIMLIB_CASE_INSENSITIVE);
254 (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
255 FILE_ATTRIBUTE_REPARSE_POINT |
256 FILE_ATTRIBUTE_ENCRYPTED)) ||
257 !(lte = inode_unnamed_lte(dentry->d_inode, ctx->common.wim->lookup_table)))
259 WARNING("%ls does not exist in WIM image!", path);
260 return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
263 ret = read_full_stream_into_alloc_buf(lte, &buf);
267 s = CALLOC(1, sizeof(struct string_set));
270 return WIMLIB_ERR_NOMEM;
273 sec.name = T("PrepopulateList");
276 ret = do_load_text_file(path, buf, lte->size, &mem, &sec, 1,
277 LOAD_TEXT_FILE_REMOVE_QUOTES |
278 LOAD_TEXT_FILE_NO_WARNINGS,
280 BUILD_BUG_ON(OS_PREFERRED_PATH_SEPARATOR != WIM_PATH_SEPARATOR);
286 ctx->wimboot.prepopulate_pats = s;
287 ctx->wimboot.mem_prepopulate_pats = mem;
291 /* Returns %true if the path to @dentry matches a pattern in [PrepopulateList]
292 * of WimBootCompress.ini. Otherwise returns %false.
294 * @dentry must have had its full path calculated. */
296 in_prepopulate_list(struct wim_dentry *dentry,
297 const struct win32_apply_ctx *ctx)
299 const struct string_set *pats = ctx->wimboot.prepopulate_pats;
301 if (!pats || !pats->num_strings)
304 return match_pattern_list(dentry->_full_path,
305 wcslen(dentry->_full_path), pats);
308 /* Calculates the SHA-1 message digest of the WIM's lookup table. */
310 hash_lookup_table(WIMStruct *wim, u8 hash[SHA1_HASH_SIZE])
312 return wim_reshdr_to_hash(&wim->hdr.lookup_table_reshdr, wim, hash);
315 /* Prepare for doing a "WIMBoot" extraction by loading patterns from
316 * [PrepopulateList] of WimBootCompress.ini and allocating a WOF data source ID
317 * on the target volume. */
319 start_wimboot_extraction(struct win32_apply_ctx *ctx)
322 WIMStruct *wim = ctx->common.wim;
324 ret = load_prepopulate_pats(ctx);
325 if (ret == WIMLIB_ERR_NOMEM)
328 if (!wim_info_get_wimboot(wim->wim_info,
330 WARNING("Image is not marked as WIMBoot compatible!");
332 ret = hash_lookup_table(ctx->common.wim,
333 ctx->wimboot.wim_lookup_table_hash);
337 return wimboot_alloc_data_source_id(wim->filename,
341 &ctx->wimboot.data_source_id,
342 &ctx->wimboot.wof_running);
345 /* Returns the number of wide characters needed to represent the path to the
346 * specified @dentry, relative to the target directory, when extracted.
348 * Does not include null terminator (not needed for NtCreateFile). */
350 dentry_extraction_path_length(const struct wim_dentry *dentry)
353 const struct wim_dentry *d;
357 len += d->d_extraction_name_nchars + 1;
359 } while (!dentry_is_root(d) && will_extract_dentry(d));
361 return --len; /* No leading slash */
364 /* Returns the length of the longest string that might need to be appended to
365 * the path to an alias of an inode to open or create a named data stream.
367 * If the inode has no named data streams, this will be 0. Otherwise, this will
368 * be 1 plus the length of the longest-named data stream, since the data stream
369 * name must be separated form the path by the ':' character. */
371 inode_longest_named_data_stream_spec(const struct wim_inode *inode)
374 for (u16 i = 0; i < inode->i_num_ads; i++) {
375 size_t len = inode->i_ads_entries[i].stream_name_nbytes;
380 max = 1 + (max / sizeof(wchar_t));
384 /* Find the length, in wide characters, of the longest path needed for
385 * extraction of any file in @dentry_list relative to the target directory.
387 * Accounts for named data streams, but does not include null terminator (not
388 * needed for NtCreateFile). */
390 compute_path_max(struct list_head *dentry_list)
393 const struct wim_dentry *dentry;
395 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
398 len = dentry_extraction_path_length(dentry);
400 /* Account for named data streams */
401 len += inode_longest_named_data_stream_spec(dentry->d_inode);
410 /* Build the path at which to extract the @dentry, relative to the target
413 * The path is saved in ctx->pathbuf. */
415 build_extraction_path(const struct wim_dentry *dentry,
416 struct win32_apply_ctx *ctx)
420 const struct wim_dentry *d;
422 len = dentry_extraction_path_length(dentry);
424 ctx->pathbuf.Length = len * sizeof(wchar_t);
425 p = ctx->pathbuf.Buffer + len;
427 !dentry_is_root(d->d_parent) && will_extract_dentry(d->d_parent);
430 p -= d->d_extraction_name_nchars;
431 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
434 /* No leading slash */
435 p -= d->d_extraction_name_nchars;
436 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
439 /* Build the path at which to extract the @dentry, relative to the target
440 * directory, adding the suffix for a named data stream.
442 * The path is saved in ctx->pathbuf. */
444 build_extraction_path_with_ads(const struct wim_dentry *dentry,
445 struct win32_apply_ctx *ctx,
446 const wchar_t *stream_name,
447 size_t stream_name_nchars)
451 build_extraction_path(dentry, ctx);
453 /* Add :NAME for named data stream */
454 p = ctx->pathbuf.Buffer + (ctx->pathbuf.Length / sizeof(wchar_t));
456 wmemcpy(p, stream_name, stream_name_nchars);
457 ctx->pathbuf.Length += (1 + stream_name_nchars) * sizeof(wchar_t);
460 /* Build the Win32 namespace path to the specified @dentry when extracted.
462 * The path is saved in ctx->pathbuf and will be null terminated.
464 * XXX: We could get rid of this if it wasn't needed for the file encryption
467 build_win32_extraction_path(const struct wim_dentry *dentry,
468 struct win32_apply_ctx *ctx)
470 build_extraction_path(dentry, ctx);
472 /* Prepend target_ntpath to our relative path, then change \??\ into \\?\ */
474 memmove(ctx->pathbuf.Buffer +
475 (ctx->target_ntpath.Length / sizeof(wchar_t)) + 1,
476 ctx->pathbuf.Buffer, ctx->pathbuf.Length);
477 memcpy(ctx->pathbuf.Buffer, ctx->target_ntpath.Buffer,
478 ctx->target_ntpath.Length);
479 ctx->pathbuf.Buffer[ctx->target_ntpath.Length / sizeof(wchar_t)] = L'\\';
480 ctx->pathbuf.Length += ctx->target_ntpath.Length + sizeof(wchar_t);
481 ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)] = L'\0';
483 wimlib_assert(ctx->pathbuf.Length >= 4 * sizeof(wchar_t) &&
484 !wmemcmp(ctx->pathbuf.Buffer, L"\\??\\", 4));
486 ctx->pathbuf.Buffer[1] = L'\\';
490 /* Returns a "printable" representation of the last relative NT path that was
491 * constructed with build_extraction_path() or build_extraction_path_with_ads().
493 * This will be overwritten by the next call to this function. */
494 static const wchar_t *
495 current_path(struct win32_apply_ctx *ctx)
497 wchar_t *p = ctx->print_buffer;
499 p = wmempcpy(p, ctx->common.target, ctx->common.target_nchars);
501 p = wmempcpy(p, ctx->pathbuf.Buffer, ctx->pathbuf.Length / sizeof(wchar_t));
503 return ctx->print_buffer;
507 * Ensures the target directory exists and opens a handle to it, in preparation
508 * of using paths relative to it.
511 prepare_target(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
517 /* Open handle to the target directory (possibly creating it). */
519 ret = win32_path_to_nt_path(ctx->common.target, &ctx->target_ntpath);
523 ctx->attr.Length = sizeof(ctx->attr);
524 ctx->attr.ObjectName = &ctx->target_ntpath;
526 status = (*func_NtCreateFile)(&ctx->h_target,
532 FILE_SHARE_VALID_FLAGS,
534 FILE_DIRECTORY_FILE |
535 FILE_OPEN_REPARSE_POINT |
536 FILE_OPEN_FOR_BACKUP_INTENT,
540 if (!NT_SUCCESS(status)) {
541 set_errno_from_nt_status(status);
542 ERROR_WITH_ERRNO("Can't open or create directory \"%ls\" "
543 "(status=0x%08"PRIx32")",
544 ctx->common.target, (u32)status);
545 return WIMLIB_ERR_OPENDIR;
548 path_max = compute_path_max(dentry_list);
550 /* Add some extra for building Win32 paths for the file encryption APIs
552 path_max += 2 + (ctx->target_ntpath.Length / sizeof(wchar_t));
554 ctx->pathbuf.MaximumLength = path_max * sizeof(wchar_t);
555 ctx->pathbuf.Buffer = MALLOC(ctx->pathbuf.MaximumLength);
556 if (!ctx->pathbuf.Buffer)
557 return WIMLIB_ERR_NOMEM;
559 ctx->attr.RootDirectory = ctx->h_target;
560 ctx->attr.ObjectName = &ctx->pathbuf;
562 ctx->print_buffer = MALLOC((ctx->common.target_nchars + 1 + path_max + 1) *
564 if (!ctx->print_buffer)
565 return WIMLIB_ERR_NOMEM;
570 /* When creating an inode that will have a short (DOS) name, we create it using
571 * the long name associated with the short name. This ensures that the short
572 * name gets associated with the correct long name. */
573 static const struct wim_dentry *
574 first_extraction_alias(const struct wim_inode *inode)
576 const struct list_head *next = inode->i_extraction_aliases.next;
577 const struct wim_dentry *dentry;
580 dentry = list_entry(next, struct wim_dentry,
581 d_extraction_alias_node);
582 if (dentry_has_short_name(dentry))
585 } while (next != &inode->i_extraction_aliases);
590 * Set or clear FILE_ATTRIBUTE_COMPRESSED if the inherited value is different
591 * from the desired value.
593 * Note that you can NOT override the inherited value of
594 * FILE_ATTRIBUTE_COMPRESSED directly with NtCreateFile().
597 adjust_compression_attribute(HANDLE h, const struct wim_dentry *dentry,
598 struct win32_apply_ctx *ctx)
600 const bool compressed = (dentry->d_inode->i_attributes &
601 FILE_ATTRIBUTE_COMPRESSED);
603 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
606 if (!ctx->common.supported_features.compressed_files)
609 FILE_BASIC_INFORMATION info;
611 USHORT compression_state;
613 /* Get current attributes */
614 status = (*func_NtQueryInformationFile)(h, &ctx->iosb,
616 FileBasicInformation);
617 if (NT_SUCCESS(status) &&
618 compressed == !!(info.FileAttributes & FILE_ATTRIBUTE_COMPRESSED))
620 /* Nothing needs to be done. */
624 /* Set the new compression state */
627 compression_state = COMPRESSION_FORMAT_DEFAULT;
629 compression_state = COMPRESSION_FORMAT_NONE;
631 status = (*func_NtFsControlFile)(h,
636 FSCTL_SET_COMPRESSION,
641 if (NT_SUCCESS(status))
644 set_errno_from_nt_status(status);
645 ERROR_WITH_ERRNO("Can't %s compression attribute on \"%ls\" "
646 "(status=0x%08"PRIx32")",
647 (compressed ? "set" : "clear"),
648 current_path(ctx), status);
649 return WIMLIB_ERR_SET_ATTRIBUTES;
653 * Clear FILE_ATTRIBUTE_ENCRYPTED if the file or directory is not supposed to be
656 * You can provide FILE_ATTRIBUTE_ENCRYPTED to NtCreateFile() to set it on the
657 * created file. However, the file or directory will otherwise default to the
658 * encryption state of the parent directory. This function works around this
659 * limitation by using DecryptFile() to remove FILE_ATTRIBUTE_ENCRYPTED on files
660 * (and directories) that are not supposed to have it set.
662 * Regardless of whether it succeeds or fails, this function may close the
663 * handle to the file. If it does, it sets it to NULL.
666 maybe_clear_encryption_attribute(HANDLE *h_ret, const struct wim_dentry *dentry,
667 struct win32_apply_ctx *ctx)
669 if (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)
672 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
675 if (!ctx->common.supported_features.encrypted_files)
678 FILE_BASIC_INFORMATION info;
682 /* Get current attributes */
683 status = (*func_NtQueryInformationFile)(*h_ret, &ctx->iosb,
685 FileBasicInformation);
686 if (NT_SUCCESS(status) &&
687 !(info.FileAttributes & FILE_ATTRIBUTE_ENCRYPTED))
689 /* Nothing needs to be done. */
693 /* Set the new encryption state */
695 /* Due to Windows' crappy file encryption APIs, we need to close the
696 * handle to the file so we don't get ERROR_SHARING_VIOLATION. We also
697 * hack together a Win32 path, although we will use the \\?\ prefix so
698 * it will actually be a NT path in disguise... */
699 (*func_NtClose)(*h_ret);
702 build_win32_extraction_path(dentry, ctx);
704 bret = DecryptFile(ctx->pathbuf.Buffer, 0);
706 /* Restore the NT namespace path */
707 build_extraction_path(dentry, ctx);
710 DWORD err = GetLastError();
711 set_errno_from_win32_error(err);
712 ERROR_WITH_ERRNO("Can't decrypt file \"%ls\" (err=%"PRIu32")",
713 current_path(ctx), (u32)err);
714 return WIMLIB_ERR_SET_ATTRIBUTES;
719 /* Set the short name on the open file @h which has been created at the location
720 * indicated by @dentry.
722 * Note that this may add, change, or remove the short name.
724 * @h must be opened with DELETE access.
726 * Returns 0 or WIMLIB_ERR_SET_SHORT_NAME. The latter only happens in
727 * STRICT_SHORT_NAMES mode.
730 set_short_name(HANDLE h, const struct wim_dentry *dentry,
731 struct win32_apply_ctx *ctx)
733 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
734 dentry->short_name_nbytes;
735 u8 buf[bufsize] _aligned_attribute(8);
736 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
739 info->FileNameLength = dentry->short_name_nbytes;
740 memcpy(info->FileName, dentry->short_name, dentry->short_name_nbytes);
742 status = (*func_NtSetInformationFile)(h, &ctx->iosb, info, bufsize,
743 FileShortNameInformation);
744 if (NT_SUCCESS(status))
747 /* By default, failure to set short names is not an error (since short
748 * names aren't too important anymore...). */
749 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES))
752 if (status == STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME) {
753 if (dentry->short_name_nbytes == 0)
755 ERROR("Can't extract short name when short "
756 "names are not enabled on the volume!");
758 ERROR("Can't set short name on \"%ls\" (status=0x%08"PRIx32")",
759 current_path(ctx), (u32)status);
761 return WIMLIB_ERR_SET_SHORT_NAME;
765 * A wrapper around NtCreateFile() to make it slightly more usable...
766 * This uses the path currently constructed in ctx->pathbuf.
768 * Also, we always specify FILE_OPEN_FOR_BACKUP_INTENT and
769 * FILE_OPEN_REPARSE_POINT.
772 do_create_file(PHANDLE FileHandle,
773 ACCESS_MASK DesiredAccess,
774 PLARGE_INTEGER AllocationSize,
775 ULONG FileAttributes,
776 ULONG CreateDisposition,
778 struct win32_apply_ctx *ctx)
780 return (*func_NtCreateFile)(FileHandle,
786 FILE_SHARE_VALID_FLAGS,
789 FILE_OPEN_FOR_BACKUP_INTENT |
790 FILE_OPEN_REPARSE_POINT,
795 /* Like do_create_file(), but builds the extraction path of the @dentry first.
798 create_file(PHANDLE FileHandle,
799 ACCESS_MASK DesiredAccess,
800 PLARGE_INTEGER AllocationSize,
801 ULONG FileAttributes,
802 ULONG CreateDisposition,
804 const struct wim_dentry *dentry,
805 struct win32_apply_ctx *ctx)
807 build_extraction_path(dentry, ctx);
808 return do_create_file(FileHandle,
817 /* Create empty named data streams.
819 * Since these won't have 'struct wim_lookup_table_entry's, they won't show up
820 * in the call to extract_stream_list(). Hence the need for the special case.
823 create_any_empty_ads(const struct wim_dentry *dentry,
824 struct win32_apply_ctx *ctx)
826 const struct wim_inode *inode = dentry->d_inode;
827 LARGE_INTEGER allocation_size;
828 bool path_modified = false;
831 if (!ctx->common.supported_features.named_data_streams)
834 for (u16 i = 0; i < inode->i_num_ads; i++) {
835 const struct wim_ads_entry *entry;
839 entry = &inode->i_ads_entries[i];
842 if (!entry->stream_name_nbytes)
849 /* Probably setting the allocation size to 0 has no effect, but
850 * we might as well try. */
851 allocation_size.QuadPart = 0;
853 build_extraction_path_with_ads(dentry, ctx,
855 entry->stream_name_nbytes /
857 path_modified = true;
858 status = do_create_file(&h, FILE_WRITE_DATA, &allocation_size,
859 0, FILE_SUPERSEDE, 0, ctx);
860 if (!NT_SUCCESS(status)) {
861 set_errno_from_nt_status(status);
862 ERROR_WITH_ERRNO("Can't create \"%ls\" "
863 "(status=0x%08"PRIx32")",
864 current_path(ctx), (u32)status);
865 ret = WIMLIB_ERR_OPEN;
870 /* Restore the path to the dentry itself */
872 build_extraction_path(dentry, ctx);
877 * Creates the directory named by @dentry, or uses an existing directory at that
878 * location. If necessary, sets the short name and/or fixes compression and
879 * encryption attributes.
881 * Returns 0, WIMLIB_ERR_MKDIR, or WIMLIB_ERR_SET_SHORT_NAME.
884 create_directory(const struct wim_dentry *dentry,
885 struct win32_apply_ctx *ctx)
892 /* Special attributes:
894 * Use FILE_ATTRIBUTE_ENCRYPTED if the directory needs to have it set.
895 * This doesn't work for FILE_ATTRIBUTE_COMPRESSED (unfortunately).
897 * Don't specify FILE_ATTRIBUTE_DIRECTORY; it gets set anyway as a
898 * result of the FILE_DIRECTORY_FILE option. */
899 attrib = (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED);
901 /* DELETE is needed for set_short_name().
902 * GENERIC_READ and GENERIC_WRITE are needed for
903 * adjust_compression_attribute(). */
904 status = create_file(&h, GENERIC_READ | GENERIC_WRITE | DELETE, NULL,
905 attrib, FILE_OPEN_IF, FILE_DIRECTORY_FILE,
907 if (!NT_SUCCESS(status)) {
908 set_errno_from_nt_status(status);
909 ERROR_WITH_ERRNO("Can't create directory \"%ls\" "
910 "(status=0x%08"PRIx32")",
911 current_path(ctx), (u32)status);
912 return WIMLIB_ERR_MKDIR;
915 ret = set_short_name(h, dentry, ctx);
918 ret = adjust_compression_attribute(h, dentry, ctx);
921 ret = maybe_clear_encryption_attribute(&h, dentry, ctx);
922 /* May close the handle!!! */
930 * Create all the directories being extracted, other than the target directory
933 * Note: we don't honor directory hard links. However, we don't allow them to
934 * exist in WIM images anyway (see inode_fixup.c).
937 create_directories(struct list_head *dentry_list,
938 struct win32_apply_ctx *ctx)
940 const struct wim_dentry *dentry;
943 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
945 if (!(dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY))
948 /* Note: Here we include files with
949 * FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT, but we
950 * wait until later to actually set the reparse data. */
952 /* If the root dentry is being extracted, it was already done so
953 * it prepare_target(). */
954 if (dentry_is_root(dentry))
957 ret = create_directory(dentry, ctx);
961 ret = create_any_empty_ads(dentry, ctx);
969 * Creates the nondirectory file named by @dentry.
971 * On success, returns an open handle to the file in @h_ret, with GENERIC_READ,
972 * GENERIC_WRITE, and DELETE access. Also, the path to the file will be saved
973 * in ctx->pathbuf. On failure, returns WIMLIB_ERR_OPEN.
976 create_nondirectory_inode(HANDLE *h_ret, const struct wim_dentry *dentry,
977 struct win32_apply_ctx *ctx)
979 const struct wim_inode *inode;
982 bool retried = false;
984 inode = dentry->d_inode;
986 /* If the file already exists and has FILE_ATTRIBUTE_SYSTEM and/or
987 * FILE_ATTRIBUTE_HIDDEN, these must be specified in order to supersede
990 * Normally the user shouldn't be trying to overwrite such files anyway,
991 * but we at least provide FILE_ATTRIBUTE_SYSTEM and
992 * FILE_ATTRIBUTE_HIDDEN if the WIM inode has those attributes so that
993 * we catch the case where the user extracts the same files to the same
994 * location more than one time.
996 * Also specify FILE_ATTRIBUTE_ENCRYPTED if the file needs to be
999 * In NO_ATTRIBUTES mode just don't specify any attributes at all.
1001 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES) {
1004 attrib = (inode->i_attributes & (FILE_ATTRIBUTE_SYSTEM |
1005 FILE_ATTRIBUTE_HIDDEN |
1006 FILE_ATTRIBUTE_ENCRYPTED));
1008 build_extraction_path(dentry, ctx);
1010 status = do_create_file(h_ret, GENERIC_READ | GENERIC_WRITE | DELETE,
1011 NULL, attrib, FILE_SUPERSEDE,
1012 FILE_NON_DIRECTORY_FILE, ctx);
1013 if (NT_SUCCESS(status)) {
1016 ret = adjust_compression_attribute(*h_ret, dentry, ctx);
1018 (*func_NtClose)(*h_ret);
1022 ret = maybe_clear_encryption_attribute(h_ret, dentry, ctx);
1023 /* May close the handle!!! */
1027 (*func_NtClose)(*h_ret);
1032 /* Re-open the handle so that we can return it on
1034 status = do_create_file(h_ret,
1036 GENERIC_WRITE | DELETE,
1038 FILE_NON_DIRECTORY_FILE, ctx);
1039 if (!NT_SUCCESS(status))
1043 ret = create_any_empty_ads(dentry, ctx);
1045 (*func_NtClose)(*h_ret);
1051 if (status == STATUS_ACCESS_DENIED && !retried) {
1052 /* We also can't supersede an existing file that has
1053 * FILE_ATTRIBUTE_READONLY set; doing so causes NtCreateFile()
1054 * to return STATUS_ACCESS_DENIED . The only workaround seems
1055 * to be to explicitly remove FILE_ATTRIBUTE_READONLY on the
1056 * existing file, then try again. */
1058 FILE_BASIC_INFORMATION info;
1061 status = do_create_file(&h, FILE_WRITE_ATTRIBUTES, NULL, 0,
1062 FILE_OPEN, FILE_NON_DIRECTORY_FILE, ctx);
1063 if (!NT_SUCCESS(status))
1066 memset(&info, 0, sizeof(info));
1067 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1069 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1070 &info, sizeof(info),
1071 FileBasicInformation);
1073 if (!NT_SUCCESS(status))
1079 set_errno_from_nt_status(status);
1080 ERROR_WITH_ERRNO("Can't create file \"%ls\" (status=0x%08"PRIx32")",
1081 current_path(ctx), (u32)status);
1082 return WIMLIB_ERR_OPEN;
1085 /* Creates a hard link at the location named by @dentry to the file represented
1086 * by the open handle @h. Or, if the target volume does not support hard links,
1087 * create a separate file instead. */
1089 create_link(HANDLE h, const struct wim_dentry *dentry,
1090 struct win32_apply_ctx *ctx)
1092 if (ctx->common.supported_features.hard_links) {
1094 build_extraction_path(dentry, ctx);
1096 size_t bufsize = offsetof(FILE_LINK_INFORMATION, FileName) +
1097 ctx->pathbuf.Length + sizeof(wchar_t);
1098 u8 buf[bufsize] _aligned_attribute(8);
1099 FILE_LINK_INFORMATION *info = (FILE_LINK_INFORMATION *)buf;
1102 info->ReplaceIfExists = TRUE;
1103 info->RootDirectory = ctx->attr.RootDirectory;
1104 info->FileNameLength = ctx->pathbuf.Length;
1105 memcpy(info->FileName, ctx->pathbuf.Buffer, ctx->pathbuf.Length);
1106 info->FileName[info->FileNameLength / 2] = L'\0';
1108 /* Note: the null terminator isn't actually necessary,
1109 * but if you don't add the extra character, you get
1110 * STATUS_INFO_LENGTH_MISMATCH when FileNameLength
1111 * happens to be 2 */
1113 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1115 FileLinkInformation);
1116 if (NT_SUCCESS(status))
1118 ERROR("Failed to create link \"%ls\" (status=0x%08"PRIx32")",
1119 current_path(ctx), (u32)status);
1120 return WIMLIB_ERR_LINK;
1125 ret = create_nondirectory_inode(&h2, dentry, ctx);
1129 (*func_NtClose)(h2);
1134 /* Given an inode (represented by the open handle @h) for which one link has
1135 * been created (named by @first_dentry), create the other links.
1137 * Or, if the target volume does not support hard links, create separate files.
1139 * Note: This uses ctx->pathbuf and does not reset it.
1142 create_links(HANDLE h, const struct wim_dentry *first_dentry,
1143 struct win32_apply_ctx *ctx)
1145 const struct wim_inode *inode;
1146 const struct list_head *next;
1147 const struct wim_dentry *dentry;
1150 inode = first_dentry->d_inode;
1151 next = inode->i_extraction_aliases.next;
1153 dentry = list_entry(next, struct wim_dentry,
1154 d_extraction_alias_node);
1155 if (dentry != first_dentry) {
1156 ret = create_link(h, dentry, ctx);
1161 } while (next != &inode->i_extraction_aliases);
1165 /* Create a nondirectory file, including all links. */
1167 create_nondirectory(const struct wim_inode *inode, struct win32_apply_ctx *ctx)
1169 const struct wim_dentry *first_dentry;
1173 first_dentry = first_extraction_alias(inode);
1175 /* Create first link. */
1176 ret = create_nondirectory_inode(&h, first_dentry, ctx);
1180 /* Set short name. */
1181 ret = set_short_name(h, first_dentry, ctx);
1183 /* Create additional links, OR if hard links are not supported just
1184 * create more files. */
1186 ret = create_links(h, first_dentry, ctx);
1192 /* Create all the nondirectory files being extracted, including all aliases
1195 create_nondirectories(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1197 const struct wim_dentry *dentry;
1198 const struct wim_inode *inode;
1201 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1202 inode = dentry->d_inode;
1203 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1205 /* Call create_nondirectory() only once per inode */
1206 if (dentry != inode_first_extraction_dentry(inode))
1208 ret = create_nondirectory(inode, ctx);
1216 close_handles(struct win32_apply_ctx *ctx)
1218 for (unsigned i = 0; i < ctx->num_open_handles; i++)
1219 (*func_NtClose)(ctx->open_handles[i]);
1222 /* Prepare to read the next stream, which has size @stream_size, into an
1223 * in-memory buffer. */
1225 prepare_data_buffer(struct win32_apply_ctx *ctx, u64 stream_size)
1227 if (stream_size > ctx->data_buffer_size) {
1228 /* Larger buffer needed. */
1230 if ((size_t)stream_size != stream_size)
1231 return WIMLIB_ERR_NOMEM;
1232 new_buffer = REALLOC(ctx->data_buffer, stream_size);
1234 return WIMLIB_ERR_NOMEM;
1235 ctx->data_buffer = new_buffer;
1236 ctx->data_buffer_size = stream_size;
1238 /* On the first call this changes data_buffer_ptr from NULL, which tells
1239 * extract_chunk() that the data buffer needs to be filled while reading
1240 * the stream data. */
1241 ctx->data_buffer_ptr = ctx->data_buffer;
1246 begin_extract_stream_instance(const struct wim_lookup_table_entry *stream,
1247 struct wim_dentry *dentry,
1248 const wchar_t *stream_name,
1249 struct win32_apply_ctx *ctx)
1251 const struct wim_inode *inode = dentry->d_inode;
1252 size_t stream_name_nchars = 0;
1253 FILE_ALLOCATION_INFORMATION alloc_info;
1257 if (unlikely(stream_name))
1258 stream_name_nchars = wcslen(stream_name);
1260 if (unlikely(stream_name_nchars)) {
1261 build_extraction_path_with_ads(dentry, ctx,
1262 stream_name, stream_name_nchars);
1264 build_extraction_path(dentry, ctx);
1267 /* Reparse point? */
1268 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1269 && (stream_name_nchars == 0))
1271 if (!ctx->common.supported_features.reparse_points)
1274 /* We can't write the reparse stream directly; we must set it
1275 * with FSCTL_SET_REPARSE_POINT, which requires that all the
1276 * data be available. So, stage the data in a buffer. */
1278 list_add_tail(&dentry->tmp_list, &ctx->reparse_dentries);
1279 return prepare_data_buffer(ctx, stream->size);
1282 /* Encrypted file? */
1283 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)
1284 && (stream_name_nchars == 0))
1286 if (!ctx->common.supported_features.encrypted_files)
1289 /* We can't write encrypted file streams directly; we must use
1290 * WriteEncryptedFileRaw(), which requires providing the data
1291 * through a callback function. This can't easily be combined
1292 * with our own callback-based approach.
1294 * The current workaround is to simply read the stream into
1295 * memory and write the encrypted file from that.
1297 * TODO: This isn't sufficient for extremely large encrypted
1298 * files. Perhaps we should create an extra thread to write
1300 list_add_tail(&dentry->tmp_list, &ctx->encrypted_dentries);
1301 return prepare_data_buffer(ctx, stream->size);
1304 /* Extracting unnamed data stream in WIMBoot mode? */
1305 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)
1306 && (stream_name_nchars == 0)
1307 && (stream->resource_location == RESOURCE_IN_WIM)
1308 && (stream->rspec->wim == ctx->common.wim)
1309 && (stream->size == stream->rspec->uncompressed_size))
1311 int ret = calculate_dentry_full_path(dentry);
1314 if (in_prepopulate_list(dentry, ctx)) {
1315 union wimlib_progress_info info;
1317 info.wimboot_exclude.path_in_wim = dentry->_full_path;
1318 info.wimboot_exclude.extraction_path = current_path(ctx);
1320 ret = call_progress(ctx->common.progfunc,
1321 WIMLIB_PROGRESS_MSG_WIMBOOT_EXCLUDE,
1322 &info, ctx->common.progctx);
1323 FREE(dentry->_full_path);
1324 dentry->_full_path = NULL;
1327 /* Go on and open the file for normal extraction. */
1329 FREE(dentry->_full_path);
1330 dentry->_full_path = NULL;
1331 return wimboot_set_pointer(&ctx->attr,
1334 ctx->wimboot.data_source_id,
1335 ctx->wimboot.wim_lookup_table_hash,
1336 ctx->wimboot.wof_running);
1340 if (ctx->num_open_handles == MAX_OPEN_STREAMS) {
1341 /* XXX: Fix this. But because of the checks in
1342 * extract_stream_list(), this can now only happen on a
1343 * filesystem that does not support hard links. */
1344 ERROR("Can't extract data: too many open files!");
1345 return WIMLIB_ERR_UNSUPPORTED;
1348 /* Open a new handle */
1349 status = do_create_file(&h,
1350 FILE_WRITE_DATA | SYNCHRONIZE,
1351 NULL, 0, FILE_OPEN_IF,
1352 FILE_SEQUENTIAL_ONLY |
1353 FILE_SYNCHRONOUS_IO_NONALERT,
1355 if (!NT_SUCCESS(status)) {
1356 set_errno_from_nt_status(status);
1357 ERROR_WITH_ERRNO("Can't open \"%ls\" for writing "
1358 "(status=0x%08"PRIx32")",
1359 current_path(ctx), (u32)status);
1360 return WIMLIB_ERR_OPEN;
1363 ctx->open_handles[ctx->num_open_handles++] = h;
1365 /* Allocate space for the data. */
1366 alloc_info.AllocationSize.QuadPart = stream->size;
1367 (*func_NtSetInformationFile)(h, &ctx->iosb,
1368 &alloc_info, sizeof(alloc_info),
1369 FileAllocationInformation);
1373 /* Set the reparse data @rpbuf of length @rpbuflen on the extracted file
1374 * corresponding to the WIM dentry @dentry. */
1376 do_set_reparse_data(const struct wim_dentry *dentry,
1377 const void *rpbuf, u16 rpbuflen,
1378 struct win32_apply_ctx *ctx)
1383 status = create_file(&h, GENERIC_WRITE, NULL,
1384 0, FILE_OPEN, 0, dentry, ctx);
1385 if (!NT_SUCCESS(status))
1388 status = (*func_NtFsControlFile)(h, NULL, NULL, NULL,
1389 &ctx->iosb, FSCTL_SET_REPARSE_POINT,
1390 (void *)rpbuf, rpbuflen,
1394 if (NT_SUCCESS(status))
1397 /* On Windows, by default only the Administrator can create symbolic
1398 * links for some reason. By default we just issue a warning if this
1399 * appears to be the problem. Use WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS
1400 * to get a hard error. */
1401 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS)
1402 && (status == STATUS_PRIVILEGE_NOT_HELD ||
1403 status == STATUS_ACCESS_DENIED)
1404 && (dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1405 dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1407 WARNING("Can't create symbolic link \"%ls\"! \n"
1408 " (Need Administrator rights, or at least "
1410 " SeCreateSymbolicLink privilege.)",
1416 set_errno_from_nt_status(status);
1417 ERROR_WITH_ERRNO("Can't set reparse data on \"%ls\" "
1418 "(status=0x%08"PRIx32")",
1419 current_path(ctx), (u32)status);
1420 return WIMLIB_ERR_SET_REPARSE_DATA;
1423 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1424 * pointer to the suffix of the path that begins with the device directly, such
1425 * as e:\Windows\System32. */
1426 static const wchar_t *
1427 skip_nt_toplevel_component(const wchar_t *path, size_t path_nchars)
1429 static const wchar_t * const dirs[] = {
1434 size_t first_dir_len = 0;
1435 const wchar_t * const end = path + path_nchars;
1437 for (size_t i = 0; i < ARRAY_LEN(dirs); i++) {
1438 size_t len = wcslen(dirs[i]);
1439 if (len <= (end - path) && !wcsnicmp(path, dirs[i], len)) {
1440 first_dir_len = len;
1444 if (first_dir_len == 0)
1446 path += first_dir_len;
1447 while (path != end && *path == L'\\')
1452 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1453 * pointer to the suffix of the path that is device-relative, such as
1456 * The path has an explicit length and is not necessarily null terminated.
1458 * If the path just something like \??\e: then the returned pointer will point
1459 * just past the colon. In this case the length of the result will be 0
1461 static const wchar_t *
1462 get_device_relative_path(const wchar_t *path, size_t path_nchars)
1464 const wchar_t * const orig_path = path;
1465 const wchar_t * const end = path + path_nchars;
1467 path = skip_nt_toplevel_component(path, path_nchars);
1468 if (path == orig_path)
1471 path = wmemchr(path, L'\\', (end - path));
1476 } while (path != end && *path == L'\\');
1481 * Given a reparse point buffer for a symbolic link or junction, adjust its
1482 * contents so that the target of the link is consistent with the new location
1486 try_rpfix(u8 *rpbuf, u16 *rpbuflen_p, struct win32_apply_ctx *ctx)
1488 struct reparse_data rpdata;
1489 size_t orig_subst_name_nchars;
1490 const wchar_t *relpath;
1491 size_t relpath_nchars;
1492 size_t target_ntpath_nchars;
1493 size_t fixed_subst_name_nchars;
1494 const wchar_t *fixed_print_name;
1495 size_t fixed_print_name_nchars;
1497 if (parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata)) {
1498 /* Do nothing if the reparse data is invalid. */
1502 if (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
1503 (rpdata.rpflags & SYMBOLIC_LINK_RELATIVE))
1505 /* Do nothing if it's a relative symbolic link. */
1509 /* Build the new substitute name from the NT namespace path to the
1510 * target directory, then a path separator, then the "device relative"
1511 * part of the old substitute name. */
1513 orig_subst_name_nchars = rpdata.substitute_name_nbytes / sizeof(wchar_t);
1515 relpath = get_device_relative_path(rpdata.substitute_name,
1516 orig_subst_name_nchars);
1517 relpath_nchars = orig_subst_name_nchars -
1518 (relpath - rpdata.substitute_name);
1520 target_ntpath_nchars = ctx->target_ntpath.Length / sizeof(wchar_t);
1522 fixed_subst_name_nchars = target_ntpath_nchars;
1524 fixed_subst_name_nchars += 1 + relpath_nchars;
1525 wchar_t fixed_subst_name[fixed_subst_name_nchars];
1527 wmemcpy(fixed_subst_name, ctx->target_ntpath.Buffer,
1528 target_ntpath_nchars);
1529 if (relpath_nchars) {
1530 fixed_subst_name[target_ntpath_nchars] = L'\\';
1531 wmemcpy(&fixed_subst_name[target_ntpath_nchars + 1],
1532 relpath, relpath_nchars);
1534 /* Doesn't need to be null-terminated. */
1536 /* Print name should be Win32, but not all NT names can even be
1537 * translated to Win32 names. But we can at least delete the top-level
1538 * directory, such as \??\, and this will have the expected result in
1539 * the usual case. */
1540 fixed_print_name = skip_nt_toplevel_component(fixed_subst_name,
1541 fixed_subst_name_nchars);
1542 fixed_print_name_nchars = fixed_subst_name_nchars - (fixed_print_name -
1545 rpdata.substitute_name = fixed_subst_name;
1546 rpdata.substitute_name_nbytes = fixed_subst_name_nchars * sizeof(wchar_t);
1547 rpdata.print_name = (wchar_t *)fixed_print_name;
1548 rpdata.print_name_nbytes = fixed_print_name_nchars * sizeof(wchar_t);
1549 make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
1552 /* Sets reparse data on the specified file. This handles "fixing" the targets
1553 * of absolute symbolic links and junctions if WIMLIB_EXTRACT_FLAG_RPFIX was
1556 set_reparse_data(const struct wim_dentry *dentry,
1557 const void *_rpbuf, u16 rpbuflen, struct win32_apply_ctx *ctx)
1559 const struct wim_inode *inode = dentry->d_inode;
1560 const void *rpbuf = _rpbuf;
1562 if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
1563 && !inode->i_not_rpfixed
1564 && (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1565 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1567 memcpy(&ctx->rpfixbuf, _rpbuf, rpbuflen);
1568 try_rpfix((u8 *)&ctx->rpfixbuf, &rpbuflen, ctx);
1569 rpbuf = &ctx->rpfixbuf;
1571 return do_set_reparse_data(dentry, rpbuf, rpbuflen, ctx);
1575 /* Import the next block of raw encrypted data */
1577 import_encrypted_data(PBYTE pbData, PVOID pvCallbackContext, PULONG Length)
1579 struct win32_apply_ctx *ctx = pvCallbackContext;
1582 copy_len = min(ctx->encrypted_size - ctx->encrypted_offset, *Length);
1583 memcpy(pbData, &ctx->data_buffer[ctx->encrypted_offset], copy_len);
1584 ctx->encrypted_offset += copy_len;
1586 return ERROR_SUCCESS;
1589 /* Write the raw encrypted data to the already-created file corresponding to
1592 * The raw encrypted data is provided in ctx->data_buffer, and its size is
1593 * ctx->encrypted_size. */
1595 extract_encrypted_file(const struct wim_dentry *dentry,
1596 struct win32_apply_ctx *ctx)
1601 /* Temporarily build a Win32 path for OpenEncryptedFileRaw() */
1602 build_win32_extraction_path(dentry, ctx);
1604 err = OpenEncryptedFileRaw(ctx->pathbuf.Buffer,
1605 CREATE_FOR_IMPORT, &rawctx);
1607 /* Restore the NT namespace path */
1608 build_extraction_path(dentry, ctx);
1610 if (err != ERROR_SUCCESS) {
1611 set_errno_from_win32_error(err);
1612 ERROR_WITH_ERRNO("Can't open \"%ls\" for encrypted import "
1613 "(err=%"PRIu32")", current_path(ctx), (u32)err);
1614 return WIMLIB_ERR_OPEN;
1617 ctx->encrypted_offset = 0;
1619 err = WriteEncryptedFileRaw(import_encrypted_data, ctx, rawctx);
1621 CloseEncryptedFileRaw(rawctx);
1623 if (err != ERROR_SUCCESS) {
1624 set_errno_from_win32_error(err);
1625 ERROR_WITH_ERRNO("Can't import encrypted file \"%ls\" "
1626 "(err=%"PRIu32")", current_path(ctx), (u32)err);
1627 return WIMLIB_ERR_WRITE;
1633 /* Called when starting to read a stream for extraction on Windows */
1635 begin_extract_stream(struct wim_lookup_table_entry *stream,
1636 u32 flags, void *_ctx)
1638 struct win32_apply_ctx *ctx = _ctx;
1639 const struct stream_owner *owners = stream_owners(stream);
1642 ctx->num_open_handles = 0;
1643 ctx->data_buffer_ptr = NULL;
1644 INIT_LIST_HEAD(&ctx->reparse_dentries);
1645 INIT_LIST_HEAD(&ctx->encrypted_dentries);
1647 for (u32 i = 0; i < stream->out_refcnt; i++) {
1648 const struct wim_inode *inode = owners[i].inode;
1649 const wchar_t *stream_name = owners[i].stream_name;
1650 struct wim_dentry *dentry;
1652 /* A copy of the stream needs to be extracted to @inode. */
1654 if (ctx->common.supported_features.hard_links) {
1655 dentry = inode_first_extraction_dentry(inode);
1656 ret = begin_extract_stream_instance(stream, dentry,
1661 /* Hard links not supported. Extract the stream
1662 * separately to each alias of the inode. */
1663 struct list_head *next;
1665 next = inode->i_extraction_aliases.next;
1667 dentry = list_entry(next, struct wim_dentry,
1668 d_extraction_alias_node);
1669 ret = begin_extract_stream_instance(stream,
1676 } while (next != &inode->i_extraction_aliases);
1687 /* Called when the next chunk of a stream has been read for extraction on
1690 extract_chunk(const void *chunk, size_t size, void *_ctx)
1692 struct win32_apply_ctx *ctx = _ctx;
1694 /* Write the data chunk to each open handle */
1695 for (unsigned i = 0; i < ctx->num_open_handles; i++) {
1696 u8 *bufptr = (u8 *)chunk;
1697 size_t bytes_remaining = size;
1699 while (bytes_remaining) {
1700 ULONG count = min(0xFFFFFFFF, bytes_remaining);
1702 status = (*func_NtWriteFile)(ctx->open_handles[i],
1704 &ctx->iosb, bufptr, count,
1706 if (!NT_SUCCESS(status)) {
1707 set_errno_from_nt_status(status);
1708 ERROR_WITH_ERRNO("Error writing data to target "
1709 "volume (status=0x%08"PRIx32")",
1711 return WIMLIB_ERR_WRITE;
1713 bufptr += ctx->iosb.Information;
1714 bytes_remaining -= ctx->iosb.Information;
1718 /* Copy the data chunk into the buffer (if needed) */
1719 if (ctx->data_buffer_ptr)
1720 ctx->data_buffer_ptr = mempcpy(ctx->data_buffer_ptr,
1725 /* Called when a stream has been fully read for extraction on Windows */
1727 end_extract_stream(struct wim_lookup_table_entry *stream, int status, void *_ctx)
1729 struct win32_apply_ctx *ctx = _ctx;
1731 const struct wim_dentry *dentry;
1738 if (likely(!ctx->data_buffer_ptr))
1741 if (!list_empty(&ctx->reparse_dentries)) {
1742 if (stream->size > REPARSE_DATA_MAX_SIZE) {
1743 dentry = list_first_entry(&ctx->reparse_dentries,
1744 struct wim_dentry, tmp_list);
1745 build_extraction_path(dentry, ctx);
1746 ERROR("Reparse data of \"%ls\" has size "
1747 "%"PRIu64" bytes (exceeds %u bytes)",
1748 current_path(ctx), stream->size,
1749 REPARSE_DATA_MAX_SIZE);
1750 return WIMLIB_ERR_INVALID_REPARSE_DATA;
1752 /* In the WIM format, reparse streams are just the reparse data
1753 * and omit the header. But we can reconstruct the header. */
1754 memcpy(ctx->rpbuf.rpdata, ctx->data_buffer, stream->size);
1755 ctx->rpbuf.rpdatalen = stream->size;
1756 ctx->rpbuf.rpreserved = 0;
1757 list_for_each_entry(dentry, &ctx->reparse_dentries, tmp_list) {
1758 ctx->rpbuf.rptag = dentry->d_inode->i_reparse_tag;
1759 ret = set_reparse_data(dentry, &ctx->rpbuf,
1760 stream->size + REPARSE_DATA_OFFSET,
1767 if (!list_empty(&ctx->encrypted_dentries)) {
1768 ctx->encrypted_size = stream->size;
1769 list_for_each_entry(dentry, &ctx->encrypted_dentries, tmp_list) {
1770 ret = extract_encrypted_file(dentry, ctx);
1779 /* Attributes that can't be set directly */
1780 #define SPECIAL_ATTRIBUTES \
1781 (FILE_ATTRIBUTE_REPARSE_POINT | \
1782 FILE_ATTRIBUTE_DIRECTORY | \
1783 FILE_ATTRIBUTE_ENCRYPTED | \
1784 FILE_ATTRIBUTE_SPARSE_FILE | \
1785 FILE_ATTRIBUTE_COMPRESSED)
1787 /* Set the security descriptor @desc, of @desc_size bytes, on the file with open
1790 set_security_descriptor(HANDLE h, const void *desc,
1791 size_t desc_size, struct win32_apply_ctx *ctx)
1793 SECURITY_INFORMATION info;
1796 /* We really just want to set entire the security descriptor as-is, but
1797 * all available APIs require specifying the specific parts of the
1798 * descriptor being set. Start out by requesting all parts be set. If
1799 * permissions problems are encountered, fall back to omitting some
1800 * parts (first the SACL, then the DACL, then the owner), unless the
1801 * WIMLIB_EXTRACT_FLAG_STRICT_ACLS flag has been enabled. */
1802 info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
1803 DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION;
1805 /* Prefer NtSetSecurityObject() to SetFileSecurity(). SetFileSecurity()
1806 * itself necessarily uses NtSetSecurityObject() as the latter is the
1807 * underlying system call for setting security information, but
1808 * SetFileSecurity() opens the handle with NtCreateFile() without
1809 * FILE_OPEN_FILE_BACKUP_INTENT. Hence, access checks are done and due
1810 * to the Windows security model, even a process running as the
1811 * Administrator can have access denied. (Of course, this not mentioned
1812 * in the MS "documentation".) */
1814 status = (*func_NtSetSecurityObject)(h, info, (PSECURITY_DESCRIPTOR)desc);
1815 if (NT_SUCCESS(status))
1817 /* Failed to set the requested parts of the security descriptor. If the
1818 * error was permissions-related, try to set fewer parts of the security
1819 * descriptor, unless WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled. */
1820 if ((status == STATUS_PRIVILEGE_NOT_HELD ||
1821 status == STATUS_ACCESS_DENIED) &&
1822 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
1824 if (info & SACL_SECURITY_INFORMATION) {
1825 info &= ~SACL_SECURITY_INFORMATION;
1826 ctx->partial_security_descriptors++;
1829 if (info & DACL_SECURITY_INFORMATION) {
1830 info &= ~DACL_SECURITY_INFORMATION;
1833 if (info & OWNER_SECURITY_INFORMATION) {
1834 info &= ~OWNER_SECURITY_INFORMATION;
1837 /* Nothing left except GROUP, and if we removed it we
1838 * wouldn't have anything at all. */
1841 /* No part of the security descriptor could be set, or
1842 * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled and the full security
1843 * descriptor could not be set. */
1844 if (!(info & SACL_SECURITY_INFORMATION))
1845 ctx->partial_security_descriptors--;
1846 ctx->no_security_descriptors++;
1850 /* Set metadata on the open file @h from the WIM inode @inode. */
1852 do_apply_metadata_to_file(HANDLE h, const struct wim_inode *inode,
1853 struct win32_apply_ctx *ctx)
1855 FILE_BASIC_INFORMATION info;
1858 /* Set security descriptor if present and not in NO_ACLS mode */
1859 if (inode->i_security_id >= 0 &&
1860 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
1862 const struct wim_security_data *sd;
1866 sd = wim_get_current_security_data(ctx->common.wim);
1867 desc = sd->descriptors[inode->i_security_id];
1868 desc_size = sd->sizes[inode->i_security_id];
1870 status = set_security_descriptor(h, desc, desc_size, ctx);
1871 if (!NT_SUCCESS(status) &&
1872 (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
1874 set_errno_from_nt_status(status);
1875 ERROR_WITH_ERRNO("Can't set security descriptor "
1876 "on \"%ls\" (status=0x%08"PRIx32")",
1877 current_path(ctx), (u32)status);
1878 return WIMLIB_ERR_SET_SECURITY;
1882 /* Set attributes and timestamps */
1883 info.CreationTime.QuadPart = inode->i_creation_time;
1884 info.LastAccessTime.QuadPart = inode->i_last_access_time;
1885 info.LastWriteTime.QuadPart = inode->i_last_write_time;
1886 info.ChangeTime.QuadPart = 0;
1887 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
1888 info.FileAttributes = 0;
1890 info.FileAttributes = inode->i_attributes & ~SPECIAL_ATTRIBUTES;
1892 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1893 &info, sizeof(info),
1894 FileBasicInformation);
1895 /* On FAT volumes we get STATUS_INVALID_PARAMETER if we try to set
1896 * attributes on the root directory. (Apparently because FAT doesn't
1897 * actually have a place to store those attributes!) */
1898 if (!NT_SUCCESS(status)
1899 && !(status == STATUS_INVALID_PARAMETER &&
1900 dentry_is_root(inode_first_extraction_dentry(inode))))
1902 set_errno_from_nt_status(status);
1903 ERROR_WITH_ERRNO("Can't set basic metadata on \"%ls\" "
1904 "(status=0x%08"PRIx32")",
1905 current_path(ctx), (u32)status);
1906 return WIMLIB_ERR_SET_ATTRIBUTES;
1913 apply_metadata_to_file(const struct wim_dentry *dentry,
1914 struct win32_apply_ctx *ctx)
1916 const struct wim_inode *inode = dentry->d_inode;
1922 perms = FILE_WRITE_ATTRIBUTES | WRITE_DAC |
1923 WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
1925 build_extraction_path(dentry, ctx);
1927 /* Open a handle with as many relevant permissions as possible. */
1928 while (!NT_SUCCESS(status = do_create_file(&h, perms, NULL,
1929 0, FILE_OPEN, 0, ctx)))
1931 if (status == STATUS_PRIVILEGE_NOT_HELD ||
1932 status == STATUS_ACCESS_DENIED)
1934 if (perms & ACCESS_SYSTEM_SECURITY) {
1935 perms &= ~ACCESS_SYSTEM_SECURITY;
1938 if (perms & WRITE_DAC) {
1939 perms &= ~WRITE_DAC;
1942 if (perms & WRITE_OWNER) {
1943 perms &= ~WRITE_OWNER;
1947 set_errno_from_nt_status(status);
1948 ERROR_WITH_ERRNO("Can't open \"%ls\" to set metadata "
1949 "(status=0x%08"PRIx32")",
1950 current_path(ctx), (u32)status);
1951 return WIMLIB_ERR_OPEN;
1954 ret = do_apply_metadata_to_file(h, inode, ctx);
1962 apply_metadata(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1964 const struct wim_dentry *dentry;
1967 /* We go in reverse so that metadata is set on all a directory's
1968 * children before the directory itself. This avoids any potential
1969 * problems with attributes, timestamps, or security descriptors. */
1970 list_for_each_entry_reverse(dentry, dentry_list, d_extraction_list_node)
1972 ret = apply_metadata_to_file(dentry, ctx);
1979 /* Issue warnings about problems during the extraction for which warnings were
1980 * not already issued (due to the high number of potential warnings if we issued
1981 * them per-file). */
1983 do_warnings(const struct win32_apply_ctx *ctx)
1985 if (ctx->partial_security_descriptors == 0 &&
1986 ctx->no_security_descriptors == 0)
1989 WARNING("Extraction to \"%ls\" complete, but with one or more warnings:",
1990 ctx->common.target);
1991 if (ctx->partial_security_descriptors != 0) {
1992 WARNING("- Could only partially set the security descriptor\n"
1993 " on %lu files or directories.",
1994 ctx->partial_security_descriptors);
1996 if (ctx->no_security_descriptors != 0) {
1997 WARNING("- Could not set security descriptor at all\n"
1998 " on %lu files or directories.",
1999 ctx->no_security_descriptors);
2001 WARNING("To fully restore all security descriptors, run the program\n"
2002 " with Administrator rights.");
2005 /* Extract files from a WIM image to a directory on Windows */
2007 win32_extract(struct list_head *dentry_list, struct apply_ctx *_ctx)
2010 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
2012 ret = prepare_target(dentry_list, ctx);
2016 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT) {
2017 ret = start_wimboot_extraction(ctx);
2022 ret = create_directories(dentry_list, ctx);
2026 ret = create_nondirectories(dentry_list, ctx);
2030 struct read_stream_list_callbacks cbs = {
2031 .begin_stream = begin_extract_stream,
2032 .begin_stream_ctx = ctx,
2033 .consume_chunk = extract_chunk,
2034 .consume_chunk_ctx = ctx,
2035 .end_stream = end_extract_stream,
2036 .end_stream_ctx = ctx,
2038 ret = extract_stream_list(&ctx->common, &cbs);
2042 ret = apply_metadata(dentry_list, ctx);
2049 (*func_NtClose)(ctx->h_target);
2050 if (ctx->target_ntpath.Buffer)
2051 HeapFree(GetProcessHeap(), 0, ctx->target_ntpath.Buffer);
2052 FREE(ctx->pathbuf.Buffer);
2053 FREE(ctx->print_buffer);
2054 if (ctx->wimboot.prepopulate_pats) {
2055 FREE(ctx->wimboot.prepopulate_pats->strings);
2056 FREE(ctx->wimboot.prepopulate_pats);
2058 FREE(ctx->wimboot.mem_prepopulate_pats);
2059 FREE(ctx->data_buffer);
2063 const struct apply_operations win32_apply_ops = {
2065 .get_supported_features = win32_get_supported_features,
2066 .extract = win32_extract,
2067 .context_size = sizeof(struct win32_apply_ctx),
2070 #endif /* __WIN32__ */