2 * win32_apply.c - Windows-specific code for applying files from a WIM image.
6 * Copyright (C) 2013, 2014, 2015 Eric Biggers
8 * This file is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU Lesser General Public License as published by the Free
10 * Software Foundation; either version 3 of the License, or (at your option) any
13 * This file is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this file; if not, see http://www.gnu.org/licenses/.
28 #include "wimlib/win32_common.h"
30 #include "wimlib/apply.h"
31 #include "wimlib/assert.h"
32 #include "wimlib/blob_table.h"
33 #include "wimlib/capture.h" /* for mangle_pat() and match_pattern_list() */
34 #include "wimlib/dentry.h"
35 #include "wimlib/encoding.h"
36 #include "wimlib/error.h"
37 #include "wimlib/metadata.h"
38 #include "wimlib/paths.h"
39 #include "wimlib/reparse.h"
40 #include "wimlib/textfile.h"
41 #include "wimlib/xml.h"
42 #include "wimlib/wildcard.h"
43 #include "wimlib/wimboot.h"
45 struct win32_apply_ctx {
47 /* Extract flags, the pointer to the WIMStruct, etc. */
48 struct apply_ctx common;
50 /* WIMBoot information, only filled in if WIMLIB_EXTRACT_FLAG_WIMBOOT
53 /* This array contains the WIM files registered with WOF on the
54 * target volume for this extraction operation. All WIMStructs
55 * in this array are distinct and have ->filename != NULL. */
59 u8 blob_table_hash[SHA1_HASH_SIZE];
62 struct string_set *prepopulate_pats;
63 void *mem_prepopulate_pats;
65 bool tried_to_load_prepopulate_list;
68 /* Open handle to the target directory */
71 /* NT namespace path to the target directory (buffer allocated) */
72 UNICODE_STRING target_ntpath;
74 /* Temporary buffer for building paths (buffer allocated) */
75 UNICODE_STRING pathbuf;
77 /* Object attributes to reuse for opening files in the target directory.
78 * (attr.ObjectName == &pathbuf) and (attr.RootDirectory == h_target).
80 OBJECT_ATTRIBUTES attr;
82 /* Temporary I/O status block for system calls */
85 /* Allocated buffer for creating "printable" paths from our
86 * target-relative NT paths */
87 wchar_t *print_buffer;
89 /* Allocated buffer for reading blob data when it cannot be extracted
93 /* Pointer to the next byte in @data_buffer to fill */
96 /* Size allocated in @data_buffer */
97 size_t data_buffer_size;
99 /* Current offset in the raw encrypted file being written */
100 size_t encrypted_offset;
102 /* Current size of the raw encrypted file being written */
103 size_t encrypted_size;
105 /* Temporary buffer for reparse data */
106 struct reparse_buffer_disk rpbuf;
108 /* Temporary buffer for reparse data of "fixed" absolute symbolic links
110 struct reparse_buffer_disk rpfixbuf;
112 /* Array of open handles to filesystem streams currently being written
114 HANDLE open_handles[MAX_OPEN_FILES];
116 /* Number of handles in @open_handles currently open (filled in from the
117 * beginning of the array) */
118 unsigned num_open_handles;
120 /* List of dentries, joined by @tmp_list, that need to have reparse data
121 * extracted as soon as the whole blob has been read into @data_buffer.
123 struct list_head reparse_dentries;
125 /* List of dentries, joined by @tmp_list, that need to have raw
126 * encrypted data extracted as soon as the whole blob has been read into
128 struct list_head encrypted_dentries;
130 /* Number of files for which we didn't have permission to set the full
131 * security descriptor. */
132 unsigned long partial_security_descriptors;
134 /* Number of files for which we didn't have permission to set any part
135 * of the security descriptor. */
136 unsigned long no_security_descriptors;
138 /* Number of files for which we couldn't set the short name. */
139 unsigned long num_set_short_name_failures;
141 /* Number of files for which we couldn't remove the short name. */
142 unsigned long num_remove_short_name_failures;
144 /* Have we tried to enable short name support on the target volume yet?
146 bool tried_to_enable_short_names;
149 /* Get the drive letter from a Windows path, or return the null character if the
150 * path is relative. */
152 get_drive_letter(const wchar_t *path)
154 /* Skip \\?\ prefix */
155 if (!wcsncmp(path, L"\\\\?\\", 4))
158 /* Return drive letter if valid */
159 if (((path[0] >= L'a' && path[0] <= L'z') ||
160 (path[0] >= L'A' && path[0] <= L'Z')) && path[1] == L':')
167 get_vol_flags(const wchar_t *target, DWORD *vol_flags_ret,
168 bool *short_names_supported_ret)
170 wchar_t filesystem_name[MAX_PATH + 1];
172 wchar_t *volume = NULL;
175 *short_names_supported_ret = false;
177 drive[0] = get_drive_letter(target);
185 if (!GetVolumeInformation(volume, NULL, 0, NULL, NULL,
186 vol_flags_ret, filesystem_name,
187 ARRAY_LEN(filesystem_name)))
189 win32_warning(GetLastError(),
190 L"Failed to get volume information for \"%ls\"",
195 if (wcsstr(filesystem_name, L"NTFS")) {
196 /* FILE_SUPPORTS_HARD_LINKS is only supported on Windows 7 and
197 * later. Force it on anyway if filesystem is NTFS. */
198 *vol_flags_ret |= FILE_SUPPORTS_HARD_LINKS;
200 /* There's no volume flag for short names, but according to the
201 * MS documentation they are only user-settable on NTFS. */
202 *short_names_supported_ret = true;
206 static const wchar_t *
207 current_path(struct win32_apply_ctx *ctx);
210 build_extraction_path(const struct wim_dentry *dentry,
211 struct win32_apply_ctx *ctx);
214 report_dentry_apply_error(const struct wim_dentry *dentry,
215 struct win32_apply_ctx *ctx, int ret)
217 build_extraction_path(dentry, ctx);
218 return report_apply_error(&ctx->common, ret, current_path(ctx));
222 check_apply_error(const struct wim_dentry *dentry,
223 struct win32_apply_ctx *ctx, int ret)
226 ret = report_dentry_apply_error(dentry, ctx, ret);
231 win32_get_supported_features(const wchar_t *target,
232 struct wim_features *supported_features)
235 bool short_names_supported;
237 /* Query the features of the target volume. */
239 get_vol_flags(target, &vol_flags, &short_names_supported);
241 supported_features->archive_files = 1;
242 supported_features->hidden_files = 1;
243 supported_features->system_files = 1;
245 if (vol_flags & FILE_FILE_COMPRESSION)
246 supported_features->compressed_files = 1;
248 if (vol_flags & FILE_SUPPORTS_ENCRYPTION) {
249 supported_features->encrypted_files = 1;
250 supported_features->encrypted_directories = 1;
253 supported_features->not_context_indexed_files = 1;
255 /* Don't do anything with FILE_SUPPORTS_SPARSE_FILES. */
257 if (vol_flags & FILE_NAMED_STREAMS)
258 supported_features->named_data_streams = 1;
260 if (vol_flags & FILE_SUPPORTS_HARD_LINKS)
261 supported_features->hard_links = 1;
263 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS)
264 supported_features->reparse_points = 1;
266 if (vol_flags & FILE_PERSISTENT_ACLS)
267 supported_features->security_descriptors = 1;
269 if (short_names_supported)
270 supported_features->short_names = 1;
272 supported_features->timestamps = 1;
274 /* Note: Windows does not support case sensitive filenames! At least
275 * not without changing the registry and rebooting... */
280 /* Load the patterns from [PrepopulateList] of WimBootCompress.ini in the WIM
281 * image being extracted. */
283 load_prepopulate_pats(struct win32_apply_ctx *ctx)
285 const wchar_t *path = L"\\Windows\\System32\\WimBootCompress.ini";
286 struct wim_dentry *dentry;
287 struct blob_descriptor *blob;
290 struct string_set *s;
292 struct text_file_section sec;
294 ctx->wimboot.tried_to_load_prepopulate_list = true;
296 dentry = get_dentry(ctx->common.wim, path, WIMLIB_CASE_INSENSITIVE);
298 (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
299 FILE_ATTRIBUTE_REPARSE_POINT |
300 FILE_ATTRIBUTE_ENCRYPTED)) ||
301 !(blob = inode_get_blob_for_unnamed_data_stream(dentry->d_inode,
302 ctx->common.wim->blob_table)))
304 WARNING("%ls does not exist in WIM image!", path);
305 return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
308 ret = read_full_blob_into_alloc_buf(blob, &buf);
312 s = CALLOC(1, sizeof(struct string_set));
315 return WIMLIB_ERR_NOMEM;
318 sec.name = T("PrepopulateList");
321 ret = do_load_text_file(path, buf, blob->size, &mem, &sec, 1,
322 LOAD_TEXT_FILE_REMOVE_QUOTES |
323 LOAD_TEXT_FILE_NO_WARNINGS,
325 BUILD_BUG_ON(OS_PREFERRED_PATH_SEPARATOR != WIM_PATH_SEPARATOR);
331 ctx->wimboot.prepopulate_pats = s;
332 ctx->wimboot.mem_prepopulate_pats = mem;
336 /* Returns %true if the specified absolute path to a file in the WIM image
337 * matches a pattern in [PrepopulateList] of WimBootCompress.ini. Otherwise
340 in_prepopulate_list(const wchar_t *path, size_t path_nchars,
341 const struct win32_apply_ctx *ctx)
343 const struct string_set *pats = ctx->wimboot.prepopulate_pats;
345 if (!pats || !pats->num_strings)
348 return match_pattern_list(path, path_nchars, pats);
351 /* Returns %true if the specified absolute path to a file in the WIM image can
352 * be subject to external backing when extracted. Otherwise returns %false. */
354 can_externally_back_path(const wchar_t *path, size_t path_nchars,
355 const struct win32_apply_ctx *ctx)
357 if (in_prepopulate_list(path, path_nchars, ctx))
360 /* Since we attempt to modify the SYSTEM registry after it's extracted
361 * (see end_wimboot_extraction()), it can't be extracted as externally
362 * backed. This extends to associated files such as SYSTEM.LOG that
363 * also must be writable in order to write to the registry. Normally,
364 * SYSTEM is in [PrepopulateList], and the SYSTEM.* files match patterns
365 * in [ExclusionList] and therefore are not captured in the WIM at all.
366 * However, a WIM that wasn't specifically captured in "WIMBoot mode"
367 * may contain SYSTEM.* files. So to make things "just work", hard-code
369 if (match_path(path, path_nchars, L"\\Windows\\System32\\config\\SYSTEM*",
370 OS_PREFERRED_PATH_SEPARATOR, false))
376 #define WIM_BACKING_NOT_ENABLED -1
377 #define WIM_BACKING_NOT_POSSIBLE -2
378 #define WIM_BACKING_EXCLUDED -3
381 will_externally_back_inode(struct wim_inode *inode, struct win32_apply_ctx *ctx,
382 const struct wim_dentry **excluded_dentry_ret)
384 struct list_head *next;
385 struct wim_dentry *dentry;
386 struct blob_descriptor *blob;
389 if (inode->i_can_externally_back)
392 /* This may do redundant checks because the cached value
393 * i_can_externally_back is 2-state (as opposed to 3-state:
394 * unknown/no/yes). But most files can be externally backed, so this
397 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
398 FILE_ATTRIBUTE_REPARSE_POINT |
399 FILE_ATTRIBUTE_ENCRYPTED))
400 return WIM_BACKING_NOT_POSSIBLE;
402 blob = inode_get_blob_for_unnamed_data_stream_resolved(inode);
404 /* Note: Microsoft's WoF driver errors out if it tries to satisfy a
405 * read, with ending offset >= 4 GiB, from an externally backed file. */
407 blob->blob_location != BLOB_IN_WIM ||
408 blob->rdesc->wim != ctx->common.wim ||
409 blob->size != blob->rdesc->uncompressed_size ||
410 blob->size > 4200000000)
411 return WIM_BACKING_NOT_POSSIBLE;
414 * We need to check the patterns in [PrepopulateList] against every name
415 * of the inode, in case any of them match.
417 next = inode->i_extraction_aliases.next;
419 dentry = list_entry(next, struct wim_dentry,
420 d_extraction_alias_node);
422 ret = calculate_dentry_full_path(dentry);
426 if (!can_externally_back_path(dentry->_full_path,
427 wcslen(dentry->_full_path), ctx))
429 if (excluded_dentry_ret)
430 *excluded_dentry_ret = dentry;
431 return WIM_BACKING_EXCLUDED;
434 } while (next != &inode->i_extraction_aliases);
436 inode->i_can_externally_back = 1;
441 * Determines if the unnamed data stream of a file will be created as an
442 * external backing, as opposed to a standard extraction.
445 win32_will_externally_back(struct wim_dentry *dentry, struct apply_ctx *_ctx)
447 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
449 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
450 return WIM_BACKING_NOT_ENABLED;
452 if (!ctx->wimboot.tried_to_load_prepopulate_list)
453 if (load_prepopulate_pats(ctx) == WIMLIB_ERR_NOMEM)
454 return WIMLIB_ERR_NOMEM;
456 return will_externally_back_inode(dentry->d_inode, ctx, NULL);
459 /* Find the WOF registration information for the specified WIM file. */
460 static struct wimboot_wim *
461 find_wimboot_wim(WIMStruct *wim_to_find, struct win32_apply_ctx *ctx)
463 for (size_t i = 0; i < ctx->wimboot.num_wims; i++)
464 if (wim_to_find == ctx->wimboot.wims[i].wim)
465 return &ctx->wimboot.wims[i];
472 set_external_backing(HANDLE h, struct wim_inode *inode, struct win32_apply_ctx *ctx)
475 const struct wim_dentry *excluded_dentry;
476 const struct blob_descriptor *blob;
477 const struct wimboot_wim *wimboot_wim;
479 ret = will_externally_back_inode(inode, ctx, &excluded_dentry);
480 if (ret > 0) /* Error. */
483 if (ret < 0 && ret != WIM_BACKING_EXCLUDED)
484 return 0; /* Not externally backing, other than due to exclusion. */
486 if (unlikely(ret == WIM_BACKING_EXCLUDED)) {
487 /* Not externally backing due to exclusion. */
488 union wimlib_progress_info info;
490 build_extraction_path(excluded_dentry, ctx);
492 info.wimboot_exclude.path_in_wim = excluded_dentry->_full_path;
493 info.wimboot_exclude.extraction_path = current_path(ctx);
495 return call_progress(ctx->common.progfunc,
496 WIMLIB_PROGRESS_MSG_WIMBOOT_EXCLUDE,
497 &info, ctx->common.progctx);
500 /* Externally backing. */
502 blob = inode_get_blob_for_unnamed_data_stream_resolved(inode);
503 wimboot_wim = find_wimboot_wim(blob->rdesc->wim, ctx);
505 if (unlikely(!wimboot_set_pointer(h,
507 wimboot_wim->data_source_id,
508 wimboot_wim->blob_table_hash,
509 ctx->wimboot.wof_running)))
511 const DWORD err = GetLastError();
513 build_extraction_path(inode_first_extraction_dentry(inode), ctx);
514 win32_error(err, L"\"%ls\": Couldn't set WIMBoot pointer data",
516 return WIMLIB_ERR_WIMBOOT;
521 /* Calculates the SHA-1 message digest of the WIM's blob table. */
523 hash_blob_table(WIMStruct *wim, u8 hash[SHA1_HASH_SIZE])
525 return wim_reshdr_to_hash(&wim->hdr.blob_table_reshdr, wim, hash);
529 register_wim_with_wof(WIMStruct *wim, struct win32_apply_ctx *ctx)
531 struct wimboot_wim *p;
534 /* Check if already registered */
535 for (size_t i = 0; i < ctx->wimboot.num_wims; i++)
536 if (wim == ctx->wimboot.wims[i].wim)
539 /* Not yet registered */
541 p = REALLOC(ctx->wimboot.wims,
542 (ctx->wimboot.num_wims + 1) * sizeof(ctx->wimboot.wims[0]));
544 return WIMLIB_ERR_NOMEM;
545 ctx->wimboot.wims = p;
547 ctx->wimboot.wims[ctx->wimboot.num_wims].wim = wim;
549 ret = hash_blob_table(wim, ctx->wimboot.wims[ctx->wimboot.num_wims].blob_table_hash);
553 ret = wimboot_alloc_data_source_id(wim->filename,
555 ctx->common.wim->current_image,
557 &ctx->wimboot.wims[ctx->wimboot.num_wims].data_source_id,
558 &ctx->wimboot.wof_running);
562 ctx->wimboot.num_wims++;
566 /* Prepare for doing a "WIMBoot" extraction by loading patterns from
567 * [PrepopulateList] of WimBootCompress.ini and registering each source WIM file
568 * with WOF on the target volume. */
570 start_wimboot_extraction(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
573 struct wim_dentry *dentry;
575 if (!ctx->wimboot.tried_to_load_prepopulate_list)
576 if (load_prepopulate_pats(ctx) == WIMLIB_ERR_NOMEM)
577 return WIMLIB_ERR_NOMEM;
579 if (!wim_info_get_wimboot(ctx->common.wim->wim_info,
580 ctx->common.wim->current_image))
581 WARNING("Image is not marked as WIMBoot compatible!");
583 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
584 struct blob_descriptor *blob;
586 ret = win32_will_externally_back(dentry, &ctx->common);
587 if (ret > 0) /* Error */
589 if (ret < 0) /* Won't externally back */
592 blob = inode_get_blob_for_unnamed_data_stream_resolved(dentry->d_inode);
593 ret = register_wim_with_wof(blob->rdesc->wim, ctx);
602 build_win32_extraction_path(const struct wim_dentry *dentry,
603 struct win32_apply_ctx *ctx);
605 /* Sets WimBoot=1 in the extracted SYSTEM registry hive.
607 * WIMGAPI does this, and it's possible that it's important.
608 * But I don't know exactly what this value means to Windows. */
610 end_wimboot_extraction(struct win32_apply_ctx *ctx)
612 struct wim_dentry *dentry;
613 wchar_t subkeyname[32];
619 dentry = get_dentry(ctx->common.wim, L"\\Windows\\System32\\config\\SYSTEM",
620 WIMLIB_CASE_INSENSITIVE);
622 if (!dentry || !will_extract_dentry(dentry))
625 if (!will_extract_dentry(wim_get_current_root_dentry(ctx->common.wim)))
628 /* Not bothering to use the native routines (e.g. NtLoadKey()) for this.
629 * If this doesn't work, you probably also have many other problems. */
631 build_win32_extraction_path(dentry, ctx);
633 randomize_char_array_with_alnum(subkeyname, 20);
634 subkeyname[20] = L'\0';
636 res = RegLoadKey(HKEY_LOCAL_MACHINE, subkeyname, ctx->pathbuf.Buffer);
640 wcscpy(&subkeyname[20], L"\\Setup");
642 res = RegCreateKeyEx(HKEY_LOCAL_MACHINE, subkeyname, 0, NULL,
643 REG_OPTION_BACKUP_RESTORE, 0, NULL, &key, NULL);
649 res = RegSetValueEx(key, L"WimBoot", 0, REG_DWORD,
650 (const BYTE *)&value, sizeof(DWORD));
654 res = RegFlushKey(key);
657 res2 = RegCloseKey(key);
661 subkeyname[20] = L'\0';
662 RegUnLoadKey(HKEY_LOCAL_MACHINE, subkeyname);
666 win32_warning(res, L"Failed to set \\Setup: dword \"WimBoot\"=1 "
667 "value in registry hive \"%ls\"",
668 ctx->pathbuf.Buffer);
674 /* Returns the number of wide characters needed to represent the path to the
675 * specified @dentry, relative to the target directory, when extracted.
677 * Does not include null terminator (not needed for NtCreateFile). */
679 dentry_extraction_path_length(const struct wim_dentry *dentry)
682 const struct wim_dentry *d;
686 len += d->d_extraction_name_nchars + 1;
688 } while (!dentry_is_root(d) && will_extract_dentry(d));
690 return --len; /* No leading slash */
693 /* Returns the length of the longest string that might need to be appended to
694 * the path to an alias of an inode to open or create a named data stream.
696 * If the inode has no named data streams, this will be 0. Otherwise, this will
697 * be 1 plus the length of the longest-named data stream, since the data stream
698 * name must be separated from the path by the ':' character. */
700 inode_longest_named_data_stream_spec(const struct wim_inode *inode)
703 for (unsigned i = 0; i < inode->i_num_streams; i++) {
704 const struct wim_inode_stream *strm = &inode->i_streams[i];
705 if (!stream_is_named_data_stream(strm))
707 size_t len = utf16le_len_chars(strm->stream_name);
716 /* Find the length, in wide characters, of the longest path needed for
717 * extraction of any file in @dentry_list relative to the target directory.
719 * Accounts for named data streams, but does not include null terminator (not
720 * needed for NtCreateFile). */
722 compute_path_max(struct list_head *dentry_list)
725 const struct wim_dentry *dentry;
727 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
730 len = dentry_extraction_path_length(dentry);
732 /* Account for named data streams */
733 len += inode_longest_named_data_stream_spec(dentry->d_inode);
742 /* Build the path at which to extract the @dentry, relative to the target
745 * The path is saved in ctx->pathbuf. */
747 build_extraction_path(const struct wim_dentry *dentry,
748 struct win32_apply_ctx *ctx)
752 const struct wim_dentry *d;
754 len = dentry_extraction_path_length(dentry);
756 ctx->pathbuf.Length = len * sizeof(wchar_t);
757 p = ctx->pathbuf.Buffer + len;
759 !dentry_is_root(d->d_parent) && will_extract_dentry(d->d_parent);
762 p -= d->d_extraction_name_nchars;
763 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
766 /* No leading slash */
767 p -= d->d_extraction_name_nchars;
768 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
771 /* Build the path at which to extract the @dentry, relative to the target
772 * directory, adding the suffix for a named data stream.
774 * The path is saved in ctx->pathbuf. */
776 build_extraction_path_with_ads(const struct wim_dentry *dentry,
777 struct win32_apply_ctx *ctx,
778 const wchar_t *stream_name,
779 size_t stream_name_nchars)
783 build_extraction_path(dentry, ctx);
785 /* Add :NAME for named data stream */
786 p = ctx->pathbuf.Buffer + (ctx->pathbuf.Length / sizeof(wchar_t));
788 wmemcpy(p, stream_name, stream_name_nchars);
789 ctx->pathbuf.Length += (1 + stream_name_nchars) * sizeof(wchar_t);
792 /* Build the Win32 namespace path to the specified @dentry when extracted.
794 * The path is saved in ctx->pathbuf and will be null terminated.
796 * XXX: We could get rid of this if it wasn't needed for the file encryption
797 * APIs, and the registry manipulation in WIMBoot mode. */
799 build_win32_extraction_path(const struct wim_dentry *dentry,
800 struct win32_apply_ctx *ctx)
802 build_extraction_path(dentry, ctx);
804 /* Prepend target_ntpath to our relative path, then change \??\ into \\?\ */
806 memmove(ctx->pathbuf.Buffer +
807 (ctx->target_ntpath.Length / sizeof(wchar_t)) + 1,
808 ctx->pathbuf.Buffer, ctx->pathbuf.Length);
809 memcpy(ctx->pathbuf.Buffer, ctx->target_ntpath.Buffer,
810 ctx->target_ntpath.Length);
811 ctx->pathbuf.Buffer[ctx->target_ntpath.Length / sizeof(wchar_t)] = L'\\';
812 ctx->pathbuf.Length += ctx->target_ntpath.Length + sizeof(wchar_t);
813 ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)] = L'\0';
815 wimlib_assert(ctx->pathbuf.Length >= 4 * sizeof(wchar_t) &&
816 !wmemcmp(ctx->pathbuf.Buffer, L"\\??\\", 4));
818 ctx->pathbuf.Buffer[1] = L'\\';
822 /* Returns a "printable" representation of the last relative NT path that was
823 * constructed with build_extraction_path() or build_extraction_path_with_ads().
825 * This will be overwritten by the next call to this function. */
826 static const wchar_t *
827 current_path(struct win32_apply_ctx *ctx)
829 wchar_t *p = ctx->print_buffer;
831 p = wmempcpy(p, ctx->common.target, ctx->common.target_nchars);
833 p = wmempcpy(p, ctx->pathbuf.Buffer, ctx->pathbuf.Length / sizeof(wchar_t));
835 return ctx->print_buffer;
838 /* Open handle to the target directory if it is not already open. If the target
839 * directory does not exist, this creates it. */
841 open_target_directory(struct win32_apply_ctx *ctx)
848 ctx->attr.Length = sizeof(ctx->attr);
849 ctx->attr.RootDirectory = NULL;
850 ctx->attr.ObjectName = &ctx->target_ntpath;
851 status = (*func_NtCreateFile)(&ctx->h_target,
857 FILE_SHARE_VALID_FLAGS,
859 FILE_DIRECTORY_FILE |
860 FILE_OPEN_REPARSE_POINT |
861 FILE_OPEN_FOR_BACKUP_INTENT,
864 if (!NT_SUCCESS(status)) {
865 winnt_error(status, L"Can't open or create directory \"%ls\"",
867 return WIMLIB_ERR_OPENDIR;
869 ctx->attr.RootDirectory = ctx->h_target;
870 ctx->attr.ObjectName = &ctx->pathbuf;
875 close_target_directory(struct win32_apply_ctx *ctx)
878 (*func_NtClose)(ctx->h_target);
879 ctx->h_target = NULL;
880 ctx->attr.RootDirectory = NULL;
885 * Ensures the target directory exists and opens a handle to it, in preparation
886 * of using paths relative to it.
889 prepare_target(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
894 ret = win32_path_to_nt_path(ctx->common.target, &ctx->target_ntpath);
898 ret = open_target_directory(ctx);
902 path_max = compute_path_max(dentry_list);
903 /* Add some extra for building Win32 paths for the file encryption APIs,
904 * and ensure we have at least enough to potentially use a 8.3 name for
905 * the last component. */
906 path_max += max(2 + (ctx->target_ntpath.Length / sizeof(wchar_t)),
909 ctx->pathbuf.MaximumLength = path_max * sizeof(wchar_t);
910 ctx->pathbuf.Buffer = MALLOC(ctx->pathbuf.MaximumLength);
911 if (!ctx->pathbuf.Buffer)
912 return WIMLIB_ERR_NOMEM;
914 ctx->print_buffer = MALLOC((ctx->common.target_nchars + 1 + path_max + 1) *
916 if (!ctx->print_buffer)
917 return WIMLIB_ERR_NOMEM;
922 /* When creating an inode that will have a short (DOS) name, we create it using
923 * the long name associated with the short name. This ensures that the short
924 * name gets associated with the correct long name. */
925 static struct wim_dentry *
926 first_extraction_alias(const struct wim_inode *inode)
928 struct list_head *next = inode->i_extraction_aliases.next;
929 struct wim_dentry *dentry;
932 dentry = list_entry(next, struct wim_dentry,
933 d_extraction_alias_node);
934 if (dentry_has_short_name(dentry))
937 } while (next != &inode->i_extraction_aliases);
942 * Set or clear FILE_ATTRIBUTE_COMPRESSED if the inherited value is different
943 * from the desired value.
945 * Note that you can NOT override the inherited value of
946 * FILE_ATTRIBUTE_COMPRESSED directly with NtCreateFile().
949 adjust_compression_attribute(HANDLE h, const struct wim_dentry *dentry,
950 struct win32_apply_ctx *ctx)
952 const bool compressed = (dentry->d_inode->i_attributes &
953 FILE_ATTRIBUTE_COMPRESSED);
955 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
958 if (!ctx->common.supported_features.compressed_files)
961 FILE_BASIC_INFORMATION info;
963 USHORT compression_state;
965 /* Get current attributes */
966 status = (*func_NtQueryInformationFile)(h, &ctx->iosb,
968 FileBasicInformation);
969 if (NT_SUCCESS(status) &&
970 compressed == !!(info.FileAttributes & FILE_ATTRIBUTE_COMPRESSED))
972 /* Nothing needs to be done. */
976 /* Set the new compression state */
979 compression_state = COMPRESSION_FORMAT_DEFAULT;
981 compression_state = COMPRESSION_FORMAT_NONE;
983 status = (*func_NtFsControlFile)(h,
988 FSCTL_SET_COMPRESSION,
993 if (NT_SUCCESS(status))
996 winnt_error(status, L"Can't %s compression attribute on \"%ls\"",
997 (compressed ? "set" : "clear"), current_path(ctx));
998 return WIMLIB_ERR_SET_ATTRIBUTES;
1001 /* Try to enable short name support on the target volume. If successful, return
1002 * true. If unsuccessful, issue a warning and return false. */
1004 try_to_enable_short_names(const wchar_t *volume)
1007 FILE_FS_PERSISTENT_VOLUME_INFORMATION info;
1009 DWORD bytesReturned;
1011 h = CreateFile(volume, GENERIC_WRITE,
1012 FILE_SHARE_VALID_FLAGS, NULL, OPEN_EXISTING,
1013 FILE_FLAG_BACKUP_SEMANTICS, NULL);
1014 if (h == INVALID_HANDLE_VALUE)
1017 info.VolumeFlags = 0;
1018 info.FlagMask = PERSISTENT_VOLUME_STATE_SHORT_NAME_CREATION_DISABLED;
1022 bret = DeviceIoControl(h, FSCTL_SET_PERSISTENT_VOLUME_STATE,
1023 &info, sizeof(info), NULL, 0,
1024 &bytesReturned, NULL);
1033 win32_warning(GetLastError(),
1034 L"Failed to enable short name support on %ls",
1040 remove_conflicting_short_name(const struct wim_dentry *dentry, struct win32_apply_ctx *ctx)
1046 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1047 (13 * sizeof(wchar_t));
1048 u8 buf[bufsize] _aligned_attribute(8);
1049 bool retried = false;
1050 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1052 memset(buf, 0, bufsize);
1054 /* Build the path with the short name. */
1055 name = &ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)];
1056 while (name != ctx->pathbuf.Buffer && *(name - 1) != L'\\')
1058 end = mempcpy(name, dentry->short_name, dentry->short_name_nbytes);
1059 ctx->pathbuf.Length = ((u8 *)end - (u8 *)ctx->pathbuf.Buffer);
1061 /* Open the conflicting file (by short name). */
1062 status = (*func_NtOpenFile)(&h, GENERIC_WRITE | DELETE,
1063 &ctx->attr, &ctx->iosb,
1064 FILE_SHARE_VALID_FLAGS,
1065 FILE_OPEN_REPARSE_POINT | FILE_OPEN_FOR_BACKUP_INTENT);
1066 if (!NT_SUCCESS(status)) {
1067 winnt_warning(status, L"Can't open \"%ls\"", current_path(ctx));
1072 WARNING("Overriding conflicting short name; path=\"%ls\"",
1076 /* Try to remove the short name on the conflicting file. */
1079 status = (*func_NtSetInformationFile)(h, &ctx->iosb, info, bufsize,
1080 FileShortNameInformation);
1082 if (status == STATUS_INVALID_PARAMETER && !retried) {
1084 /* Microsoft forgot to make it possible to remove short names
1085 * until Windows 7. Oops. Use a random short name instead. */
1087 info->FileNameLength = 12 * sizeof(wchar_t);
1088 for (int i = 0; i < 8; i++)
1089 info->FileName[i] = 'A' + (rand() % 26);
1090 info->FileName[8] = L'.';
1091 info->FileName[9] = L'W';
1092 info->FileName[10] = L'L';
1093 info->FileName[11] = L'B';
1094 info->FileName[12] = L'\0';
1100 build_extraction_path(dentry, ctx);
1104 /* Set the short name on the open file @h which has been created at the location
1105 * indicated by @dentry.
1107 * Note that this may add, change, or remove the short name.
1109 * @h must be opened with DELETE access.
1111 * Returns 0 or WIMLIB_ERR_SET_SHORT_NAME. The latter only happens in
1112 * STRICT_SHORT_NAMES mode.
1115 set_short_name(HANDLE h, const struct wim_dentry *dentry,
1116 struct win32_apply_ctx *ctx)
1119 if (!ctx->common.supported_features.short_names)
1123 * Note: The size of the FILE_NAME_INFORMATION buffer must be such that
1124 * FileName contains at least 2 wide characters (4 bytes). Otherwise,
1125 * NtSetInformationFile() will return STATUS_INFO_LENGTH_MISMATCH. This
1126 * is despite the fact that FileNameLength can validly be 0 or 2 bytes,
1127 * with the former case being removing the existing short name if
1128 * present, rather than setting one.
1130 * The null terminator is seemingly optional, but to be safe we include
1131 * space for it and zero all unused space.
1134 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1135 max(dentry->short_name_nbytes, sizeof(wchar_t)) +
1137 u8 buf[bufsize] _aligned_attribute(8);
1138 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1140 bool tried_to_remove_existing = false;
1142 memset(buf, 0, bufsize);
1144 info->FileNameLength = dentry->short_name_nbytes;
1145 memcpy(info->FileName, dentry->short_name, dentry->short_name_nbytes);
1148 status = (*func_NtSetInformationFile)(h, &ctx->iosb, info, bufsize,
1149 FileShortNameInformation);
1150 if (NT_SUCCESS(status))
1153 if (status == STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME) {
1154 if (dentry->short_name_nbytes == 0)
1156 if (!ctx->tried_to_enable_short_names) {
1160 ctx->tried_to_enable_short_names = true;
1162 ret = win32_get_drive_path(ctx->common.target,
1166 if (try_to_enable_short_names(volume))
1172 * Short names can conflict in several cases:
1174 * - a file being extracted has a short name conflicting with an
1177 * - a file being extracted has a short name conflicting with another
1178 * file being extracted (possible, but shouldn't happen)
1180 * - a file being extracted has a short name that conflicts with the
1181 * automatically generated short name of a file we previously
1182 * extracted, but failed to set the short name for. Sounds unlikely,
1183 * but this actually does happen fairly often on versions of Windows
1184 * prior to Windows 7 because they do not support removing short names
1187 if (unlikely(status == STATUS_OBJECT_NAME_COLLISION) &&
1188 dentry->short_name_nbytes && !tried_to_remove_existing)
1190 tried_to_remove_existing = true;
1191 status = remove_conflicting_short_name(dentry, ctx);
1192 if (NT_SUCCESS(status))
1196 /* By default, failure to set short names is not an error (since short
1197 * names aren't too important anymore...). */
1198 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES)) {
1199 if (dentry->short_name_nbytes)
1200 ctx->num_set_short_name_failures++;
1202 ctx->num_remove_short_name_failures++;
1206 winnt_error(status, L"Can't set short name on \"%ls\"", current_path(ctx));
1207 return WIMLIB_ERR_SET_SHORT_NAME;
1211 * A wrapper around NtCreateFile() to make it slightly more usable...
1212 * This uses the path currently constructed in ctx->pathbuf.
1214 * Also, we always specify FILE_OPEN_FOR_BACKUP_INTENT and
1215 * FILE_OPEN_REPARSE_POINT.
1218 do_create_file(PHANDLE FileHandle,
1219 ACCESS_MASK DesiredAccess,
1220 PLARGE_INTEGER AllocationSize,
1221 ULONG FileAttributes,
1222 ULONG CreateDisposition,
1223 ULONG CreateOptions,
1224 struct win32_apply_ctx *ctx)
1226 return (*func_NtCreateFile)(FileHandle,
1232 FILE_SHARE_VALID_FLAGS,
1235 FILE_OPEN_FOR_BACKUP_INTENT |
1236 FILE_OPEN_REPARSE_POINT,
1241 /* Like do_create_file(), but builds the extraction path of the @dentry first.
1244 create_file(PHANDLE FileHandle,
1245 ACCESS_MASK DesiredAccess,
1246 PLARGE_INTEGER AllocationSize,
1247 ULONG FileAttributes,
1248 ULONG CreateDisposition,
1249 ULONG CreateOptions,
1250 const struct wim_dentry *dentry,
1251 struct win32_apply_ctx *ctx)
1253 build_extraction_path(dentry, ctx);
1254 return do_create_file(FileHandle,
1264 delete_file_or_stream(struct win32_apply_ctx *ctx)
1268 FILE_DISPOSITION_INFORMATION disposition_info;
1269 FILE_BASIC_INFORMATION basic_info;
1270 bool retried = false;
1272 status = do_create_file(&h,
1277 FILE_NON_DIRECTORY_FILE,
1279 if (unlikely(!NT_SUCCESS(status))) {
1280 winnt_error(status, L"Can't open \"%ls\" for deletion",
1282 return WIMLIB_ERR_OPEN;
1286 disposition_info.DoDeleteFile = TRUE;
1287 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1289 sizeof(disposition_info),
1290 FileDispositionInformation);
1292 if (likely(NT_SUCCESS(status)))
1295 if (status == STATUS_CANNOT_DELETE && !retried) {
1296 /* Clear file attributes and try again. This is necessary for
1297 * FILE_ATTRIBUTE_READONLY files. */
1298 status = do_create_file(&h,
1299 FILE_WRITE_ATTRIBUTES | DELETE,
1303 FILE_NON_DIRECTORY_FILE,
1305 if (!NT_SUCCESS(status)) {
1307 L"Can't open \"%ls\" to reset attributes",
1309 return WIMLIB_ERR_OPEN;
1311 memset(&basic_info, 0, sizeof(basic_info));
1312 basic_info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1313 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1316 FileBasicInformation);
1317 if (!NT_SUCCESS(status)) {
1319 L"Can't reset file attributes on \"%ls\"",
1322 return WIMLIB_ERR_SET_ATTRIBUTES;
1327 winnt_error(status, L"Can't delete \"%ls\"", current_path(ctx));
1328 return WIMLIB_ERR_OPEN;
1332 * Create a nondirectory file or named data stream at the current path,
1333 * superseding any that already exists at that path. If successful, return an
1334 * open handle to the file or named data stream.
1337 supersede_file_or_stream(struct win32_apply_ctx *ctx, HANDLE *h_ret)
1340 bool retried = false;
1342 /* FILE_ATTRIBUTE_SYSTEM is needed to ensure that
1343 * FILE_ATTRIBUTE_ENCRYPTED doesn't get set before we want it to be. */
1345 status = do_create_file(h_ret,
1346 GENERIC_READ | GENERIC_WRITE | DELETE,
1348 FILE_ATTRIBUTE_SYSTEM,
1350 FILE_NON_DIRECTORY_FILE,
1352 if (likely(NT_SUCCESS(status)))
1355 /* STATUS_OBJECT_NAME_COLLISION means that the file or stream already
1356 * exists. Delete the existing file or stream, then try again.
1358 * Note: we don't use FILE_OVERWRITE_IF or FILE_SUPERSEDE because of
1359 * problems with certain file attributes, especially
1360 * FILE_ATTRIBUTE_ENCRYPTED. FILE_SUPERSEDE is also broken in the
1361 * Windows PE ramdisk. */
1362 if (status == STATUS_OBJECT_NAME_COLLISION && !retried) {
1363 int ret = delete_file_or_stream(ctx);
1369 winnt_error(status, L"Can't create \"%ls\"", current_path(ctx));
1370 return WIMLIB_ERR_OPEN;
1374 * Create empty named data streams for the specified file, if there are any.
1376 * Since these won't have blob descriptors, they won't show up in the call to
1377 * extract_blob_list(). Hence the need for the special case.
1380 create_empty_named_data_streams(const struct wim_dentry *dentry,
1381 struct win32_apply_ctx *ctx)
1383 const struct wim_inode *inode = dentry->d_inode;
1384 bool path_modified = false;
1387 if (!ctx->common.supported_features.named_data_streams)
1390 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1391 const struct wim_inode_stream *strm = &inode->i_streams[i];
1394 if (!stream_is_named_data_stream(strm) ||
1395 stream_blob_resolved(strm) != NULL)
1398 build_extraction_path_with_ads(dentry, ctx,
1400 utf16le_len_chars(strm->stream_name));
1401 path_modified = true;
1402 ret = supersede_file_or_stream(ctx, &h);
1407 /* Restore the path to the dentry itself */
1409 build_extraction_path(dentry, ctx);
1414 * Creates the directory named by @dentry, or uses an existing directory at that
1415 * location. If necessary, sets the short name and/or fixes compression and
1416 * encryption attributes.
1418 * Returns 0, WIMLIB_ERR_MKDIR, or WIMLIB_ERR_SET_SHORT_NAME.
1421 create_directory(const struct wim_dentry *dentry, struct win32_apply_ctx *ctx)
1428 /* DELETE is needed for set_short_name(); GENERIC_READ and GENERIC_WRITE
1429 * are needed for adjust_compression_attribute(). */
1430 perms = GENERIC_READ | GENERIC_WRITE;
1431 if (!dentry_is_root(dentry))
1434 /* FILE_ATTRIBUTE_SYSTEM is needed to ensure that
1435 * FILE_ATTRIBUTE_ENCRYPTED doesn't get set before we want it to be. */
1436 status = create_file(&h, perms, NULL, FILE_ATTRIBUTE_SYSTEM,
1437 FILE_OPEN_IF, FILE_DIRECTORY_FILE, dentry, ctx);
1438 if (!NT_SUCCESS(status)) {
1439 winnt_error(status, L"Can't create directory \"%ls\"",
1441 return WIMLIB_ERR_MKDIR;
1444 if (ctx->iosb.Information == FILE_OPENED) {
1445 /* If we opened an existing directory, try to clear its file
1446 * attributes. As far as I know, this only actually makes a
1447 * difference in the case where a FILE_ATTRIBUTE_READONLY
1448 * directory has a named data stream which needs to be
1449 * extracted. You cannot create a named data stream of such a
1450 * directory, even though this contradicts Microsoft's
1451 * documentation for FILE_ATTRIBUTE_READONLY which states it is
1452 * not honored for directories! */
1453 FILE_BASIC_INFORMATION basic_info = { .FileAttributes = FILE_ATTRIBUTE_NORMAL };
1454 (*func_NtSetInformationFile)(h, &ctx->iosb, &basic_info,
1455 sizeof(basic_info), FileBasicInformation);
1458 if (!dentry_is_root(dentry)) {
1459 ret = set_short_name(h, dentry, ctx);
1464 ret = adjust_compression_attribute(h, dentry, ctx);
1471 * Create all the directories being extracted, other than the target directory
1474 * Note: we don't honor directory hard links. However, we don't allow them to
1475 * exist in WIM images anyway (see inode_fixup.c).
1478 create_directories(struct list_head *dentry_list,
1479 struct win32_apply_ctx *ctx)
1481 const struct wim_dentry *dentry;
1484 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1486 if (!(dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY))
1489 /* Note: Here we include files with
1490 * FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT, but we
1491 * wait until later to actually set the reparse data. */
1493 ret = create_directory(dentry, ctx);
1496 ret = create_empty_named_data_streams(dentry, ctx);
1498 ret = check_apply_error(dentry, ctx, ret);
1502 ret = report_file_created(&ctx->common);
1510 * Creates the nondirectory file named by @dentry.
1512 * On success, returns an open handle to the file in @h_ret, with GENERIC_READ,
1513 * GENERIC_WRITE, and DELETE access. Also, the path to the file will be saved
1514 * in ctx->pathbuf. On failure, returns an error code.
1517 create_nondirectory_inode(HANDLE *h_ret, const struct wim_dentry *dentry,
1518 struct win32_apply_ctx *ctx)
1523 build_extraction_path(dentry, ctx);
1525 ret = supersede_file_or_stream(ctx, &h);
1529 ret = adjust_compression_attribute(h, dentry, ctx);
1533 ret = create_empty_named_data_streams(dentry, ctx);
1546 /* Creates a hard link at the location named by @dentry to the file represented
1547 * by the open handle @h. Or, if the target volume does not support hard links,
1548 * create a separate file instead. */
1550 create_link(HANDLE h, const struct wim_dentry *dentry,
1551 struct win32_apply_ctx *ctx)
1553 if (ctx->common.supported_features.hard_links) {
1555 build_extraction_path(dentry, ctx);
1557 size_t bufsize = offsetof(FILE_LINK_INFORMATION, FileName) +
1558 ctx->pathbuf.Length + sizeof(wchar_t);
1559 u8 buf[bufsize] _aligned_attribute(8);
1560 FILE_LINK_INFORMATION *info = (FILE_LINK_INFORMATION *)buf;
1563 info->ReplaceIfExists = TRUE;
1564 info->RootDirectory = ctx->attr.RootDirectory;
1565 info->FileNameLength = ctx->pathbuf.Length;
1566 memcpy(info->FileName, ctx->pathbuf.Buffer, ctx->pathbuf.Length);
1567 info->FileName[info->FileNameLength / 2] = L'\0';
1569 /* Note: the null terminator isn't actually necessary,
1570 * but if you don't add the extra character, you get
1571 * STATUS_INFO_LENGTH_MISMATCH when FileNameLength
1572 * happens to be 2 */
1574 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1576 FileLinkInformation);
1577 if (NT_SUCCESS(status))
1579 winnt_error(status, L"Failed to create link \"%ls\"",
1581 return WIMLIB_ERR_LINK;
1586 ret = create_nondirectory_inode(&h2, dentry, ctx);
1590 (*func_NtClose)(h2);
1595 /* Given an inode (represented by the open handle @h) for which one link has
1596 * been created (named by @first_dentry), create the other links.
1598 * Or, if the target volume does not support hard links, create separate files.
1600 * Note: This uses ctx->pathbuf and does not reset it.
1603 create_links(HANDLE h, const struct wim_dentry *first_dentry,
1604 struct win32_apply_ctx *ctx)
1606 const struct wim_inode *inode;
1607 const struct list_head *next;
1608 const struct wim_dentry *dentry;
1611 inode = first_dentry->d_inode;
1612 next = inode->i_extraction_aliases.next;
1614 dentry = list_entry(next, struct wim_dentry,
1615 d_extraction_alias_node);
1616 if (dentry != first_dentry) {
1617 ret = create_link(h, dentry, ctx);
1622 } while (next != &inode->i_extraction_aliases);
1626 /* Create a nondirectory file, including all links. */
1628 create_nondirectory(struct wim_inode *inode, struct win32_apply_ctx *ctx)
1630 struct wim_dentry *first_dentry;
1634 first_dentry = first_extraction_alias(inode);
1636 /* Create first link. */
1637 ret = create_nondirectory_inode(&h, first_dentry, ctx);
1641 /* Set short name. */
1642 ret = set_short_name(h, first_dentry, ctx);
1644 /* Create additional links, OR if hard links are not supported just
1645 * create more files. */
1647 ret = create_links(h, first_dentry, ctx);
1649 /* "WIMBoot" extraction: set external backing by the WIM file if needed. */
1650 if (!ret && unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
1651 ret = set_external_backing(h, inode, ctx);
1657 /* Create all the nondirectory files being extracted, including all aliases
1660 create_nondirectories(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1662 struct wim_dentry *dentry;
1663 struct wim_inode *inode;
1666 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1667 inode = dentry->d_inode;
1668 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1670 /* Call create_nondirectory() only once per inode */
1671 if (dentry == inode_first_extraction_dentry(inode)) {
1672 ret = create_nondirectory(inode, ctx);
1673 ret = check_apply_error(dentry, ctx, ret);
1677 ret = report_file_created(&ctx->common);
1685 close_handles(struct win32_apply_ctx *ctx)
1687 for (unsigned i = 0; i < ctx->num_open_handles; i++)
1688 (*func_NtClose)(ctx->open_handles[i]);
1691 /* Prepare to read the next blob, which has size @blob_size, into an in-memory
1694 prepare_data_buffer(struct win32_apply_ctx *ctx, u64 blob_size)
1696 if (blob_size > ctx->data_buffer_size) {
1697 /* Larger buffer needed. */
1699 if ((size_t)blob_size != blob_size)
1701 new_buffer = REALLOC(ctx->data_buffer, blob_size);
1704 ctx->data_buffer = new_buffer;
1705 ctx->data_buffer_size = blob_size;
1707 /* On the first call this changes data_buffer_ptr from NULL, which tells
1708 * extract_chunk() that the data buffer needs to be filled while reading
1709 * the stream data. */
1710 ctx->data_buffer_ptr = ctx->data_buffer;
1715 begin_extract_blob_instance(const struct blob_descriptor *blob,
1716 struct wim_dentry *dentry,
1717 const struct wim_inode_stream *strm,
1718 struct win32_apply_ctx *ctx)
1720 FILE_ALLOCATION_INFORMATION alloc_info;
1724 if (unlikely(strm->stream_type == STREAM_TYPE_REPARSE_POINT)) {
1725 /* We can't write the reparse point stream directly; we must set
1726 * it with FSCTL_SET_REPARSE_POINT, which requires that all the
1727 * data be available. So, stage the data in a buffer. */
1728 if (!prepare_data_buffer(ctx, blob->size))
1729 return WIMLIB_ERR_NOMEM;
1730 list_add_tail(&dentry->tmp_list, &ctx->reparse_dentries);
1734 if (unlikely(strm->stream_type == STREAM_TYPE_EFSRPC_RAW_DATA)) {
1735 /* We can't write encrypted files directly; we must use
1736 * WriteEncryptedFileRaw(), which requires providing the data
1737 * through a callback function. This can't easily be combined
1738 * with our own callback-based approach.
1740 * The current workaround is to simply read the blob into memory
1741 * and write the encrypted file from that.
1743 * TODO: This isn't sufficient for extremely large encrypted
1744 * files. Perhaps we should create an extra thread to write
1746 if (!prepare_data_buffer(ctx, blob->size))
1747 return WIMLIB_ERR_NOMEM;
1748 list_add_tail(&dentry->tmp_list, &ctx->encrypted_dentries);
1752 /* It's a data stream (may be unnamed or named). */
1753 wimlib_assert(strm->stream_type == STREAM_TYPE_DATA);
1755 if (ctx->num_open_handles == MAX_OPEN_FILES) {
1756 /* XXX: Fix this. But because of the checks in
1757 * extract_blob_list(), this can now only happen on a filesystem
1758 * that does not support hard links. */
1759 ERROR("Can't extract data: too many open files!");
1760 return WIMLIB_ERR_UNSUPPORTED;
1764 if (unlikely(stream_is_named(strm))) {
1765 build_extraction_path_with_ads(dentry, ctx,
1767 utf16le_len_chars(strm->stream_name));
1769 build_extraction_path(dentry, ctx);
1773 /* Open a new handle */
1774 status = do_create_file(&h,
1775 FILE_WRITE_DATA | SYNCHRONIZE,
1776 NULL, 0, FILE_OPEN_IF,
1777 FILE_SEQUENTIAL_ONLY |
1778 FILE_SYNCHRONOUS_IO_NONALERT,
1780 if (!NT_SUCCESS(status)) {
1781 winnt_error(status, L"Can't open \"%ls\" for writing",
1783 return WIMLIB_ERR_OPEN;
1786 ctx->open_handles[ctx->num_open_handles++] = h;
1788 /* Allocate space for the data. */
1789 alloc_info.AllocationSize.QuadPart = blob->size;
1790 (*func_NtSetInformationFile)(h, &ctx->iosb,
1791 &alloc_info, sizeof(alloc_info),
1792 FileAllocationInformation);
1796 /* Set the reparse data @rpbuf of length @rpbuflen on the extracted file
1797 * corresponding to the WIM dentry @dentry. */
1799 do_set_reparse_data(const struct wim_dentry *dentry,
1800 const void *rpbuf, u16 rpbuflen,
1801 struct win32_apply_ctx *ctx)
1806 status = create_file(&h, GENERIC_WRITE, NULL,
1807 0, FILE_OPEN, 0, dentry, ctx);
1808 if (!NT_SUCCESS(status))
1811 status = (*func_NtFsControlFile)(h, NULL, NULL, NULL,
1812 &ctx->iosb, FSCTL_SET_REPARSE_POINT,
1813 (void *)rpbuf, rpbuflen,
1817 if (NT_SUCCESS(status))
1820 /* On Windows, by default only the Administrator can create symbolic
1821 * links for some reason. By default we just issue a warning if this
1822 * appears to be the problem. Use WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS
1823 * to get a hard error. */
1824 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS)
1825 && (status == STATUS_PRIVILEGE_NOT_HELD ||
1826 status == STATUS_ACCESS_DENIED)
1827 && (dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1828 dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1830 WARNING("Can't create symbolic link \"%ls\"! \n"
1831 " (Need Administrator rights, or at least "
1833 " SeCreateSymbolicLink privilege.)",
1839 winnt_error(status, L"Can't set reparse data on \"%ls\"",
1841 return WIMLIB_ERR_SET_REPARSE_DATA;
1844 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1845 * pointer to the suffix of the path that begins with the device directly, such
1846 * as e:\Windows\System32. */
1847 static const wchar_t *
1848 skip_nt_toplevel_component(const wchar_t *path, size_t path_nchars)
1850 static const wchar_t * const dirs[] = {
1855 size_t first_dir_len = 0;
1856 const wchar_t * const end = path + path_nchars;
1858 for (size_t i = 0; i < ARRAY_LEN(dirs); i++) {
1859 size_t len = wcslen(dirs[i]);
1860 if (len <= (end - path) && !wcsnicmp(path, dirs[i], len)) {
1861 first_dir_len = len;
1865 if (first_dir_len == 0)
1867 path += first_dir_len;
1868 while (path != end && *path == L'\\')
1873 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1874 * pointer to the suffix of the path that is device-relative, such as
1877 * The path has an explicit length and is not necessarily null terminated.
1879 * If the path just something like \??\e: then the returned pointer will point
1880 * just past the colon. In this case the length of the result will be 0
1882 static const wchar_t *
1883 get_device_relative_path(const wchar_t *path, size_t path_nchars)
1885 const wchar_t * const orig_path = path;
1886 const wchar_t * const end = path + path_nchars;
1888 path = skip_nt_toplevel_component(path, path_nchars);
1889 if (path == orig_path)
1892 path = wmemchr(path, L'\\', (end - path));
1897 } while (path != end && *path == L'\\');
1902 * Given a reparse point buffer for a symbolic link or junction, adjust its
1903 * contents so that the target of the link is consistent with the new location
1907 try_rpfix(u8 *rpbuf, u16 *rpbuflen_p, struct win32_apply_ctx *ctx)
1909 struct reparse_data rpdata;
1910 size_t orig_subst_name_nchars;
1911 const wchar_t *relpath;
1912 size_t relpath_nchars;
1913 size_t target_ntpath_nchars;
1914 size_t fixed_subst_name_nchars;
1915 const wchar_t *fixed_print_name;
1916 size_t fixed_print_name_nchars;
1918 if (parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata)) {
1919 /* Do nothing if the reparse data is invalid. */
1923 if (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
1924 (rpdata.rpflags & SYMBOLIC_LINK_RELATIVE))
1926 /* Do nothing if it's a relative symbolic link. */
1930 /* Build the new substitute name from the NT namespace path to the
1931 * target directory, then a path separator, then the "device relative"
1932 * part of the old substitute name. */
1934 orig_subst_name_nchars = rpdata.substitute_name_nbytes / sizeof(wchar_t);
1936 relpath = get_device_relative_path(rpdata.substitute_name,
1937 orig_subst_name_nchars);
1938 relpath_nchars = orig_subst_name_nchars -
1939 (relpath - rpdata.substitute_name);
1941 target_ntpath_nchars = ctx->target_ntpath.Length / sizeof(wchar_t);
1943 fixed_subst_name_nchars = target_ntpath_nchars;
1945 fixed_subst_name_nchars += 1 + relpath_nchars;
1946 wchar_t fixed_subst_name[fixed_subst_name_nchars];
1948 wmemcpy(fixed_subst_name, ctx->target_ntpath.Buffer,
1949 target_ntpath_nchars);
1950 if (relpath_nchars) {
1951 fixed_subst_name[target_ntpath_nchars] = L'\\';
1952 wmemcpy(&fixed_subst_name[target_ntpath_nchars + 1],
1953 relpath, relpath_nchars);
1955 /* Doesn't need to be null-terminated. */
1957 /* Print name should be Win32, but not all NT names can even be
1958 * translated to Win32 names. But we can at least delete the top-level
1959 * directory, such as \??\, and this will have the expected result in
1960 * the usual case. */
1961 fixed_print_name = skip_nt_toplevel_component(fixed_subst_name,
1962 fixed_subst_name_nchars);
1963 fixed_print_name_nchars = fixed_subst_name_nchars - (fixed_print_name -
1966 rpdata.substitute_name = fixed_subst_name;
1967 rpdata.substitute_name_nbytes = fixed_subst_name_nchars * sizeof(wchar_t);
1968 rpdata.print_name = (wchar_t *)fixed_print_name;
1969 rpdata.print_name_nbytes = fixed_print_name_nchars * sizeof(wchar_t);
1970 make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
1973 /* Sets reparse data on the specified file. This handles "fixing" the targets
1974 * of absolute symbolic links and junctions if WIMLIB_EXTRACT_FLAG_RPFIX was
1977 set_reparse_data(const struct wim_dentry *dentry,
1978 const void *_rpbuf, u16 rpbuflen, struct win32_apply_ctx *ctx)
1980 const struct wim_inode *inode = dentry->d_inode;
1981 const void *rpbuf = _rpbuf;
1983 if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
1984 && !inode->i_not_rpfixed
1985 && (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1986 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1988 memcpy(&ctx->rpfixbuf, _rpbuf, rpbuflen);
1989 try_rpfix((u8 *)&ctx->rpfixbuf, &rpbuflen, ctx);
1990 rpbuf = &ctx->rpfixbuf;
1992 return do_set_reparse_data(dentry, rpbuf, rpbuflen, ctx);
1996 /* Import the next block of raw encrypted data */
1998 import_encrypted_data(PBYTE pbData, PVOID pvCallbackContext, PULONG Length)
2000 struct win32_apply_ctx *ctx = pvCallbackContext;
2003 copy_len = min(ctx->encrypted_size - ctx->encrypted_offset, *Length);
2004 memcpy(pbData, &ctx->data_buffer[ctx->encrypted_offset], copy_len);
2005 ctx->encrypted_offset += copy_len;
2007 return ERROR_SUCCESS;
2011 * Write the raw encrypted data to the already-created file (or directory)
2012 * corresponding to @dentry.
2014 * The raw encrypted data is provided in ctx->data_buffer, and its size is
2015 * ctx->encrypted_size.
2017 * This function may close the target directory, in which case the caller needs
2018 * to re-open it if needed.
2021 extract_encrypted_file(const struct wim_dentry *dentry,
2022 struct win32_apply_ctx *ctx)
2029 /* Temporarily build a Win32 path for OpenEncryptedFileRaw() */
2030 build_win32_extraction_path(dentry, ctx);
2032 flags = CREATE_FOR_IMPORT | OVERWRITE_HIDDEN;
2033 if (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
2034 flags |= CREATE_FOR_DIR;
2038 err = OpenEncryptedFileRaw(ctx->pathbuf.Buffer, flags, &rawctx);
2039 if (err == ERROR_SHARING_VIOLATION && !retried) {
2040 /* This can be caused by the handle we have open to the target
2041 * directory. Try closing it temporarily. */
2042 close_target_directory(ctx);
2047 /* Restore the NT namespace path */
2048 build_extraction_path(dentry, ctx);
2050 if (err != ERROR_SUCCESS) {
2051 win32_error(err, L"Can't open \"%ls\" for encrypted import",
2053 return WIMLIB_ERR_OPEN;
2056 ctx->encrypted_offset = 0;
2058 err = WriteEncryptedFileRaw(import_encrypted_data, ctx, rawctx);
2060 CloseEncryptedFileRaw(rawctx);
2062 if (err != ERROR_SUCCESS) {
2063 win32_error(err, L"Can't import encrypted file \"%ls\"",
2065 return WIMLIB_ERR_WRITE;
2071 /* Called when starting to read a blob for extraction on Windows */
2073 begin_extract_blob(struct blob_descriptor *blob, void *_ctx)
2075 struct win32_apply_ctx *ctx = _ctx;
2076 const struct blob_extraction_target *targets = blob_extraction_targets(blob);
2079 ctx->num_open_handles = 0;
2080 ctx->data_buffer_ptr = NULL;
2081 INIT_LIST_HEAD(&ctx->reparse_dentries);
2082 INIT_LIST_HEAD(&ctx->encrypted_dentries);
2084 for (u32 i = 0; i < blob->out_refcnt; i++) {
2085 const struct wim_inode *inode = targets[i].inode;
2086 const struct wim_inode_stream *strm = targets[i].stream;
2087 struct wim_dentry *dentry;
2089 /* A copy of the blob needs to be extracted to @inode. */
2091 if (ctx->common.supported_features.hard_links) {
2092 dentry = inode_first_extraction_dentry(inode);
2093 ret = begin_extract_blob_instance(blob, dentry, strm, ctx);
2094 ret = check_apply_error(dentry, ctx, ret);
2098 /* Hard links not supported. Extract the blob
2099 * separately to each alias of the inode. */
2100 struct list_head *next;
2102 next = inode->i_extraction_aliases.next;
2104 dentry = list_entry(next, struct wim_dentry,
2105 d_extraction_alias_node);
2106 ret = begin_extract_blob_instance(blob, dentry, strm, ctx);
2107 ret = check_apply_error(dentry, ctx, ret);
2111 } while (next != &inode->i_extraction_aliases);
2122 /* Called when the next chunk of a blob has been read for extraction on Windows
2125 extract_chunk(const void *chunk, size_t size, void *_ctx)
2127 struct win32_apply_ctx *ctx = _ctx;
2129 /* Write the data chunk to each open handle */
2130 for (unsigned i = 0; i < ctx->num_open_handles; i++) {
2131 u8 *bufptr = (u8 *)chunk;
2132 size_t bytes_remaining = size;
2134 while (bytes_remaining) {
2135 ULONG count = min(0xFFFFFFFF, bytes_remaining);
2137 status = (*func_NtWriteFile)(ctx->open_handles[i],
2139 &ctx->iosb, bufptr, count,
2141 if (!NT_SUCCESS(status)) {
2142 winnt_error(status, L"Error writing data to target volume");
2143 return WIMLIB_ERR_WRITE;
2145 bufptr += ctx->iosb.Information;
2146 bytes_remaining -= ctx->iosb.Information;
2150 /* Copy the data chunk into the buffer (if needed) */
2151 if (ctx->data_buffer_ptr)
2152 ctx->data_buffer_ptr = mempcpy(ctx->data_buffer_ptr,
2157 /* Called when a blob has been fully read for extraction on Windows */
2159 end_extract_blob(struct blob_descriptor *blob, int status, void *_ctx)
2161 struct win32_apply_ctx *ctx = _ctx;
2163 const struct wim_dentry *dentry;
2170 if (likely(!ctx->data_buffer_ptr))
2173 if (!list_empty(&ctx->reparse_dentries)) {
2174 if (blob->size > REPARSE_DATA_MAX_SIZE) {
2175 dentry = list_first_entry(&ctx->reparse_dentries,
2176 struct wim_dentry, tmp_list);
2177 build_extraction_path(dentry, ctx);
2178 ERROR("Reparse data of \"%ls\" has size "
2179 "%"PRIu64" bytes (exceeds %u bytes)",
2180 current_path(ctx), blob->size,
2181 REPARSE_DATA_MAX_SIZE);
2182 ret = WIMLIB_ERR_INVALID_REPARSE_DATA;
2183 return check_apply_error(dentry, ctx, ret);
2185 /* In the WIM format, reparse point streams are just the reparse
2186 * data and omit the header. But we can reconstruct the header.
2188 memcpy(ctx->rpbuf.rpdata, ctx->data_buffer, blob->size);
2189 ctx->rpbuf.rpdatalen = blob->size;
2190 ctx->rpbuf.rpreserved = 0;
2191 list_for_each_entry(dentry, &ctx->reparse_dentries, tmp_list) {
2192 ctx->rpbuf.rptag = dentry->d_inode->i_reparse_tag;
2193 ret = set_reparse_data(dentry, &ctx->rpbuf,
2194 blob->size + REPARSE_DATA_OFFSET,
2196 ret = check_apply_error(dentry, ctx, ret);
2202 if (!list_empty(&ctx->encrypted_dentries)) {
2203 ctx->encrypted_size = blob->size;
2204 list_for_each_entry(dentry, &ctx->encrypted_dentries, tmp_list) {
2205 ret = extract_encrypted_file(dentry, ctx);
2206 ret = check_apply_error(dentry, ctx, ret);
2209 /* Re-open the target directory if needed. */
2210 ret = open_target_directory(ctx);
2219 /* Attributes that can't be set directly */
2220 #define SPECIAL_ATTRIBUTES \
2221 (FILE_ATTRIBUTE_REPARSE_POINT | \
2222 FILE_ATTRIBUTE_DIRECTORY | \
2223 FILE_ATTRIBUTE_ENCRYPTED | \
2224 FILE_ATTRIBUTE_SPARSE_FILE | \
2225 FILE_ATTRIBUTE_COMPRESSED)
2227 /* Set the security descriptor @desc, of @desc_size bytes, on the file with open
2230 set_security_descriptor(HANDLE h, const void *_desc,
2231 size_t desc_size, struct win32_apply_ctx *ctx)
2233 SECURITY_INFORMATION info;
2235 SECURITY_DESCRIPTOR_RELATIVE *desc;
2238 * Ideally, we would just pass in the security descriptor buffer as-is.
2239 * But it turns out that Windows can mess up the security descriptor
2240 * even when using the low-level NtSetSecurityObject() function:
2242 * - Windows will clear SE_DACL_AUTO_INHERITED if it is set in the
2243 * passed buffer. To actually get Windows to set
2244 * SE_DACL_AUTO_INHERITED, the application must set the non-persistent
2245 * flag SE_DACL_AUTO_INHERIT_REQ. As usual, Microsoft didn't bother
2246 * to properly document either of these flags. It's unclear how
2247 * important SE_DACL_AUTO_INHERITED actually is, but to be safe we use
2248 * the SE_DACL_AUTO_INHERIT_REQ workaround to set it if needed.
2250 * - The above also applies to the equivalent SACL flags,
2251 * SE_SACL_AUTO_INHERITED and SE_SACL_AUTO_INHERIT_REQ.
2253 * - If the application says that it's setting
2254 * DACL_SECURITY_INFORMATION, then Windows sets SE_DACL_PRESENT in the
2255 * resulting security descriptor, even if the security descriptor the
2256 * application provided did not have a DACL. This seems to be
2257 * unavoidable, since omitting DACL_SECURITY_INFORMATION would cause a
2258 * default DACL to remain. Fortunately, this behavior seems harmless,
2259 * since the resulting DACL will still be "null" --- but it will be
2260 * "the other representation of null".
2262 * - The above also applies to SACL_SECURITY_INFORMATION and
2263 * SE_SACL_PRESENT. Again, it's seemingly unavoidable but "harmless"
2264 * that Windows changes the representation of a "null SACL".
2266 if (likely(desc_size <= STACK_MAX)) {
2267 desc = alloca(desc_size);
2269 desc = MALLOC(desc_size);
2271 return STATUS_NO_MEMORY;
2274 memcpy(desc, _desc, desc_size);
2276 if (likely(desc_size >= 4)) {
2278 if (desc->Control & SE_DACL_AUTO_INHERITED)
2279 desc->Control |= SE_DACL_AUTO_INHERIT_REQ;
2281 if (desc->Control & SE_SACL_AUTO_INHERITED)
2282 desc->Control |= SE_SACL_AUTO_INHERIT_REQ;
2286 * More API insanity. We want to set the entire security descriptor
2287 * as-is. But all available APIs require specifying the specific parts
2288 * of the security descriptor being set. Especially annoying is that
2289 * mandatory integrity labels are part of the SACL, but they aren't set
2290 * with SACL_SECURITY_INFORMATION. Instead, applications must also
2291 * specify LABEL_SECURITY_INFORMATION (Windows Vista, Windows 7) or
2292 * BACKUP_SECURITY_INFORMATION (Windows 8). But at least older versions
2293 * of Windows don't error out if you provide these newer flags...
2295 * Also, if the process isn't running as Administrator, then it probably
2296 * doesn't have SE_RESTORE_PRIVILEGE. In this case, it will always get
2297 * the STATUS_PRIVILEGE_NOT_HELD error by trying to set the SACL, even
2298 * if the security descriptor it provided did not have a SACL. By
2299 * default, in this case we try to recover and set as much of the
2300 * security descriptor as possible --- potentially excluding the DACL, and
2301 * even the owner, as well as the SACL.
2304 info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
2305 DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION |
2306 LABEL_SECURITY_INFORMATION | BACKUP_SECURITY_INFORMATION;
2310 * It's also worth noting that SetFileSecurity() is unusable because it
2311 * doesn't request "backup semantics" when it opens the file internally.
2312 * NtSetSecurityObject() seems to be the best function to use in backup
2313 * applications. (SetSecurityInfo() should also work, but it's harder
2314 * to use and must call NtSetSecurityObject() internally anyway.
2315 * BackupWrite() is theoretically usable as well, but it's inflexible
2316 * and poorly documented.)
2320 status = (*func_NtSetSecurityObject)(h, info, desc);
2321 if (NT_SUCCESS(status))
2322 goto out_maybe_free_desc;
2324 /* Failed to set the requested parts of the security descriptor. If the
2325 * error was permissions-related, try to set fewer parts of the security
2326 * descriptor, unless WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled. */
2327 if ((status == STATUS_PRIVILEGE_NOT_HELD ||
2328 status == STATUS_ACCESS_DENIED) &&
2329 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2331 if (info & SACL_SECURITY_INFORMATION) {
2332 info &= ~(SACL_SECURITY_INFORMATION |
2333 LABEL_SECURITY_INFORMATION |
2334 BACKUP_SECURITY_INFORMATION);
2335 ctx->partial_security_descriptors++;
2338 if (info & DACL_SECURITY_INFORMATION) {
2339 info &= ~DACL_SECURITY_INFORMATION;
2342 if (info & OWNER_SECURITY_INFORMATION) {
2343 info &= ~OWNER_SECURITY_INFORMATION;
2346 /* Nothing left except GROUP, and if we removed it we
2347 * wouldn't have anything at all. */
2350 /* No part of the security descriptor could be set, or
2351 * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled and the full security
2352 * descriptor could not be set. */
2353 if (!(info & SACL_SECURITY_INFORMATION))
2354 ctx->partial_security_descriptors--;
2355 ctx->no_security_descriptors++;
2357 out_maybe_free_desc:
2358 if (unlikely(desc_size > STACK_MAX))
2363 /* Set metadata on the open file @h from the WIM inode @inode. */
2365 do_apply_metadata_to_file(HANDLE h, const struct wim_inode *inode,
2366 struct win32_apply_ctx *ctx)
2368 FILE_BASIC_INFORMATION info;
2371 /* Set security descriptor if present and not in NO_ACLS mode */
2372 if (inode->i_security_id >= 0 &&
2373 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
2375 const struct wim_security_data *sd;
2379 sd = wim_get_current_security_data(ctx->common.wim);
2380 desc = sd->descriptors[inode->i_security_id];
2381 desc_size = sd->sizes[inode->i_security_id];
2383 status = set_security_descriptor(h, desc, desc_size, ctx);
2384 if (!NT_SUCCESS(status) &&
2385 (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2388 L"Can't set security descriptor on \"%ls\"",
2390 return WIMLIB_ERR_SET_SECURITY;
2394 /* Set attributes and timestamps */
2395 info.CreationTime.QuadPart = inode->i_creation_time;
2396 info.LastAccessTime.QuadPart = inode->i_last_access_time;
2397 info.LastWriteTime.QuadPart = inode->i_last_write_time;
2398 info.ChangeTime.QuadPart = 0;
2399 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES) {
2400 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
2402 info.FileAttributes = inode->i_attributes & ~SPECIAL_ATTRIBUTES;
2403 if (info.FileAttributes == 0)
2404 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
2407 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
2408 &info, sizeof(info),
2409 FileBasicInformation);
2410 /* On FAT volumes we get STATUS_INVALID_PARAMETER if we try to set
2411 * attributes on the root directory. (Apparently because FAT doesn't
2412 * actually have a place to store those attributes!) */
2413 if (!NT_SUCCESS(status)
2414 && !(status == STATUS_INVALID_PARAMETER &&
2415 dentry_is_root(inode_first_extraction_dentry(inode))))
2417 winnt_error(status, L"Can't set basic metadata on \"%ls\"",
2419 return WIMLIB_ERR_SET_ATTRIBUTES;
2426 apply_metadata_to_file(const struct wim_dentry *dentry,
2427 struct win32_apply_ctx *ctx)
2429 const struct wim_inode *inode = dentry->d_inode;
2435 perms = FILE_WRITE_ATTRIBUTES | WRITE_DAC |
2436 WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
2438 build_extraction_path(dentry, ctx);
2440 /* Open a handle with as many relevant permissions as possible. */
2441 while (!NT_SUCCESS(status = do_create_file(&h, perms, NULL,
2442 0, FILE_OPEN, 0, ctx)))
2444 if (status == STATUS_PRIVILEGE_NOT_HELD ||
2445 status == STATUS_ACCESS_DENIED)
2447 if (perms & ACCESS_SYSTEM_SECURITY) {
2448 perms &= ~ACCESS_SYSTEM_SECURITY;
2451 if (perms & WRITE_DAC) {
2452 perms &= ~WRITE_DAC;
2455 if (perms & WRITE_OWNER) {
2456 perms &= ~WRITE_OWNER;
2460 winnt_error(status, L"Can't open \"%ls\" to set metadata",
2462 return WIMLIB_ERR_OPEN;
2465 ret = do_apply_metadata_to_file(h, inode, ctx);
2473 apply_metadata(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
2475 const struct wim_dentry *dentry;
2478 /* We go in reverse so that metadata is set on all a directory's
2479 * children before the directory itself. This avoids any potential
2480 * problems with attributes, timestamps, or security descriptors. */
2481 list_for_each_entry_reverse(dentry, dentry_list, d_extraction_list_node)
2483 ret = apply_metadata_to_file(dentry, ctx);
2484 ret = check_apply_error(dentry, ctx, ret);
2487 ret = report_file_metadata_applied(&ctx->common);
2494 /* Issue warnings about problems during the extraction for which warnings were
2495 * not already issued (due to the high number of potential warnings if we issued
2496 * them per-file). */
2498 do_warnings(const struct win32_apply_ctx *ctx)
2500 if (ctx->partial_security_descriptors == 0
2501 && ctx->no_security_descriptors == 0
2502 && ctx->num_set_short_name_failures == 0
2504 && ctx->num_remove_short_name_failures == 0
2509 WARNING("Extraction to \"%ls\" complete, but with one or more warnings:",
2510 ctx->common.target);
2511 if (ctx->num_set_short_name_failures) {
2512 WARNING("- Could not set short names on %lu files or directories",
2513 ctx->num_set_short_name_failures);
2516 if (ctx->num_remove_short_name_failures) {
2517 WARNING("- Could not remove short names on %lu files or directories"
2518 " (This is expected on Vista and earlier)",
2519 ctx->num_remove_short_name_failures);
2522 if (ctx->partial_security_descriptors) {
2523 WARNING("- Could only partially set the security descriptor\n"
2524 " on %lu files or directories.",
2525 ctx->partial_security_descriptors);
2527 if (ctx->no_security_descriptors) {
2528 WARNING("- Could not set security descriptor at all\n"
2529 " on %lu files or directories.",
2530 ctx->no_security_descriptors);
2532 if (ctx->partial_security_descriptors || ctx->no_security_descriptors) {
2533 WARNING("To fully restore all security descriptors, run the program\n"
2534 " with Administrator rights.");
2539 count_dentries(const struct list_head *dentry_list)
2541 const struct list_head *cur;
2544 list_for_each(cur, dentry_list)
2550 /* Extract files from a WIM image to a directory on Windows */
2552 win32_extract(struct list_head *dentry_list, struct apply_ctx *_ctx)
2555 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
2558 ret = prepare_target(dentry_list, ctx);
2562 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
2563 ret = start_wimboot_extraction(dentry_list, ctx);
2568 dentry_count = count_dentries(dentry_list);
2570 ret = start_file_structure_phase(&ctx->common, dentry_count);
2574 ret = create_directories(dentry_list, ctx);
2578 ret = create_nondirectories(dentry_list, ctx);
2582 ret = end_file_structure_phase(&ctx->common);
2586 struct read_blob_list_callbacks cbs = {
2587 .begin_blob = begin_extract_blob,
2588 .begin_blob_ctx = ctx,
2589 .consume_chunk = extract_chunk,
2590 .consume_chunk_ctx = ctx,
2591 .end_blob = end_extract_blob,
2592 .end_blob_ctx = ctx,
2594 ret = extract_blob_list(&ctx->common, &cbs);
2598 ret = start_file_metadata_phase(&ctx->common, dentry_count);
2602 ret = apply_metadata(dentry_list, ctx);
2606 ret = end_file_metadata_phase(&ctx->common);
2610 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
2611 ret = end_wimboot_extraction(ctx);
2618 close_target_directory(ctx);
2619 if (ctx->target_ntpath.Buffer)
2620 HeapFree(GetProcessHeap(), 0, ctx->target_ntpath.Buffer);
2621 FREE(ctx->pathbuf.Buffer);
2622 FREE(ctx->print_buffer);
2623 FREE(ctx->wimboot.wims);
2624 if (ctx->wimboot.prepopulate_pats) {
2625 FREE(ctx->wimboot.prepopulate_pats->strings);
2626 FREE(ctx->wimboot.prepopulate_pats);
2628 FREE(ctx->wimboot.mem_prepopulate_pats);
2629 FREE(ctx->data_buffer);
2633 const struct apply_operations win32_apply_ops = {
2635 .get_supported_features = win32_get_supported_features,
2636 .extract = win32_extract,
2637 .will_externally_back = win32_will_externally_back,
2638 .context_size = sizeof(struct win32_apply_ctx),
2641 #endif /* __WIN32__ */