2 * win32_apply.c - Windows-specific code for applying files from a WIM image.
6 * Copyright (C) 2013, 2014 Eric Biggers
8 * This file is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU Lesser General Public License as published by the Free
10 * Software Foundation; either version 3 of the License, or (at your option) any
13 * This file is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this file; if not, see http://www.gnu.org/licenses/.
28 #include "wimlib/win32_common.h"
30 #include "wimlib/apply.h"
31 #include "wimlib/assert.h"
32 #include "wimlib/capture.h" /* for mangle_pat() and match_pattern_list() */
33 #include "wimlib/dentry.h"
34 #include "wimlib/error.h"
35 #include "wimlib/lookup_table.h"
36 #include "wimlib/metadata.h"
37 #include "wimlib/paths.h"
38 #include "wimlib/reparse.h"
39 #include "wimlib/textfile.h"
40 #include "wimlib/xml.h"
41 #include "wimlib/wildcard.h"
42 #include "wimlib/wimboot.h"
44 struct win32_apply_ctx {
46 /* Extract flags, the pointer to the WIMStruct, etc. */
47 struct apply_ctx common;
49 /* WIMBoot information, only filled in if WIMLIB_EXTRACT_FLAG_WIMBOOT
53 struct string_set *prepopulate_pats;
54 void *mem_prepopulate_pats;
55 u8 wim_lookup_table_hash[SHA1_HASH_SIZE];
57 bool tried_to_load_prepopulate_list;
60 /* Open handle to the target directory */
63 /* NT namespace path to the target directory (buffer allocated) */
64 UNICODE_STRING target_ntpath;
66 /* Temporary buffer for building paths (buffer allocated) */
67 UNICODE_STRING pathbuf;
69 /* Object attributes to reuse for opening files in the target directory.
70 * (attr.ObjectName == &pathbuf) and (attr.RootDirectory == h_target).
72 OBJECT_ATTRIBUTES attr;
74 /* Temporary I/O status block for system calls */
77 /* Allocated buffer for creating "printable" paths from our
78 * target-relative NT paths */
79 wchar_t *print_buffer;
81 /* Allocated buffer for reading stream data when it cannot be extracted
85 /* Pointer to the next byte in @data_buffer to fill */
88 /* Size allocated in @data_buffer */
89 size_t data_buffer_size;
91 /* Current offset in the raw encrypted file being written */
92 size_t encrypted_offset;
94 /* Current size of the raw encrypted file being written */
95 size_t encrypted_size;
97 /* Temporary buffer for reparse data */
98 struct reparse_buffer_disk rpbuf;
100 /* Temporary buffer for reparse data of "fixed" absolute symbolic links
102 struct reparse_buffer_disk rpfixbuf;
104 /* Array of open handles to filesystem streams currently being written
106 HANDLE open_handles[MAX_OPEN_STREAMS];
108 /* Number of handles in @open_handles currently open (filled in from the
109 * beginning of the array) */
110 unsigned num_open_handles;
112 /* List of dentries, joined by @tmp_list, that need to have reparse data
113 * extracted as soon as the whole stream has been read into
115 struct list_head reparse_dentries;
117 /* List of dentries, joined by @tmp_list, that need to have raw
118 * encrypted data extracted as soon as the whole stream has been read
119 * into @data_buffer. */
120 struct list_head encrypted_dentries;
122 /* Number of files for which we didn't have permission to set the full
123 * security descriptor. */
124 unsigned long partial_security_descriptors;
126 /* Number of files for which we didn't have permission to set any part
127 * of the security descriptor. */
128 unsigned long no_security_descriptors;
130 /* Number of files for which we couldn't set the short name. */
131 unsigned long num_set_short_name_failures;
133 /* Number of files for which we couldn't remove the short name. */
134 unsigned long num_remove_short_name_failures;
136 /* Have we tried to enable short name support on the target volume yet?
138 bool tried_to_enable_short_names;
141 /* Get the drive letter from a Windows path, or return the null character if the
142 * path is relative. */
144 get_drive_letter(const wchar_t *path)
146 /* Skip \\?\ prefix */
147 if (!wcsncmp(path, L"\\\\?\\", 4))
150 /* Return drive letter if valid */
151 if (((path[0] >= L'a' && path[0] <= L'z') ||
152 (path[0] >= L'A' && path[0] <= L'Z')) && path[1] == L':')
159 get_vol_flags(const wchar_t *target, DWORD *vol_flags_ret,
160 bool *short_names_supported_ret)
162 wchar_t filesystem_name[MAX_PATH + 1];
164 wchar_t *volume = NULL;
167 *short_names_supported_ret = false;
169 drive[0] = get_drive_letter(target);
177 if (!GetVolumeInformation(volume, NULL, 0, NULL, NULL,
178 vol_flags_ret, filesystem_name,
179 ARRAY_LEN(filesystem_name)))
181 DWORD err = GetLastError();
182 set_errno_from_win32_error(err);
183 WARNING_WITH_ERRNO("Failed to get volume information for "
184 "\"%ls\" (err=%"PRIu32")",
189 if (wcsstr(filesystem_name, L"NTFS")) {
190 /* FILE_SUPPORTS_HARD_LINKS is only supported on Windows 7 and
191 * later. Force it on anyway if filesystem is NTFS. */
192 *vol_flags_ret |= FILE_SUPPORTS_HARD_LINKS;
194 /* There's no volume flag for short names, but according to the
195 * MS documentation they are only user-settable on NTFS. */
196 *short_names_supported_ret = true;
200 static const wchar_t *
201 current_path(struct win32_apply_ctx *ctx);
204 build_extraction_path(const struct wim_dentry *dentry,
205 struct win32_apply_ctx *ctx);
208 report_dentry_apply_error(const struct wim_dentry *dentry,
209 struct win32_apply_ctx *ctx, int ret)
211 build_extraction_path(dentry, ctx);
212 return report_apply_error(&ctx->common, ret, current_path(ctx));
216 check_apply_error(const struct wim_dentry *dentry,
217 struct win32_apply_ctx *ctx, int ret)
220 ret = report_dentry_apply_error(dentry, ctx, ret);
225 win32_get_supported_features(const wchar_t *target,
226 struct wim_features *supported_features)
229 bool short_names_supported;
231 /* Query the features of the target volume. */
233 get_vol_flags(target, &vol_flags, &short_names_supported);
235 supported_features->archive_files = 1;
236 supported_features->hidden_files = 1;
237 supported_features->system_files = 1;
239 if (vol_flags & FILE_FILE_COMPRESSION)
240 supported_features->compressed_files = 1;
242 if (vol_flags & FILE_SUPPORTS_ENCRYPTION) {
243 supported_features->encrypted_files = 1;
244 supported_features->encrypted_directories = 1;
247 supported_features->not_context_indexed_files = 1;
249 /* Don't do anything with FILE_SUPPORTS_SPARSE_FILES. */
251 if (vol_flags & FILE_NAMED_STREAMS)
252 supported_features->named_data_streams = 1;
254 if (vol_flags & FILE_SUPPORTS_HARD_LINKS)
255 supported_features->hard_links = 1;
257 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS)
258 supported_features->reparse_points = 1;
260 if (vol_flags & FILE_PERSISTENT_ACLS)
261 supported_features->security_descriptors = 1;
263 if (short_names_supported)
264 supported_features->short_names = 1;
266 supported_features->timestamps = 1;
268 /* Note: Windows does not support case sensitive filenames! At least
269 * not without changing the registry and rebooting... */
274 /* Load the patterns from [PrepopulateList] of WimBootCompress.ini in the WIM
275 * image being extracted. */
277 load_prepopulate_pats(struct win32_apply_ctx *ctx)
279 const wchar_t *path = L"\\Windows\\System32\\WimBootCompress.ini";
280 struct wim_dentry *dentry;
281 struct wim_lookup_table_entry *lte;
284 struct string_set *s;
286 struct text_file_section sec;
288 ctx->wimboot.tried_to_load_prepopulate_list = true;
290 dentry = get_dentry(ctx->common.wim, path, WIMLIB_CASE_INSENSITIVE);
292 (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
293 FILE_ATTRIBUTE_REPARSE_POINT |
294 FILE_ATTRIBUTE_ENCRYPTED)) ||
295 !(lte = inode_unnamed_lte(dentry->d_inode, ctx->common.wim->lookup_table)))
297 WARNING("%ls does not exist in WIM image!", path);
298 return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
301 ret = read_full_stream_into_alloc_buf(lte, &buf);
305 s = CALLOC(1, sizeof(struct string_set));
308 return WIMLIB_ERR_NOMEM;
311 sec.name = T("PrepopulateList");
314 ret = do_load_text_file(path, buf, lte->size, &mem, &sec, 1,
315 LOAD_TEXT_FILE_REMOVE_QUOTES |
316 LOAD_TEXT_FILE_NO_WARNINGS,
318 BUILD_BUG_ON(OS_PREFERRED_PATH_SEPARATOR != WIM_PATH_SEPARATOR);
324 ctx->wimboot.prepopulate_pats = s;
325 ctx->wimboot.mem_prepopulate_pats = mem;
329 /* Returns %true if the specified absolute path to a file in the WIM image
330 * matches a pattern in [PrepopulateList] of WimBootCompress.ini. Otherwise
333 in_prepopulate_list(const wchar_t *path, size_t path_nchars,
334 const struct win32_apply_ctx *ctx)
336 const struct string_set *pats = ctx->wimboot.prepopulate_pats;
338 if (!pats || !pats->num_strings)
341 return match_pattern_list(path, path_nchars, pats);
344 /* Returns %true if the specified absolute path to a file in the WIM image can
345 * be subject to external backing when extracted. Otherwise returns %false. */
347 can_externally_back_path(const wchar_t *path, size_t path_nchars,
348 const struct win32_apply_ctx *ctx)
350 if (in_prepopulate_list(path, path_nchars, ctx))
353 /* Since we attempt to modify the SYSTEM registry after it's extracted
354 * (see end_wimboot_extraction()), it can't be extracted as externally
355 * backed. This extends to associated files such as SYSTEM.LOG that
356 * also must be writable in order to write to the registry. Normally,
357 * SYSTEM is in [PrepopulateList], and the SYSTEM.* files match patterns
358 * in [ExclusionList] and therefore are not captured in the WIM at all.
359 * However, a WIM that wasn't specifically captured in "WIMBoot mode"
360 * may contain SYSTEM.* files. So to make things "just work", hard-code
362 if (match_path(path, path_nchars, L"\\Windows\\System32\\config\\SYSTEM*",
363 OS_PREFERRED_PATH_SEPARATOR, false))
369 #define WIM_BACKING_NOT_ENABLED -1
370 #define WIM_BACKING_NOT_POSSIBLE -2
371 #define WIM_BACKING_EXCLUDED -3
374 will_externally_back_inode(struct wim_inode *inode, struct win32_apply_ctx *ctx,
375 const struct wim_dentry **excluded_dentry_ret)
377 struct list_head *next;
378 struct wim_dentry *dentry;
379 struct wim_lookup_table_entry *stream;
382 if (inode->i_can_externally_back)
385 /* This may do redundant checks because the cached value
386 * i_can_externally_back is 2-state (as opposed to 3-state:
387 * unknown/no/yes). But most files can be externally backed, so this
390 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
391 FILE_ATTRIBUTE_REPARSE_POINT |
392 FILE_ATTRIBUTE_ENCRYPTED))
393 return WIM_BACKING_NOT_POSSIBLE;
395 stream = inode_unnamed_lte_resolved(inode);
398 stream->resource_location != RESOURCE_IN_WIM ||
399 stream->rspec->wim != ctx->common.wim ||
400 stream->size != stream->rspec->uncompressed_size)
401 return WIM_BACKING_NOT_POSSIBLE;
404 * We need to check the patterns in [PrepopulateList] against every name
405 * of the inode, in case any of them match.
407 next = inode->i_extraction_aliases.next;
409 dentry = list_entry(next, struct wim_dentry,
410 d_extraction_alias_node);
412 ret = calculate_dentry_full_path(dentry);
416 if (!can_externally_back_path(dentry->_full_path,
417 wcslen(dentry->_full_path), ctx))
419 if (excluded_dentry_ret)
420 *excluded_dentry_ret = dentry;
421 return WIM_BACKING_EXCLUDED;
424 } while (next != &inode->i_extraction_aliases);
426 inode->i_can_externally_back = 1;
431 * Determines if the unnamed data stream of a file will be created as an
432 * external backing, as opposed to a standard extraction.
435 win32_will_externally_back(struct wim_dentry *dentry, struct apply_ctx *_ctx)
437 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
439 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
440 return WIM_BACKING_NOT_ENABLED;
442 if (!ctx->wimboot.tried_to_load_prepopulate_list)
443 if (load_prepopulate_pats(ctx) == WIMLIB_ERR_NOMEM)
444 return WIMLIB_ERR_NOMEM;
446 return will_externally_back_inode(dentry->d_inode, ctx, NULL);
450 set_external_backing(HANDLE h, struct wim_inode *inode, struct win32_apply_ctx *ctx)
453 const struct wim_dentry *excluded_dentry;
455 ret = will_externally_back_inode(inode, ctx, &excluded_dentry);
456 if (ret > 0) /* Error. */
459 if (ret < 0 && ret != WIM_BACKING_EXCLUDED)
460 return 0; /* Not externally backing, other than due to exclusion. */
462 if (unlikely(ret == WIM_BACKING_EXCLUDED)) {
463 /* Not externally backing due to exclusion. */
464 union wimlib_progress_info info;
466 build_extraction_path(excluded_dentry, ctx);
468 info.wimboot_exclude.path_in_wim = excluded_dentry->_full_path;
469 info.wimboot_exclude.extraction_path = current_path(ctx);
471 return call_progress(ctx->common.progfunc,
472 WIMLIB_PROGRESS_MSG_WIMBOOT_EXCLUDE,
473 &info, ctx->common.progctx);
475 /* Externally backing. */
476 if (unlikely(!wimboot_set_pointer(h,
477 inode_unnamed_lte_resolved(inode),
478 ctx->wimboot.data_source_id,
479 ctx->wimboot.wim_lookup_table_hash,
480 ctx->wimboot.wof_running)))
482 const DWORD err = GetLastError();
484 build_extraction_path(inode_first_extraction_dentry(inode), ctx);
485 set_errno_from_win32_error(err);
486 ERROR_WITH_ERRNO("\"%ls\": Couldn't set WIMBoot "
487 "pointer data (err=%"PRIu32")",
488 current_path(ctx), (u32)err);
489 return WIMLIB_ERR_WIMBOOT;
495 /* Calculates the SHA-1 message digest of the WIM's lookup table. */
497 hash_lookup_table(WIMStruct *wim, u8 hash[SHA1_HASH_SIZE])
499 return wim_reshdr_to_hash(&wim->hdr.lookup_table_reshdr, wim, hash);
502 /* Prepare for doing a "WIMBoot" extraction by loading patterns from
503 * [PrepopulateList] of WimBootCompress.ini and allocating a WOF data source ID
504 * on the target volume. */
506 start_wimboot_extraction(struct win32_apply_ctx *ctx)
509 WIMStruct *wim = ctx->common.wim;
511 if (!ctx->wimboot.tried_to_load_prepopulate_list)
512 if (load_prepopulate_pats(ctx) == WIMLIB_ERR_NOMEM)
513 return WIMLIB_ERR_NOMEM;
515 if (!wim_info_get_wimboot(wim->wim_info, wim->current_image))
516 WARNING("Image is not marked as WIMBoot compatible!");
518 ret = hash_lookup_table(ctx->common.wim,
519 ctx->wimboot.wim_lookup_table_hash);
523 return wimboot_alloc_data_source_id(wim->filename,
527 &ctx->wimboot.data_source_id,
528 &ctx->wimboot.wof_running);
532 build_win32_extraction_path(const struct wim_dentry *dentry,
533 struct win32_apply_ctx *ctx);
535 /* Sets WimBoot=1 in the extracted SYSTEM registry hive.
537 * WIMGAPI does this, and it's possible that it's important.
538 * But I don't know exactly what this value means to Windows. */
540 end_wimboot_extraction(struct win32_apply_ctx *ctx)
542 struct wim_dentry *dentry;
543 wchar_t subkeyname[32];
549 dentry = get_dentry(ctx->common.wim, L"\\Windows\\System32\\config\\SYSTEM",
550 WIMLIB_CASE_INSENSITIVE);
552 if (!dentry || !will_extract_dentry(dentry))
555 if (!will_extract_dentry(wim_get_current_root_dentry(ctx->common.wim)))
558 /* Not bothering to use the native routines (e.g. NtLoadKey()) for this.
559 * If this doesn't work, you probably also have many other problems. */
561 build_win32_extraction_path(dentry, ctx);
563 randomize_char_array_with_alnum(subkeyname, 20);
564 subkeyname[20] = L'\0';
566 res = RegLoadKey(HKEY_LOCAL_MACHINE, subkeyname, ctx->pathbuf.Buffer);
570 wcscpy(&subkeyname[20], L"\\Setup");
572 res = RegCreateKeyEx(HKEY_LOCAL_MACHINE, subkeyname, 0, NULL,
573 REG_OPTION_BACKUP_RESTORE, 0, NULL, &key, NULL);
579 res = RegSetValueEx(key, L"WimBoot", 0, REG_DWORD,
580 (const BYTE *)&value, sizeof(DWORD));
584 res = RegFlushKey(key);
587 res2 = RegCloseKey(key);
591 subkeyname[20] = L'\0';
592 RegUnLoadKey(HKEY_LOCAL_MACHINE, subkeyname);
596 set_errno_from_win32_error(res);
597 WARNING_WITH_ERRNO("Failed to set \\Setup: dword \"WimBoot\"=1 value "
598 "in registry hive \"%ls\" (err=%"PRIu32")",
599 ctx->pathbuf.Buffer, (u32)res);
605 /* Returns the number of wide characters needed to represent the path to the
606 * specified @dentry, relative to the target directory, when extracted.
608 * Does not include null terminator (not needed for NtCreateFile). */
610 dentry_extraction_path_length(const struct wim_dentry *dentry)
613 const struct wim_dentry *d;
617 len += d->d_extraction_name_nchars + 1;
619 } while (!dentry_is_root(d) && will_extract_dentry(d));
621 return --len; /* No leading slash */
624 /* Returns the length of the longest string that might need to be appended to
625 * the path to an alias of an inode to open or create a named data stream.
627 * If the inode has no named data streams, this will be 0. Otherwise, this will
628 * be 1 plus the length of the longest-named data stream, since the data stream
629 * name must be separated from the path by the ':' character. */
631 inode_longest_named_data_stream_spec(const struct wim_inode *inode)
634 for (u16 i = 0; i < inode->i_num_ads; i++) {
635 size_t len = inode->i_ads_entries[i].stream_name_nbytes;
640 max = 1 + (max / sizeof(wchar_t));
644 /* Find the length, in wide characters, of the longest path needed for
645 * extraction of any file in @dentry_list relative to the target directory.
647 * Accounts for named data streams, but does not include null terminator (not
648 * needed for NtCreateFile). */
650 compute_path_max(struct list_head *dentry_list)
653 const struct wim_dentry *dentry;
655 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
658 len = dentry_extraction_path_length(dentry);
660 /* Account for named data streams */
661 len += inode_longest_named_data_stream_spec(dentry->d_inode);
670 /* Build the path at which to extract the @dentry, relative to the target
673 * The path is saved in ctx->pathbuf. */
675 build_extraction_path(const struct wim_dentry *dentry,
676 struct win32_apply_ctx *ctx)
680 const struct wim_dentry *d;
682 len = dentry_extraction_path_length(dentry);
684 ctx->pathbuf.Length = len * sizeof(wchar_t);
685 p = ctx->pathbuf.Buffer + len;
687 !dentry_is_root(d->d_parent) && will_extract_dentry(d->d_parent);
690 p -= d->d_extraction_name_nchars;
691 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
694 /* No leading slash */
695 p -= d->d_extraction_name_nchars;
696 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
699 /* Build the path at which to extract the @dentry, relative to the target
700 * directory, adding the suffix for a named data stream.
702 * The path is saved in ctx->pathbuf. */
704 build_extraction_path_with_ads(const struct wim_dentry *dentry,
705 struct win32_apply_ctx *ctx,
706 const wchar_t *stream_name,
707 size_t stream_name_nchars)
711 build_extraction_path(dentry, ctx);
713 /* Add :NAME for named data stream */
714 p = ctx->pathbuf.Buffer + (ctx->pathbuf.Length / sizeof(wchar_t));
716 wmemcpy(p, stream_name, stream_name_nchars);
717 ctx->pathbuf.Length += (1 + stream_name_nchars) * sizeof(wchar_t);
720 /* Build the Win32 namespace path to the specified @dentry when extracted.
722 * The path is saved in ctx->pathbuf and will be null terminated.
724 * XXX: We could get rid of this if it wasn't needed for the file encryption
725 * APIs, and the registry manipulation in WIMBoot mode. */
727 build_win32_extraction_path(const struct wim_dentry *dentry,
728 struct win32_apply_ctx *ctx)
730 build_extraction_path(dentry, ctx);
732 /* Prepend target_ntpath to our relative path, then change \??\ into \\?\ */
734 memmove(ctx->pathbuf.Buffer +
735 (ctx->target_ntpath.Length / sizeof(wchar_t)) + 1,
736 ctx->pathbuf.Buffer, ctx->pathbuf.Length);
737 memcpy(ctx->pathbuf.Buffer, ctx->target_ntpath.Buffer,
738 ctx->target_ntpath.Length);
739 ctx->pathbuf.Buffer[ctx->target_ntpath.Length / sizeof(wchar_t)] = L'\\';
740 ctx->pathbuf.Length += ctx->target_ntpath.Length + sizeof(wchar_t);
741 ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)] = L'\0';
743 wimlib_assert(ctx->pathbuf.Length >= 4 * sizeof(wchar_t) &&
744 !wmemcmp(ctx->pathbuf.Buffer, L"\\??\\", 4));
746 ctx->pathbuf.Buffer[1] = L'\\';
750 /* Returns a "printable" representation of the last relative NT path that was
751 * constructed with build_extraction_path() or build_extraction_path_with_ads().
753 * This will be overwritten by the next call to this function. */
754 static const wchar_t *
755 current_path(struct win32_apply_ctx *ctx)
757 wchar_t *p = ctx->print_buffer;
759 p = wmempcpy(p, ctx->common.target, ctx->common.target_nchars);
761 p = wmempcpy(p, ctx->pathbuf.Buffer, ctx->pathbuf.Length / sizeof(wchar_t));
763 return ctx->print_buffer;
767 * Ensures the target directory exists and opens a handle to it, in preparation
768 * of using paths relative to it.
771 prepare_target(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
777 /* Open handle to the target directory (possibly creating it). */
779 ret = win32_path_to_nt_path(ctx->common.target, &ctx->target_ntpath);
783 ctx->attr.Length = sizeof(ctx->attr);
784 ctx->attr.ObjectName = &ctx->target_ntpath;
786 status = (*func_NtCreateFile)(&ctx->h_target,
792 FILE_SHARE_VALID_FLAGS,
794 FILE_DIRECTORY_FILE |
795 FILE_OPEN_REPARSE_POINT |
796 FILE_OPEN_FOR_BACKUP_INTENT,
800 if (!NT_SUCCESS(status)) {
801 set_errno_from_nt_status(status);
802 ERROR_WITH_ERRNO("Can't open or create directory \"%ls\" "
803 "(status=0x%08"PRIx32")",
804 ctx->common.target, (u32)status);
805 return WIMLIB_ERR_OPENDIR;
808 path_max = compute_path_max(dentry_list);
810 /* Add some extra for building Win32 paths for the file encryption APIs,
811 * and ensure we have at least enough to potentially use a 8.3 name for
812 * the last component. */
813 path_max += max(2 + (ctx->target_ntpath.Length / sizeof(wchar_t)),
816 ctx->pathbuf.MaximumLength = path_max * sizeof(wchar_t);
817 ctx->pathbuf.Buffer = MALLOC(ctx->pathbuf.MaximumLength);
818 if (!ctx->pathbuf.Buffer)
819 return WIMLIB_ERR_NOMEM;
821 ctx->attr.RootDirectory = ctx->h_target;
822 ctx->attr.ObjectName = &ctx->pathbuf;
824 ctx->print_buffer = MALLOC((ctx->common.target_nchars + 1 + path_max + 1) *
826 if (!ctx->print_buffer)
827 return WIMLIB_ERR_NOMEM;
832 /* When creating an inode that will have a short (DOS) name, we create it using
833 * the long name associated with the short name. This ensures that the short
834 * name gets associated with the correct long name. */
835 static struct wim_dentry *
836 first_extraction_alias(const struct wim_inode *inode)
838 struct list_head *next = inode->i_extraction_aliases.next;
839 struct wim_dentry *dentry;
842 dentry = list_entry(next, struct wim_dentry,
843 d_extraction_alias_node);
844 if (dentry_has_short_name(dentry))
847 } while (next != &inode->i_extraction_aliases);
852 * Set or clear FILE_ATTRIBUTE_COMPRESSED if the inherited value is different
853 * from the desired value.
855 * Note that you can NOT override the inherited value of
856 * FILE_ATTRIBUTE_COMPRESSED directly with NtCreateFile().
859 adjust_compression_attribute(HANDLE h, const struct wim_dentry *dentry,
860 struct win32_apply_ctx *ctx)
862 const bool compressed = (dentry->d_inode->i_attributes &
863 FILE_ATTRIBUTE_COMPRESSED);
865 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
868 if (!ctx->common.supported_features.compressed_files)
871 FILE_BASIC_INFORMATION info;
873 USHORT compression_state;
875 /* Get current attributes */
876 status = (*func_NtQueryInformationFile)(h, &ctx->iosb,
878 FileBasicInformation);
879 if (NT_SUCCESS(status) &&
880 compressed == !!(info.FileAttributes & FILE_ATTRIBUTE_COMPRESSED))
882 /* Nothing needs to be done. */
886 /* Set the new compression state */
889 compression_state = COMPRESSION_FORMAT_DEFAULT;
891 compression_state = COMPRESSION_FORMAT_NONE;
893 status = (*func_NtFsControlFile)(h,
898 FSCTL_SET_COMPRESSION,
903 if (NT_SUCCESS(status))
906 set_errno_from_nt_status(status);
907 ERROR_WITH_ERRNO("Can't %s compression attribute on \"%ls\" "
908 "(status=0x%08"PRIx32")",
909 (compressed ? "set" : "clear"),
910 current_path(ctx), status);
911 return WIMLIB_ERR_SET_ATTRIBUTES;
915 * Clear FILE_ATTRIBUTE_ENCRYPTED if the file or directory is not supposed to be
918 * You can provide FILE_ATTRIBUTE_ENCRYPTED to NtCreateFile() to set it on the
919 * created file. However, the file or directory will otherwise default to the
920 * encryption state of the parent directory. This function works around this
921 * limitation by using DecryptFile() to remove FILE_ATTRIBUTE_ENCRYPTED on files
922 * (and directories) that are not supposed to have it set.
924 * Regardless of whether it succeeds or fails, this function may close the
925 * handle to the file. If it does, it sets it to NULL.
928 maybe_clear_encryption_attribute(HANDLE *h_ptr, const struct wim_dentry *dentry,
929 struct win32_apply_ctx *ctx)
931 if (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)
934 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
937 if (!ctx->common.supported_features.encrypted_files)
940 FILE_BASIC_INFORMATION info;
944 /* Get current attributes */
945 status = (*func_NtQueryInformationFile)(*h_ptr, &ctx->iosb,
947 FileBasicInformation);
948 if (NT_SUCCESS(status) &&
949 !(info.FileAttributes & FILE_ATTRIBUTE_ENCRYPTED))
951 /* Nothing needs to be done. */
955 /* Set the new encryption state */
957 /* Due to Windows' crappy file encryption APIs, we need to close the
958 * handle to the file so we don't get ERROR_SHARING_VIOLATION. We also
959 * hack together a Win32 path, although we will use the \\?\ prefix so
960 * it will actually be a NT path in disguise... */
961 (*func_NtClose)(*h_ptr);
964 build_win32_extraction_path(dentry, ctx);
966 bret = DecryptFile(ctx->pathbuf.Buffer, 0);
968 /* Restore the NT namespace path */
969 build_extraction_path(dentry, ctx);
972 DWORD err = GetLastError();
973 set_errno_from_win32_error(err);
974 ERROR_WITH_ERRNO("Can't decrypt file \"%ls\" (err=%"PRIu32")",
975 current_path(ctx), (u32)err);
976 return WIMLIB_ERR_SET_ATTRIBUTES;
981 /* Try to enable short name support on the target volume. If successful, return
982 * true. If unsuccessful, issue a warning and return false. */
984 try_to_enable_short_names(const wchar_t *volume)
987 FILE_FS_PERSISTENT_VOLUME_INFORMATION info;
991 h = CreateFile(volume, GENERIC_WRITE,
992 FILE_SHARE_VALID_FLAGS, NULL, OPEN_EXISTING,
993 FILE_FLAG_BACKUP_SEMANTICS, NULL);
994 if (h == INVALID_HANDLE_VALUE)
997 info.VolumeFlags = 0;
998 info.FlagMask = PERSISTENT_VOLUME_STATE_SHORT_NAME_CREATION_DISABLED;
1002 bret = DeviceIoControl(h, FSCTL_SET_PERSISTENT_VOLUME_STATE,
1003 &info, sizeof(info), NULL, 0,
1004 &bytesReturned, NULL);
1013 WARNING("Failed to enable short name support on %ls "
1014 "(err=%"PRIu32")", volume + 4, (u32)GetLastError());
1019 remove_conflicting_short_name(const struct wim_dentry *dentry, struct win32_apply_ctx *ctx)
1025 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1026 (13 * sizeof(wchar_t));
1027 u8 buf[bufsize] _aligned_attribute(8);
1028 bool retried = false;
1029 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1031 memset(buf, 0, bufsize);
1033 /* Build the path with the short name. */
1034 name = &ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)];
1035 while (name != ctx->pathbuf.Buffer && *(name - 1) != L'\\')
1037 end = mempcpy(name, dentry->short_name, dentry->short_name_nbytes);
1038 ctx->pathbuf.Length = ((u8 *)end - (u8 *)ctx->pathbuf.Buffer);
1040 /* Open the conflicting file (by short name). */
1041 status = (*func_NtOpenFile)(&h, GENERIC_WRITE | DELETE,
1042 &ctx->attr, &ctx->iosb,
1043 FILE_SHARE_VALID_FLAGS,
1044 FILE_OPEN_REPARSE_POINT | FILE_OPEN_FOR_BACKUP_INTENT);
1045 if (!NT_SUCCESS(status)) {
1046 WARNING("Can't open \"%ls\" (status=0x%08"PRIx32")",
1047 current_path(ctx), (u32)status);
1052 WARNING("Overriding conflicting short name; path=\"%ls\"",
1056 /* Try to remove the short name on the conflicting file. */
1059 status = (*func_NtSetInformationFile)(h, &ctx->iosb, info, bufsize,
1060 FileShortNameInformation);
1062 if (status == STATUS_INVALID_PARAMETER && !retried) {
1064 /* Microsoft forgot to make it possible to remove short names
1065 * until Windows 7. Oops. Use a random short name instead. */
1067 info->FileNameLength = 12 * sizeof(wchar_t);
1068 for (int i = 0; i < 8; i++)
1069 info->FileName[i] = 'A' + (rand() % 26);
1070 info->FileName[8] = L'.';
1071 info->FileName[9] = L'W';
1072 info->FileName[10] = L'L';
1073 info->FileName[11] = L'B';
1074 info->FileName[12] = L'\0';
1080 build_extraction_path(dentry, ctx);
1084 /* Set the short name on the open file @h which has been created at the location
1085 * indicated by @dentry.
1087 * Note that this may add, change, or remove the short name.
1089 * @h must be opened with DELETE access.
1091 * Returns 0 or WIMLIB_ERR_SET_SHORT_NAME. The latter only happens in
1092 * STRICT_SHORT_NAMES mode.
1095 set_short_name(HANDLE h, const struct wim_dentry *dentry,
1096 struct win32_apply_ctx *ctx)
1099 if (!ctx->common.supported_features.short_names)
1103 * Note: The size of the FILE_NAME_INFORMATION buffer must be such that
1104 * FileName contains at least 2 wide characters (4 bytes). Otherwise,
1105 * NtSetInformationFile() will return STATUS_INFO_LENGTH_MISMATCH. This
1106 * is despite the fact that FileNameLength can validly be 0 or 2 bytes,
1107 * with the former case being removing the existing short name if
1108 * present, rather than setting one.
1110 * The null terminator is seemingly optional, but to be safe we include
1111 * space for it and zero all unused space.
1114 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1115 max(dentry->short_name_nbytes, sizeof(wchar_t)) +
1117 u8 buf[bufsize] _aligned_attribute(8);
1118 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1120 bool tried_to_remove_existing = false;
1122 memset(buf, 0, bufsize);
1124 info->FileNameLength = dentry->short_name_nbytes;
1125 memcpy(info->FileName, dentry->short_name, dentry->short_name_nbytes);
1128 status = (*func_NtSetInformationFile)(h, &ctx->iosb, info, bufsize,
1129 FileShortNameInformation);
1130 if (NT_SUCCESS(status))
1133 if (status == STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME) {
1134 if (dentry->short_name_nbytes == 0)
1136 if (!ctx->tried_to_enable_short_names) {
1140 ctx->tried_to_enable_short_names = true;
1142 ret = win32_get_drive_path(ctx->common.target,
1146 if (try_to_enable_short_names(volume))
1152 * Short names can conflict in several cases:
1154 * - a file being extracted has a short name conflicting with an
1157 * - a file being extracted has a short name conflicting with another
1158 * file being extracted (possible, but shouldn't happen)
1160 * - a file being extracted has a short name that conflicts with the
1161 * automatically generated short name of a file we previously
1162 * extracted, but failed to set the short name for. Sounds unlikely,
1163 * but this actually does happen fairly often on versions of Windows
1164 * prior to Windows 7 because they do not support removing short names
1167 if (unlikely(status == STATUS_OBJECT_NAME_COLLISION) &&
1168 dentry->short_name_nbytes && !tried_to_remove_existing)
1170 tried_to_remove_existing = true;
1171 status = remove_conflicting_short_name(dentry, ctx);
1172 if (NT_SUCCESS(status))
1176 /* By default, failure to set short names is not an error (since short
1177 * names aren't too important anymore...). */
1178 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES)) {
1179 if (dentry->short_name_nbytes)
1180 ctx->num_set_short_name_failures++;
1182 ctx->num_remove_short_name_failures++;
1186 if (status == STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME) {
1187 ERROR("Can't set short name when short "
1188 "names are not enabled on the volume!");
1190 ERROR("Can't set short name on \"%ls\" (status=0x%08"PRIx32")",
1191 current_path(ctx), (u32)status);
1193 return WIMLIB_ERR_SET_SHORT_NAME;
1197 * A wrapper around NtCreateFile() to make it slightly more usable...
1198 * This uses the path currently constructed in ctx->pathbuf.
1200 * Also, we always specify FILE_OPEN_FOR_BACKUP_INTENT and
1201 * FILE_OPEN_REPARSE_POINT.
1204 do_create_file(PHANDLE FileHandle,
1205 ACCESS_MASK DesiredAccess,
1206 PLARGE_INTEGER AllocationSize,
1207 ULONG FileAttributes,
1208 ULONG CreateDisposition,
1209 ULONG CreateOptions,
1210 struct win32_apply_ctx *ctx)
1212 return (*func_NtCreateFile)(FileHandle,
1218 FILE_SHARE_VALID_FLAGS,
1221 FILE_OPEN_FOR_BACKUP_INTENT |
1222 FILE_OPEN_REPARSE_POINT,
1227 /* Like do_create_file(), but builds the extraction path of the @dentry first.
1230 create_file(PHANDLE FileHandle,
1231 ACCESS_MASK DesiredAccess,
1232 PLARGE_INTEGER AllocationSize,
1233 ULONG FileAttributes,
1234 ULONG CreateDisposition,
1235 ULONG CreateOptions,
1236 const struct wim_dentry *dentry,
1237 struct win32_apply_ctx *ctx)
1239 build_extraction_path(dentry, ctx);
1240 return do_create_file(FileHandle,
1249 /* Create empty named data streams.
1251 * Since these won't have 'struct wim_lookup_table_entry's, they won't show up
1252 * in the call to extract_stream_list(). Hence the need for the special case.
1255 create_any_empty_ads(const struct wim_dentry *dentry,
1256 struct win32_apply_ctx *ctx)
1258 const struct wim_inode *inode = dentry->d_inode;
1259 LARGE_INTEGER allocation_size;
1260 bool path_modified = false;
1263 if (!ctx->common.supported_features.named_data_streams)
1266 for (u16 i = 0; i < inode->i_num_ads; i++) {
1267 const struct wim_ads_entry *entry;
1273 entry = &inode->i_ads_entries[i];
1276 if (!entry->stream_name_nbytes)
1283 /* Probably setting the allocation size to 0 has no effect, but
1284 * we might as well try. */
1285 allocation_size.QuadPart = 0;
1287 build_extraction_path_with_ads(dentry, ctx,
1289 entry->stream_name_nbytes /
1291 path_modified = true;
1294 disposition = FILE_SUPERSEDE;
1296 status = do_create_file(&h, FILE_WRITE_DATA, &allocation_size,
1297 0, disposition, 0, ctx);
1298 if (unlikely(!NT_SUCCESS(status))) {
1299 if (status == STATUS_OBJECT_NAME_NOT_FOUND && !retried) {
1300 /* Workaround for defect in the Windows PE
1301 * in-memory filesystem implementation:
1302 * FILE_SUPERSEDE does not create the file, as
1303 * expected and documented, when the named file
1304 * does not exist. */
1306 disposition = FILE_CREATE;
1309 set_errno_from_nt_status(status);
1310 ERROR_WITH_ERRNO("Can't create \"%ls\" "
1311 "(status=0x%08"PRIx32")",
1312 current_path(ctx), (u32)status);
1313 ret = WIMLIB_ERR_OPEN;
1318 /* Restore the path to the dentry itself */
1320 build_extraction_path(dentry, ctx);
1325 * Creates the directory named by @dentry, or uses an existing directory at that
1326 * location. If necessary, sets the short name and/or fixes compression and
1327 * encryption attributes.
1329 * Returns 0, WIMLIB_ERR_MKDIR, or WIMLIB_ERR_SET_SHORT_NAME.
1332 create_directory(const struct wim_dentry *dentry,
1333 struct win32_apply_ctx *ctx)
1340 /* Special attributes:
1342 * Use FILE_ATTRIBUTE_ENCRYPTED if the directory needs to have it set.
1343 * This doesn't work for FILE_ATTRIBUTE_COMPRESSED (unfortunately).
1345 * Don't specify FILE_ATTRIBUTE_DIRECTORY; it gets set anyway as a
1346 * result of the FILE_DIRECTORY_FILE option. */
1347 attrib = (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED);
1349 /* DELETE is needed for set_short_name().
1350 * GENERIC_READ and GENERIC_WRITE are needed for
1351 * adjust_compression_attribute(). */
1352 status = create_file(&h, GENERIC_READ | GENERIC_WRITE | DELETE, NULL,
1353 attrib, FILE_OPEN_IF, FILE_DIRECTORY_FILE,
1355 if (!NT_SUCCESS(status)) {
1356 set_errno_from_nt_status(status);
1357 ERROR_WITH_ERRNO("Can't create directory \"%ls\" "
1358 "(status=0x%08"PRIx32")",
1359 current_path(ctx), (u32)status);
1360 return WIMLIB_ERR_MKDIR;
1363 ret = set_short_name(h, dentry, ctx);
1366 ret = adjust_compression_attribute(h, dentry, ctx);
1369 ret = maybe_clear_encryption_attribute(&h, dentry, ctx);
1370 /* May close the handle!!! */
1378 * Create all the directories being extracted, other than the target directory
1381 * Note: we don't honor directory hard links. However, we don't allow them to
1382 * exist in WIM images anyway (see inode_fixup.c).
1385 create_directories(struct list_head *dentry_list,
1386 struct win32_apply_ctx *ctx)
1388 const struct wim_dentry *dentry;
1391 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1393 if (!(dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY))
1396 /* Note: Here we include files with
1397 * FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT, but we
1398 * wait until later to actually set the reparse data. */
1400 /* If the root dentry is being extracted, it was already done so
1401 * in prepare_target(). */
1402 if (!dentry_is_root(dentry)) {
1403 ret = create_directory(dentry, ctx);
1404 ret = check_apply_error(dentry, ctx, ret);
1408 ret = create_any_empty_ads(dentry, ctx);
1409 ret = check_apply_error(dentry, ctx, ret);
1414 ret = report_file_created(&ctx->common);
1422 * Creates the nondirectory file named by @dentry.
1424 * On success, returns an open handle to the file in @h_ret, with GENERIC_READ,
1425 * GENERIC_WRITE, and DELETE access. Also, the path to the file will be saved
1426 * in ctx->pathbuf. On failure, returns WIMLIB_ERR_OPEN.
1429 create_nondirectory_inode(HANDLE *h_ret, const struct wim_dentry *dentry,
1430 struct win32_apply_ctx *ctx)
1432 const struct wim_inode *inode;
1435 bool retried = false;
1438 inode = dentry->d_inode;
1440 /* If the file already exists and has FILE_ATTRIBUTE_SYSTEM and/or
1441 * FILE_ATTRIBUTE_HIDDEN, these must be specified in order to supersede
1444 * Normally the user shouldn't be trying to overwrite such files anyway,
1445 * but we at least provide FILE_ATTRIBUTE_SYSTEM and
1446 * FILE_ATTRIBUTE_HIDDEN if the WIM inode has those attributes so that
1447 * we catch the case where the user extracts the same files to the same
1448 * location more than one time.
1450 * Also specify FILE_ATTRIBUTE_ENCRYPTED if the file needs to be
1453 * In NO_ATTRIBUTES mode just don't specify any attributes at all.
1455 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES) {
1458 attrib = (inode->i_attributes & (FILE_ATTRIBUTE_SYSTEM |
1459 FILE_ATTRIBUTE_HIDDEN |
1460 FILE_ATTRIBUTE_ENCRYPTED));
1462 build_extraction_path(dentry, ctx);
1463 disposition = FILE_SUPERSEDE;
1465 status = do_create_file(h_ret, GENERIC_READ | GENERIC_WRITE | DELETE,
1466 NULL, attrib, disposition,
1467 FILE_NON_DIRECTORY_FILE, ctx);
1468 if (likely(NT_SUCCESS(status))) {
1471 ret = adjust_compression_attribute(*h_ret, dentry, ctx);
1473 (*func_NtClose)(*h_ret);
1477 ret = maybe_clear_encryption_attribute(h_ret, dentry, ctx);
1478 /* May close the handle!!! */
1482 (*func_NtClose)(*h_ret);
1487 /* Re-open the handle so that we can return it on
1489 status = do_create_file(h_ret,
1491 GENERIC_WRITE | DELETE,
1493 FILE_NON_DIRECTORY_FILE, ctx);
1494 if (!NT_SUCCESS(status))
1498 ret = create_any_empty_ads(dentry, ctx);
1500 (*func_NtClose)(*h_ret);
1506 if (status == STATUS_OBJECT_NAME_NOT_FOUND && !retried) {
1507 /* Workaround for defect in the Windows PE in-memory filesystem
1508 * implementation: FILE_SUPERSEDE does not create the file, as
1509 * expected and documented, when the named file does not exist.
1512 disposition = FILE_CREATE;
1516 if (status == STATUS_ACCESS_DENIED && !retried) {
1517 /* We also can't supersede an existing file that has
1518 * FILE_ATTRIBUTE_READONLY set; doing so causes NtCreateFile()
1519 * to return STATUS_ACCESS_DENIED . The only workaround seems
1520 * to be to explicitly remove FILE_ATTRIBUTE_READONLY on the
1521 * existing file, then try again. */
1523 FILE_BASIC_INFORMATION info;
1526 status = do_create_file(&h, FILE_WRITE_ATTRIBUTES, NULL, 0,
1527 FILE_OPEN, FILE_NON_DIRECTORY_FILE, ctx);
1528 if (!NT_SUCCESS(status))
1531 memset(&info, 0, sizeof(info));
1532 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1534 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1535 &info, sizeof(info),
1536 FileBasicInformation);
1538 if (!NT_SUCCESS(status))
1544 set_errno_from_nt_status(status);
1545 ERROR_WITH_ERRNO("Can't create file \"%ls\" (status=0x%08"PRIx32")",
1546 current_path(ctx), (u32)status);
1547 return WIMLIB_ERR_OPEN;
1550 /* Creates a hard link at the location named by @dentry to the file represented
1551 * by the open handle @h. Or, if the target volume does not support hard links,
1552 * create a separate file instead. */
1554 create_link(HANDLE h, const struct wim_dentry *dentry,
1555 struct win32_apply_ctx *ctx)
1557 if (ctx->common.supported_features.hard_links) {
1559 build_extraction_path(dentry, ctx);
1561 size_t bufsize = offsetof(FILE_LINK_INFORMATION, FileName) +
1562 ctx->pathbuf.Length + sizeof(wchar_t);
1563 u8 buf[bufsize] _aligned_attribute(8);
1564 FILE_LINK_INFORMATION *info = (FILE_LINK_INFORMATION *)buf;
1567 info->ReplaceIfExists = TRUE;
1568 info->RootDirectory = ctx->attr.RootDirectory;
1569 info->FileNameLength = ctx->pathbuf.Length;
1570 memcpy(info->FileName, ctx->pathbuf.Buffer, ctx->pathbuf.Length);
1571 info->FileName[info->FileNameLength / 2] = L'\0';
1573 /* Note: the null terminator isn't actually necessary,
1574 * but if you don't add the extra character, you get
1575 * STATUS_INFO_LENGTH_MISMATCH when FileNameLength
1576 * happens to be 2 */
1578 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1580 FileLinkInformation);
1581 if (NT_SUCCESS(status))
1583 ERROR("Failed to create link \"%ls\" (status=0x%08"PRIx32")",
1584 current_path(ctx), (u32)status);
1585 return WIMLIB_ERR_LINK;
1590 ret = create_nondirectory_inode(&h2, dentry, ctx);
1594 (*func_NtClose)(h2);
1599 /* Given an inode (represented by the open handle @h) for which one link has
1600 * been created (named by @first_dentry), create the other links.
1602 * Or, if the target volume does not support hard links, create separate files.
1604 * Note: This uses ctx->pathbuf and does not reset it.
1607 create_links(HANDLE h, const struct wim_dentry *first_dentry,
1608 struct win32_apply_ctx *ctx)
1610 const struct wim_inode *inode;
1611 const struct list_head *next;
1612 const struct wim_dentry *dentry;
1615 inode = first_dentry->d_inode;
1616 next = inode->i_extraction_aliases.next;
1618 dentry = list_entry(next, struct wim_dentry,
1619 d_extraction_alias_node);
1620 if (dentry != first_dentry) {
1621 ret = create_link(h, dentry, ctx);
1626 } while (next != &inode->i_extraction_aliases);
1630 /* Create a nondirectory file, including all links. */
1632 create_nondirectory(struct wim_inode *inode, struct win32_apply_ctx *ctx)
1634 struct wim_dentry *first_dentry;
1638 first_dentry = first_extraction_alias(inode);
1640 /* Create first link. */
1641 ret = create_nondirectory_inode(&h, first_dentry, ctx);
1645 /* Set short name. */
1646 ret = set_short_name(h, first_dentry, ctx);
1648 /* Create additional links, OR if hard links are not supported just
1649 * create more files. */
1651 ret = create_links(h, first_dentry, ctx);
1653 /* "WIMBoot" extraction: set external backing by the WIM file if needed. */
1654 if (!ret && unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
1655 ret = set_external_backing(h, inode, ctx);
1661 /* Create all the nondirectory files being extracted, including all aliases
1664 create_nondirectories(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1666 struct wim_dentry *dentry;
1667 struct wim_inode *inode;
1670 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1671 inode = dentry->d_inode;
1672 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1674 /* Call create_nondirectory() only once per inode */
1675 if (dentry == inode_first_extraction_dentry(inode)) {
1676 ret = create_nondirectory(inode, ctx);
1677 ret = check_apply_error(dentry, ctx, ret);
1681 ret = report_file_created(&ctx->common);
1689 close_handles(struct win32_apply_ctx *ctx)
1691 for (unsigned i = 0; i < ctx->num_open_handles; i++)
1692 (*func_NtClose)(ctx->open_handles[i]);
1695 /* Prepare to read the next stream, which has size @stream_size, into an
1696 * in-memory buffer. */
1698 prepare_data_buffer(struct win32_apply_ctx *ctx, u64 stream_size)
1700 if (stream_size > ctx->data_buffer_size) {
1701 /* Larger buffer needed. */
1703 if ((size_t)stream_size != stream_size)
1705 new_buffer = REALLOC(ctx->data_buffer, stream_size);
1708 ctx->data_buffer = new_buffer;
1709 ctx->data_buffer_size = stream_size;
1711 /* On the first call this changes data_buffer_ptr from NULL, which tells
1712 * extract_chunk() that the data buffer needs to be filled while reading
1713 * the stream data. */
1714 ctx->data_buffer_ptr = ctx->data_buffer;
1719 begin_extract_stream_instance(const struct wim_lookup_table_entry *stream,
1720 struct wim_dentry *dentry,
1721 const wchar_t *stream_name,
1722 struct win32_apply_ctx *ctx)
1724 const struct wim_inode *inode = dentry->d_inode;
1725 size_t stream_name_nchars = 0;
1726 FILE_ALLOCATION_INFORMATION alloc_info;
1730 if (unlikely(stream_name))
1731 stream_name_nchars = wcslen(stream_name);
1733 if (unlikely(stream_name_nchars)) {
1734 build_extraction_path_with_ads(dentry, ctx,
1735 stream_name, stream_name_nchars);
1737 build_extraction_path(dentry, ctx);
1741 /* Encrypted file? */
1742 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)
1743 && (stream_name_nchars == 0))
1745 if (!ctx->common.supported_features.encrypted_files)
1748 /* We can't write encrypted file streams directly; we must use
1749 * WriteEncryptedFileRaw(), which requires providing the data
1750 * through a callback function. This can't easily be combined
1751 * with our own callback-based approach.
1753 * The current workaround is to simply read the stream into
1754 * memory and write the encrypted file from that.
1756 * TODO: This isn't sufficient for extremely large encrypted
1757 * files. Perhaps we should create an extra thread to write
1759 if (!prepare_data_buffer(ctx, stream->size))
1760 return WIMLIB_ERR_NOMEM;
1761 list_add_tail(&dentry->tmp_list, &ctx->encrypted_dentries);
1767 * Note: FILE_ATTRIBUTE_REPARSE_POINT is tested *after*
1768 * FILE_ATTRIBUTE_ENCRYPTED since the WIM format does not store both EFS
1769 * data and reparse data for the same file, and the EFS data takes
1771 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1772 && (stream_name_nchars == 0))
1774 if (!ctx->common.supported_features.reparse_points)
1777 /* We can't write the reparse stream directly; we must set it
1778 * with FSCTL_SET_REPARSE_POINT, which requires that all the
1779 * data be available. So, stage the data in a buffer. */
1781 if (!prepare_data_buffer(ctx, stream->size))
1782 return WIMLIB_ERR_NOMEM;
1783 list_add_tail(&dentry->tmp_list, &ctx->reparse_dentries);
1787 if (ctx->num_open_handles == MAX_OPEN_STREAMS) {
1788 /* XXX: Fix this. But because of the checks in
1789 * extract_stream_list(), this can now only happen on a
1790 * filesystem that does not support hard links. */
1791 ERROR("Can't extract data: too many open files!");
1792 return WIMLIB_ERR_UNSUPPORTED;
1795 /* Open a new handle */
1796 status = do_create_file(&h,
1797 FILE_WRITE_DATA | SYNCHRONIZE,
1798 NULL, 0, FILE_OPEN_IF,
1799 FILE_SEQUENTIAL_ONLY |
1800 FILE_SYNCHRONOUS_IO_NONALERT,
1802 if (!NT_SUCCESS(status)) {
1803 set_errno_from_nt_status(status);
1804 ERROR_WITH_ERRNO("Can't open \"%ls\" for writing "
1805 "(status=0x%08"PRIx32")",
1806 current_path(ctx), (u32)status);
1807 return WIMLIB_ERR_OPEN;
1810 ctx->open_handles[ctx->num_open_handles++] = h;
1812 /* Allocate space for the data. */
1813 alloc_info.AllocationSize.QuadPart = stream->size;
1814 (*func_NtSetInformationFile)(h, &ctx->iosb,
1815 &alloc_info, sizeof(alloc_info),
1816 FileAllocationInformation);
1820 /* Set the reparse data @rpbuf of length @rpbuflen on the extracted file
1821 * corresponding to the WIM dentry @dentry. */
1823 do_set_reparse_data(const struct wim_dentry *dentry,
1824 const void *rpbuf, u16 rpbuflen,
1825 struct win32_apply_ctx *ctx)
1830 status = create_file(&h, GENERIC_WRITE, NULL,
1831 0, FILE_OPEN, 0, dentry, ctx);
1832 if (!NT_SUCCESS(status))
1835 status = (*func_NtFsControlFile)(h, NULL, NULL, NULL,
1836 &ctx->iosb, FSCTL_SET_REPARSE_POINT,
1837 (void *)rpbuf, rpbuflen,
1841 if (NT_SUCCESS(status))
1844 /* On Windows, by default only the Administrator can create symbolic
1845 * links for some reason. By default we just issue a warning if this
1846 * appears to be the problem. Use WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS
1847 * to get a hard error. */
1848 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS)
1849 && (status == STATUS_PRIVILEGE_NOT_HELD ||
1850 status == STATUS_ACCESS_DENIED)
1851 && (dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1852 dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1854 WARNING("Can't create symbolic link \"%ls\"! \n"
1855 " (Need Administrator rights, or at least "
1857 " SeCreateSymbolicLink privilege.)",
1863 set_errno_from_nt_status(status);
1864 ERROR_WITH_ERRNO("Can't set reparse data on \"%ls\" "
1865 "(status=0x%08"PRIx32")",
1866 current_path(ctx), (u32)status);
1867 return WIMLIB_ERR_SET_REPARSE_DATA;
1870 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1871 * pointer to the suffix of the path that begins with the device directly, such
1872 * as e:\Windows\System32. */
1873 static const wchar_t *
1874 skip_nt_toplevel_component(const wchar_t *path, size_t path_nchars)
1876 static const wchar_t * const dirs[] = {
1881 size_t first_dir_len = 0;
1882 const wchar_t * const end = path + path_nchars;
1884 for (size_t i = 0; i < ARRAY_LEN(dirs); i++) {
1885 size_t len = wcslen(dirs[i]);
1886 if (len <= (end - path) && !wcsnicmp(path, dirs[i], len)) {
1887 first_dir_len = len;
1891 if (first_dir_len == 0)
1893 path += first_dir_len;
1894 while (path != end && *path == L'\\')
1899 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1900 * pointer to the suffix of the path that is device-relative, such as
1903 * The path has an explicit length and is not necessarily null terminated.
1905 * If the path just something like \??\e: then the returned pointer will point
1906 * just past the colon. In this case the length of the result will be 0
1908 static const wchar_t *
1909 get_device_relative_path(const wchar_t *path, size_t path_nchars)
1911 const wchar_t * const orig_path = path;
1912 const wchar_t * const end = path + path_nchars;
1914 path = skip_nt_toplevel_component(path, path_nchars);
1915 if (path == orig_path)
1918 path = wmemchr(path, L'\\', (end - path));
1923 } while (path != end && *path == L'\\');
1928 * Given a reparse point buffer for a symbolic link or junction, adjust its
1929 * contents so that the target of the link is consistent with the new location
1933 try_rpfix(u8 *rpbuf, u16 *rpbuflen_p, struct win32_apply_ctx *ctx)
1935 struct reparse_data rpdata;
1936 size_t orig_subst_name_nchars;
1937 const wchar_t *relpath;
1938 size_t relpath_nchars;
1939 size_t target_ntpath_nchars;
1940 size_t fixed_subst_name_nchars;
1941 const wchar_t *fixed_print_name;
1942 size_t fixed_print_name_nchars;
1944 if (parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata)) {
1945 /* Do nothing if the reparse data is invalid. */
1949 if (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
1950 (rpdata.rpflags & SYMBOLIC_LINK_RELATIVE))
1952 /* Do nothing if it's a relative symbolic link. */
1956 /* Build the new substitute name from the NT namespace path to the
1957 * target directory, then a path separator, then the "device relative"
1958 * part of the old substitute name. */
1960 orig_subst_name_nchars = rpdata.substitute_name_nbytes / sizeof(wchar_t);
1962 relpath = get_device_relative_path(rpdata.substitute_name,
1963 orig_subst_name_nchars);
1964 relpath_nchars = orig_subst_name_nchars -
1965 (relpath - rpdata.substitute_name);
1967 target_ntpath_nchars = ctx->target_ntpath.Length / sizeof(wchar_t);
1969 fixed_subst_name_nchars = target_ntpath_nchars;
1971 fixed_subst_name_nchars += 1 + relpath_nchars;
1972 wchar_t fixed_subst_name[fixed_subst_name_nchars];
1974 wmemcpy(fixed_subst_name, ctx->target_ntpath.Buffer,
1975 target_ntpath_nchars);
1976 if (relpath_nchars) {
1977 fixed_subst_name[target_ntpath_nchars] = L'\\';
1978 wmemcpy(&fixed_subst_name[target_ntpath_nchars + 1],
1979 relpath, relpath_nchars);
1981 /* Doesn't need to be null-terminated. */
1983 /* Print name should be Win32, but not all NT names can even be
1984 * translated to Win32 names. But we can at least delete the top-level
1985 * directory, such as \??\, and this will have the expected result in
1986 * the usual case. */
1987 fixed_print_name = skip_nt_toplevel_component(fixed_subst_name,
1988 fixed_subst_name_nchars);
1989 fixed_print_name_nchars = fixed_subst_name_nchars - (fixed_print_name -
1992 rpdata.substitute_name = fixed_subst_name;
1993 rpdata.substitute_name_nbytes = fixed_subst_name_nchars * sizeof(wchar_t);
1994 rpdata.print_name = (wchar_t *)fixed_print_name;
1995 rpdata.print_name_nbytes = fixed_print_name_nchars * sizeof(wchar_t);
1996 make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
1999 /* Sets reparse data on the specified file. This handles "fixing" the targets
2000 * of absolute symbolic links and junctions if WIMLIB_EXTRACT_FLAG_RPFIX was
2003 set_reparse_data(const struct wim_dentry *dentry,
2004 const void *_rpbuf, u16 rpbuflen, struct win32_apply_ctx *ctx)
2006 const struct wim_inode *inode = dentry->d_inode;
2007 const void *rpbuf = _rpbuf;
2009 if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
2010 && !inode->i_not_rpfixed
2011 && (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
2012 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
2014 memcpy(&ctx->rpfixbuf, _rpbuf, rpbuflen);
2015 try_rpfix((u8 *)&ctx->rpfixbuf, &rpbuflen, ctx);
2016 rpbuf = &ctx->rpfixbuf;
2018 return do_set_reparse_data(dentry, rpbuf, rpbuflen, ctx);
2022 /* Import the next block of raw encrypted data */
2024 import_encrypted_data(PBYTE pbData, PVOID pvCallbackContext, PULONG Length)
2026 struct win32_apply_ctx *ctx = pvCallbackContext;
2029 copy_len = min(ctx->encrypted_size - ctx->encrypted_offset, *Length);
2030 memcpy(pbData, &ctx->data_buffer[ctx->encrypted_offset], copy_len);
2031 ctx->encrypted_offset += copy_len;
2033 return ERROR_SUCCESS;
2036 /* Write the raw encrypted data to the already-created file corresponding to
2039 * The raw encrypted data is provided in ctx->data_buffer, and its size is
2040 * ctx->encrypted_size. */
2042 extract_encrypted_file(const struct wim_dentry *dentry,
2043 struct win32_apply_ctx *ctx)
2048 /* Temporarily build a Win32 path for OpenEncryptedFileRaw() */
2049 build_win32_extraction_path(dentry, ctx);
2051 err = OpenEncryptedFileRaw(ctx->pathbuf.Buffer,
2052 CREATE_FOR_IMPORT, &rawctx);
2054 /* Restore the NT namespace path */
2055 build_extraction_path(dentry, ctx);
2057 if (err != ERROR_SUCCESS) {
2058 set_errno_from_win32_error(err);
2059 ERROR_WITH_ERRNO("Can't open \"%ls\" for encrypted import "
2060 "(err=%"PRIu32")", current_path(ctx), (u32)err);
2061 return WIMLIB_ERR_OPEN;
2064 ctx->encrypted_offset = 0;
2066 err = WriteEncryptedFileRaw(import_encrypted_data, ctx, rawctx);
2068 CloseEncryptedFileRaw(rawctx);
2070 if (err != ERROR_SUCCESS) {
2071 set_errno_from_win32_error(err);
2072 ERROR_WITH_ERRNO("Can't import encrypted file \"%ls\" "
2073 "(err=%"PRIu32")", current_path(ctx), (u32)err);
2074 return WIMLIB_ERR_WRITE;
2080 /* Called when starting to read a stream for extraction on Windows */
2082 begin_extract_stream(struct wim_lookup_table_entry *stream, void *_ctx)
2084 struct win32_apply_ctx *ctx = _ctx;
2085 const struct stream_owner *owners = stream_owners(stream);
2088 ctx->num_open_handles = 0;
2089 ctx->data_buffer_ptr = NULL;
2090 INIT_LIST_HEAD(&ctx->reparse_dentries);
2091 INIT_LIST_HEAD(&ctx->encrypted_dentries);
2093 for (u32 i = 0; i < stream->out_refcnt; i++) {
2094 const struct wim_inode *inode = owners[i].inode;
2095 const wchar_t *stream_name = owners[i].stream_name;
2096 struct wim_dentry *dentry;
2098 /* A copy of the stream needs to be extracted to @inode. */
2100 if (ctx->common.supported_features.hard_links) {
2101 dentry = inode_first_extraction_dentry(inode);
2102 ret = begin_extract_stream_instance(stream, dentry,
2104 ret = check_apply_error(dentry, ctx, ret);
2108 /* Hard links not supported. Extract the stream
2109 * separately to each alias of the inode. */
2110 struct list_head *next;
2112 next = inode->i_extraction_aliases.next;
2114 dentry = list_entry(next, struct wim_dentry,
2115 d_extraction_alias_node);
2116 ret = begin_extract_stream_instance(stream,
2120 ret = check_apply_error(dentry, ctx, ret);
2124 } while (next != &inode->i_extraction_aliases);
2135 /* Called when the next chunk of a stream has been read for extraction on
2138 extract_chunk(const void *chunk, size_t size, void *_ctx)
2140 struct win32_apply_ctx *ctx = _ctx;
2142 /* Write the data chunk to each open handle */
2143 for (unsigned i = 0; i < ctx->num_open_handles; i++) {
2144 u8 *bufptr = (u8 *)chunk;
2145 size_t bytes_remaining = size;
2147 while (bytes_remaining) {
2148 ULONG count = min(0xFFFFFFFF, bytes_remaining);
2150 status = (*func_NtWriteFile)(ctx->open_handles[i],
2152 &ctx->iosb, bufptr, count,
2154 if (!NT_SUCCESS(status)) {
2155 set_errno_from_nt_status(status);
2156 ERROR_WITH_ERRNO("Error writing data to target "
2157 "volume (status=0x%08"PRIx32")",
2159 return WIMLIB_ERR_WRITE;
2161 bufptr += ctx->iosb.Information;
2162 bytes_remaining -= ctx->iosb.Information;
2166 /* Copy the data chunk into the buffer (if needed) */
2167 if (ctx->data_buffer_ptr)
2168 ctx->data_buffer_ptr = mempcpy(ctx->data_buffer_ptr,
2173 /* Called when a stream has been fully read for extraction on Windows */
2175 end_extract_stream(struct wim_lookup_table_entry *stream, int status, void *_ctx)
2177 struct win32_apply_ctx *ctx = _ctx;
2179 const struct wim_dentry *dentry;
2186 if (likely(!ctx->data_buffer_ptr))
2189 if (!list_empty(&ctx->reparse_dentries)) {
2190 if (stream->size > REPARSE_DATA_MAX_SIZE) {
2191 dentry = list_first_entry(&ctx->reparse_dentries,
2192 struct wim_dentry, tmp_list);
2193 build_extraction_path(dentry, ctx);
2194 ERROR("Reparse data of \"%ls\" has size "
2195 "%"PRIu64" bytes (exceeds %u bytes)",
2196 current_path(ctx), stream->size,
2197 REPARSE_DATA_MAX_SIZE);
2198 ret = WIMLIB_ERR_INVALID_REPARSE_DATA;
2199 return check_apply_error(dentry, ctx, ret);
2201 /* In the WIM format, reparse streams are just the reparse data
2202 * and omit the header. But we can reconstruct the header. */
2203 memcpy(ctx->rpbuf.rpdata, ctx->data_buffer, stream->size);
2204 ctx->rpbuf.rpdatalen = stream->size;
2205 ctx->rpbuf.rpreserved = 0;
2206 list_for_each_entry(dentry, &ctx->reparse_dentries, tmp_list) {
2207 ctx->rpbuf.rptag = dentry->d_inode->i_reparse_tag;
2208 ret = set_reparse_data(dentry, &ctx->rpbuf,
2209 stream->size + REPARSE_DATA_OFFSET,
2211 ret = check_apply_error(dentry, ctx, ret);
2217 if (!list_empty(&ctx->encrypted_dentries)) {
2218 ctx->encrypted_size = stream->size;
2219 list_for_each_entry(dentry, &ctx->encrypted_dentries, tmp_list) {
2220 ret = extract_encrypted_file(dentry, ctx);
2221 ret = check_apply_error(dentry, ctx, ret);
2230 /* Attributes that can't be set directly */
2231 #define SPECIAL_ATTRIBUTES \
2232 (FILE_ATTRIBUTE_REPARSE_POINT | \
2233 FILE_ATTRIBUTE_DIRECTORY | \
2234 FILE_ATTRIBUTE_ENCRYPTED | \
2235 FILE_ATTRIBUTE_SPARSE_FILE | \
2236 FILE_ATTRIBUTE_COMPRESSED)
2238 /* Set the security descriptor @desc, of @desc_size bytes, on the file with open
2241 set_security_descriptor(HANDLE h, const void *_desc,
2242 size_t desc_size, struct win32_apply_ctx *ctx)
2244 SECURITY_INFORMATION info;
2246 SECURITY_DESCRIPTOR_RELATIVE *desc;
2249 * Ideally, we would just pass in the security descriptor buffer as-is.
2250 * But it turns out that Windows can mess up the security descriptor
2251 * even when using the low-level NtSetSecurityObject() function:
2253 * - Windows will clear SE_DACL_AUTO_INHERITED if it is set in the
2254 * passed buffer. To actually get Windows to set
2255 * SE_DACL_AUTO_INHERITED, the application must set the non-persistent
2256 * flag SE_DACL_AUTO_INHERIT_REQ. As usual, Microsoft didn't bother
2257 * to properly document either of these flags. It's unclear how
2258 * important SE_DACL_AUTO_INHERITED actually is, but to be safe we use
2259 * the SE_DACL_AUTO_INHERIT_REQ workaround to set it if needed.
2261 * - The above also applies to the equivalent SACL flags,
2262 * SE_SACL_AUTO_INHERITED and SE_SACL_AUTO_INHERIT_REQ.
2264 * - If the application says that it's setting
2265 * DACL_SECURITY_INFORMATION, then Windows sets SE_DACL_PRESENT in the
2266 * resulting security descriptor, even if the security descriptor the
2267 * application provided did not have a DACL. This seems to be
2268 * unavoidable, since omitting DACL_SECURITY_INFORMATION would cause a
2269 * default DACL to remain. Fortunately, this behavior seems harmless,
2270 * since the resulting DACL will still be "null" --- but it will be
2271 * "the other representation of null".
2273 * - The above also applies to SACL_SECURITY_INFORMATION and
2274 * SE_SACL_PRESENT. Again, it's seemingly unavoidable but "harmless"
2275 * that Windows changes the representation of a "null SACL".
2277 if (likely(desc_size <= STACK_MAX)) {
2278 desc = alloca(desc_size);
2280 desc = MALLOC(desc_size);
2282 return STATUS_NO_MEMORY;
2285 memcpy(desc, _desc, desc_size);
2287 if (likely(desc_size >= 4)) {
2289 if (desc->Control & SE_DACL_AUTO_INHERITED)
2290 desc->Control |= SE_DACL_AUTO_INHERIT_REQ;
2292 if (desc->Control & SE_SACL_AUTO_INHERITED)
2293 desc->Control |= SE_SACL_AUTO_INHERIT_REQ;
2297 * More API insanity. We want to set the entire security descriptor
2298 * as-is. But all available APIs require specifying the specific parts
2299 * of the security descriptor being set. Especially annoying is that
2300 * mandatory integrity labels are part of the SACL, but they aren't set
2301 * with SACL_SECURITY_INFORMATION. Instead, applications must also
2302 * specify LABEL_SECURITY_INFORMATION (Windows Vista, Windows 7) or
2303 * BACKUP_SECURITY_INFORMATION (Windows 8). But at least older versions
2304 * of Windows don't error out if you provide these newer flags...
2306 * Also, if the process isn't running as Administrator, then it probably
2307 * doesn't have SE_RESTORE_PRIVILEGE. In this case, it will always get
2308 * the STATUS_PRIVILEGE_NOT_HELD error by trying to set the SACL, even
2309 * if the security descriptor it provided did not have a SACL. By
2310 * default, in this case we try to recover and set as much of the
2311 * security descriptor as possible --- potentially excluding the DACL, and
2312 * even the owner, as well as the SACL.
2315 info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
2316 DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION |
2317 LABEL_SECURITY_INFORMATION | BACKUP_SECURITY_INFORMATION;
2321 * It's also worth noting that SetFileSecurity() is unusable because it
2322 * doesn't request "backup semantics" when it opens the file internally.
2323 * NtSetSecurityObject() seems to be the best function to use in backup
2324 * applications. (SetSecurityInfo() should also work, but it's harder
2325 * to use and must call NtSetSecurityObject() internally anyway.
2326 * BackupWrite() is theoretically usable as well, but it's inflexible
2327 * and poorly documented.)
2331 status = (*func_NtSetSecurityObject)(h, info, desc);
2332 if (NT_SUCCESS(status))
2333 goto out_maybe_free_desc;
2335 /* Failed to set the requested parts of the security descriptor. If the
2336 * error was permissions-related, try to set fewer parts of the security
2337 * descriptor, unless WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled. */
2338 if ((status == STATUS_PRIVILEGE_NOT_HELD ||
2339 status == STATUS_ACCESS_DENIED) &&
2340 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2342 if (info & SACL_SECURITY_INFORMATION) {
2343 info &= ~(SACL_SECURITY_INFORMATION |
2344 LABEL_SECURITY_INFORMATION |
2345 BACKUP_SECURITY_INFORMATION);
2346 ctx->partial_security_descriptors++;
2349 if (info & DACL_SECURITY_INFORMATION) {
2350 info &= ~DACL_SECURITY_INFORMATION;
2353 if (info & OWNER_SECURITY_INFORMATION) {
2354 info &= ~OWNER_SECURITY_INFORMATION;
2357 /* Nothing left except GROUP, and if we removed it we
2358 * wouldn't have anything at all. */
2361 /* No part of the security descriptor could be set, or
2362 * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled and the full security
2363 * descriptor could not be set. */
2364 if (!(info & SACL_SECURITY_INFORMATION))
2365 ctx->partial_security_descriptors--;
2366 ctx->no_security_descriptors++;
2368 out_maybe_free_desc:
2369 if (unlikely(desc_size > STACK_MAX))
2374 /* Set metadata on the open file @h from the WIM inode @inode. */
2376 do_apply_metadata_to_file(HANDLE h, const struct wim_inode *inode,
2377 struct win32_apply_ctx *ctx)
2379 FILE_BASIC_INFORMATION info;
2382 /* Set security descriptor if present and not in NO_ACLS mode */
2383 if (inode->i_security_id >= 0 &&
2384 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
2386 const struct wim_security_data *sd;
2390 sd = wim_get_current_security_data(ctx->common.wim);
2391 desc = sd->descriptors[inode->i_security_id];
2392 desc_size = sd->sizes[inode->i_security_id];
2394 status = set_security_descriptor(h, desc, desc_size, ctx);
2395 if (!NT_SUCCESS(status) &&
2396 (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2398 set_errno_from_nt_status(status);
2399 ERROR_WITH_ERRNO("Can't set security descriptor "
2400 "on \"%ls\" (status=0x%08"PRIx32")",
2401 current_path(ctx), (u32)status);
2402 return WIMLIB_ERR_SET_SECURITY;
2406 /* Set attributes and timestamps */
2407 info.CreationTime.QuadPart = inode->i_creation_time;
2408 info.LastAccessTime.QuadPart = inode->i_last_access_time;
2409 info.LastWriteTime.QuadPart = inode->i_last_write_time;
2410 info.ChangeTime.QuadPart = 0;
2411 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
2412 info.FileAttributes = 0;
2414 info.FileAttributes = inode->i_attributes & ~SPECIAL_ATTRIBUTES;
2416 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
2417 &info, sizeof(info),
2418 FileBasicInformation);
2419 /* On FAT volumes we get STATUS_INVALID_PARAMETER if we try to set
2420 * attributes on the root directory. (Apparently because FAT doesn't
2421 * actually have a place to store those attributes!) */
2422 if (!NT_SUCCESS(status)
2423 && !(status == STATUS_INVALID_PARAMETER &&
2424 dentry_is_root(inode_first_extraction_dentry(inode))))
2426 set_errno_from_nt_status(status);
2427 ERROR_WITH_ERRNO("Can't set basic metadata on \"%ls\" "
2428 "(status=0x%08"PRIx32")",
2429 current_path(ctx), (u32)status);
2430 return WIMLIB_ERR_SET_ATTRIBUTES;
2437 apply_metadata_to_file(const struct wim_dentry *dentry,
2438 struct win32_apply_ctx *ctx)
2440 const struct wim_inode *inode = dentry->d_inode;
2446 perms = FILE_WRITE_ATTRIBUTES | WRITE_DAC |
2447 WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
2449 build_extraction_path(dentry, ctx);
2451 /* Open a handle with as many relevant permissions as possible. */
2452 while (!NT_SUCCESS(status = do_create_file(&h, perms, NULL,
2453 0, FILE_OPEN, 0, ctx)))
2455 if (status == STATUS_PRIVILEGE_NOT_HELD ||
2456 status == STATUS_ACCESS_DENIED)
2458 if (perms & ACCESS_SYSTEM_SECURITY) {
2459 perms &= ~ACCESS_SYSTEM_SECURITY;
2462 if (perms & WRITE_DAC) {
2463 perms &= ~WRITE_DAC;
2466 if (perms & WRITE_OWNER) {
2467 perms &= ~WRITE_OWNER;
2471 set_errno_from_nt_status(status);
2472 ERROR_WITH_ERRNO("Can't open \"%ls\" to set metadata "
2473 "(status=0x%08"PRIx32")",
2474 current_path(ctx), (u32)status);
2475 return WIMLIB_ERR_OPEN;
2478 ret = do_apply_metadata_to_file(h, inode, ctx);
2486 apply_metadata(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
2488 const struct wim_dentry *dentry;
2491 /* We go in reverse so that metadata is set on all a directory's
2492 * children before the directory itself. This avoids any potential
2493 * problems with attributes, timestamps, or security descriptors. */
2494 list_for_each_entry_reverse(dentry, dentry_list, d_extraction_list_node)
2496 ret = apply_metadata_to_file(dentry, ctx);
2497 ret = check_apply_error(dentry, ctx, ret);
2500 ret = report_file_metadata_applied(&ctx->common);
2507 /* Issue warnings about problems during the extraction for which warnings were
2508 * not already issued (due to the high number of potential warnings if we issued
2509 * them per-file). */
2511 do_warnings(const struct win32_apply_ctx *ctx)
2513 if (ctx->partial_security_descriptors == 0
2514 && ctx->no_security_descriptors == 0
2515 && ctx->num_set_short_name_failures == 0
2517 && ctx->num_remove_short_name_failures == 0
2522 WARNING("Extraction to \"%ls\" complete, but with one or more warnings:",
2523 ctx->common.target);
2524 if (ctx->num_set_short_name_failures) {
2525 WARNING("- Could not set short names on %lu files or directories",
2526 ctx->num_set_short_name_failures);
2529 if (ctx->num_remove_short_name_failures) {
2530 WARNING("- Could not remove short names on %lu files or directories"
2531 " (This is expected on Vista and earlier)",
2532 ctx->num_remove_short_name_failures);
2535 if (ctx->partial_security_descriptors) {
2536 WARNING("- Could only partially set the security descriptor\n"
2537 " on %lu files or directories.",
2538 ctx->partial_security_descriptors);
2540 if (ctx->no_security_descriptors) {
2541 WARNING("- Could not set security descriptor at all\n"
2542 " on %lu files or directories.",
2543 ctx->no_security_descriptors);
2545 if (ctx->partial_security_descriptors || ctx->no_security_descriptors) {
2546 WARNING("To fully restore all security descriptors, run the program\n"
2547 " with Administrator rights.");
2552 count_dentries(const struct list_head *dentry_list)
2554 const struct list_head *cur;
2557 list_for_each(cur, dentry_list)
2563 /* Extract files from a WIM image to a directory on Windows */
2565 win32_extract(struct list_head *dentry_list, struct apply_ctx *_ctx)
2568 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
2569 uint64_t dentry_count;
2571 ret = prepare_target(dentry_list, ctx);
2575 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
2576 ret = start_wimboot_extraction(ctx);
2581 dentry_count = count_dentries(dentry_list);
2583 ret = start_file_structure_phase(&ctx->common, dentry_count);
2587 ret = create_directories(dentry_list, ctx);
2591 ret = create_nondirectories(dentry_list, ctx);
2595 ret = end_file_structure_phase(&ctx->common);
2599 struct read_stream_list_callbacks cbs = {
2600 .begin_stream = begin_extract_stream,
2601 .begin_stream_ctx = ctx,
2602 .consume_chunk = extract_chunk,
2603 .consume_chunk_ctx = ctx,
2604 .end_stream = end_extract_stream,
2605 .end_stream_ctx = ctx,
2607 ret = extract_stream_list(&ctx->common, &cbs);
2611 ret = start_file_metadata_phase(&ctx->common, dentry_count);
2615 ret = apply_metadata(dentry_list, ctx);
2619 ret = end_file_metadata_phase(&ctx->common);
2623 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
2624 ret = end_wimboot_extraction(ctx);
2632 (*func_NtClose)(ctx->h_target);
2633 if (ctx->target_ntpath.Buffer)
2634 HeapFree(GetProcessHeap(), 0, ctx->target_ntpath.Buffer);
2635 FREE(ctx->pathbuf.Buffer);
2636 FREE(ctx->print_buffer);
2637 if (ctx->wimboot.prepopulate_pats) {
2638 FREE(ctx->wimboot.prepopulate_pats->strings);
2639 FREE(ctx->wimboot.prepopulate_pats);
2641 FREE(ctx->wimboot.mem_prepopulate_pats);
2642 FREE(ctx->data_buffer);
2646 const struct apply_operations win32_apply_ops = {
2648 .get_supported_features = win32_get_supported_features,
2649 .extract = win32_extract,
2650 .will_externally_back = win32_will_externally_back,
2651 .context_size = sizeof(struct win32_apply_ctx),
2654 #endif /* __WIN32__ */