4 * Support for extracting WIM images, or files or directories contained in a WIM
9 * Copyright (C) 2012, 2013 Eric Biggers
11 * This file is part of wimlib, a library for working with WIM files.
13 * wimlib is free software; you can redistribute it and/or modify it under the
14 * terms of the GNU General Public License as published by the Free
15 * Software Foundation; either version 3 of the License, or (at your option)
18 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20 * A PARTICULAR PURPOSE. See the GNU General Public License for more
23 * You should have received a copy of the GNU General Public License
24 * along with wimlib; if not, see http://www.gnu.org/licenses/.
28 * This file provides the API functions wimlib_extract_image(),
29 * wimlib_extract_files(), and wimlib_extract_image_from_pipe(). Internally,
30 * all end up calling extract_tree() zero or more times to extract a tree of
31 * files from the currently selected WIM image to the specified target directory
34 * Although wimlib supports multiple extraction modes/backends (NTFS-3g, UNIX,
35 * Win32), this file does not itself have code to extract files or directories
36 * to any specific target; instead, it handles generic functionality and relies
37 * on lower-level callback functions declared in `struct apply_operations' to do
38 * the actual extraction.
45 #include "wimlib/apply.h"
46 #include "wimlib/dentry.h"
47 #include "wimlib/encoding.h"
48 #include "wimlib/endianness.h"
49 #include "wimlib/error.h"
50 #include "wimlib/lookup_table.h"
51 #include "wimlib/metadata.h"
52 #include "wimlib/paths.h"
53 #include "wimlib/reparse.h"
54 #include "wimlib/resource.h"
55 #include "wimlib/security.h"
56 #include "wimlib/swm.h"
58 # include "wimlib/win32.h" /* for realpath() equivalent */
60 #include "wimlib/xml.h"
61 #include "wimlib/wim.h"
69 #define WIMLIB_EXTRACT_FLAG_MULTI_IMAGE 0x80000000
70 #define WIMLIB_EXTRACT_FLAG_FROM_PIPE 0x40000000
71 #define WIMLIB_EXTRACT_MASK_PUBLIC 0x3fffffff
73 /* Given a WIM dentry in the tree to be extracted, resolve all streams in the
74 * corresponding inode and set 'out_refcnt' in each to 0. */
76 dentry_resolve_and_zero_lte_refcnt(struct wim_dentry *dentry, void *_ctx)
78 struct apply_ctx *ctx = _ctx;
79 struct wim_inode *inode = dentry->d_inode;
80 struct wim_lookup_table_entry *lte;
84 if (dentry->extraction_skipped)
87 /* Special case: when extracting from a pipe, the WIM lookup table is
88 * initially empty, so "resolving" an inode's streams is initially not
89 * possible. However, we still need to keep track of which streams,
90 * identified by SHA1 message digests, need to be extracted, so we
91 * "resolve" the inode's streams anyway by allocating new entries. */
92 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE)
94 ret = inode_resolve_ltes(inode, ctx->wim->lookup_table, force);
97 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
98 lte = inode_stream_lte_resolved(inode, i);
106 is_linked_extraction(const struct apply_ctx *ctx)
108 return 0 != (ctx->extract_flags & (WIMLIB_EXTRACT_FLAG_HARDLINK |
109 WIMLIB_EXTRACT_FLAG_SYMLINK));
113 can_extract_named_data_streams(const struct apply_ctx *ctx)
115 return ctx->supported_features.named_data_streams &&
116 !is_linked_extraction(ctx);
120 ref_stream_to_extract(struct wim_lookup_table_entry *lte,
121 struct wim_dentry *dentry, struct apply_ctx *ctx)
126 if (likely(!is_linked_extraction(ctx)) || (lte->out_refcnt == 0 &&
127 lte->extracted_file == NULL))
129 ctx->progress.extract.total_bytes += wim_resource_size(lte);
130 ctx->progress.extract.num_streams++;
133 if (lte->out_refcnt == 0) {
134 list_add_tail(<e->extraction_list, &ctx->stream_list);
135 ctx->num_streams_remaining++;
138 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_SEQUENTIAL) {
139 struct wim_dentry **lte_dentries;
141 /* Append dentry to this stream's array of dentries referencing
142 * it. Use inline array to avoid memory allocation until the
143 * number of dentries becomes too large. */
144 if (lte->out_refcnt < ARRAY_LEN(lte->inline_lte_dentries)) {
145 lte_dentries = lte->inline_lte_dentries;
147 struct wim_dentry **prev_lte_dentries;
148 size_t alloc_lte_dentries;
150 if (lte->out_refcnt == ARRAY_LEN(lte->inline_lte_dentries)) {
151 prev_lte_dentries = NULL;
152 alloc_lte_dentries = ARRAY_LEN(lte->inline_lte_dentries);
154 prev_lte_dentries = lte->lte_dentries;
155 alloc_lte_dentries = lte->alloc_lte_dentries;
158 if (lte->out_refcnt == alloc_lte_dentries) {
159 alloc_lte_dentries *= 2;
160 lte_dentries = REALLOC(prev_lte_dentries,
162 sizeof(lte_dentries[0]));
164 return WIMLIB_ERR_NOMEM;
165 if (prev_lte_dentries == NULL) {
167 lte->inline_lte_dentries,
168 sizeof(lte->inline_lte_dentries));
170 lte->lte_dentries = lte_dentries;
171 lte->alloc_lte_dentries = alloc_lte_dentries;
173 lte_dentries = lte->lte_dentries;
175 lte_dentries[lte->out_refcnt] = dentry;
181 /* Given a WIM dentry in the tree to be extracted, iterate through streams that
182 * need to be extracted. For each one, add it to the list of streams to be
183 * extracted (ctx->stream_list) if not already done so, and also update the
184 * progress information (ctx->progress) with the stream. Furthermore, if doing
185 * a sequential extraction, build a mapping from each the stream to the dentries
188 dentry_add_streams_to_extract(struct wim_dentry *dentry, void *_ctx)
190 struct apply_ctx *ctx = _ctx;
191 struct wim_inode *inode = dentry->d_inode;
194 /* Don't process dentries marked as skipped. */
195 if (dentry->extraction_skipped)
198 /* Don't process additional hard links. */
199 if (inode->i_visited && ctx->supported_features.hard_links)
202 /* The unnamed data stream will always be extracted, except in an
204 if (!inode_is_encrypted_directory(inode)) {
205 ret = ref_stream_to_extract(inode_unnamed_lte_resolved(inode),
211 /* Named data streams will be extracted only if supported in the current
212 * extraction mode and volume, and to avoid complications, if not doing
213 * a linked extraction. */
214 if (can_extract_named_data_streams(ctx)) {
215 for (u16 i = 0; i < inode->i_num_ads; i++) {
216 if (!ads_entry_is_named_stream(&inode->i_ads_entries[i]))
218 ret = ref_stream_to_extract(inode->i_ads_entries[i].lte,
224 inode->i_visited = 1;
228 /* Inform library user of progress of stream extraction following the successful
229 * extraction of a copy of the stream specified by @lte. */
231 update_extract_progress(struct apply_ctx *ctx,
232 const struct wim_lookup_table_entry *lte)
234 wimlib_progress_func_t progress_func = ctx->progress_func;
235 union wimlib_progress_info *progress = &ctx->progress;
237 progress->extract.completed_bytes += wim_resource_size(lte);
239 progress->extract.completed_bytes >= ctx->next_progress)
241 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS, progress);
242 if (progress->extract.completed_bytes >=
243 progress->extract.total_bytes)
245 ctx->next_progress = ~0ULL;
247 ctx->next_progress += progress->extract.total_bytes / 128;
248 if (ctx->next_progress > progress->extract.total_bytes)
249 ctx->next_progress = progress->extract.total_bytes;
255 /* Extract a symbolic link (not directly as reparse data), handling fixing up
256 * the target of absolute symbolic links and updating the extract progress.
258 * @inode must specify the WIM inode for a symbolic link or junction reparse
261 * @lte_override overrides the resource used as the reparse data for the
264 extract_symlink(const tchar *path, struct apply_ctx *ctx,
265 struct wim_inode *inode,
266 struct wim_lookup_table_entry *lte_override)
268 ssize_t bufsize = ctx->ops->path_max;
269 tchar target[bufsize];
275 /* If absolute symbolic link fixups requested, reserve space in the link
276 * target buffer for the absolute path of the target directory. */
277 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
279 buf += ctx->realtarget_nchars;
280 bufsize -= ctx->realtarget_nchars;
283 /* Translate the WIM inode's reparse data into the link target. */
284 sret = wim_inode_readlink(inode, buf, bufsize - 1, lte_override);
287 return WIMLIB_ERR_READLINK;
291 if ((ctx->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX) &&
294 /* Fix absolute symbolic link target to point into the
295 * actual extraction destination. */
296 tmemcpy(target, ctx->realtarget, ctx->realtarget_nchars);
297 fixed_target = target;
299 /* Keep same link target. */
303 /* Call into the apply_operations to create the symbolic link. */
304 DEBUG("Creating symlink \"%"TS"\" => \"%"TS"\"",
306 ret = ctx->ops->create_symlink(fixed_target, path, ctx);
308 ERROR_WITH_ERRNO("Failed to create symlink "
309 "\"%"TS"\" => \"%"TS"\"", path, fixed_target);
313 /* Account for reparse data consumed. */
314 update_extract_progress(ctx,
315 (lte_override ? lte_override :
316 inode_unnamed_lte_resolved(inode)));
319 #endif /* !__WIN32__ */
321 /* Create a file, directory, or symbolic link. */
323 extract_inode(const tchar *path, struct apply_ctx *ctx, struct wim_inode *inode)
328 if (ctx->supported_features.symlink_reparse_points &&
329 !ctx->supported_features.reparse_points &&
330 inode_is_symlink(inode))
332 ret = extract_symlink(path, ctx, inode, NULL);
334 #endif /* !__WIN32__ */
335 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
336 ret = ctx->ops->create_directory(path, ctx, &inode->extract_cookie);
338 ERROR_WITH_ERRNO("Failed to create the directory "
341 } else if ((inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) &&
342 ctx->ops->extract_encrypted_stream_creates_file &&
343 ctx->supported_features.encrypted_files) {
344 ret = ctx->ops->extract_encrypted_stream(
345 path, inode_unnamed_lte_resolved(inode), ctx);
347 ERROR_WITH_ERRNO("Failed to create and extract "
348 "encrypted file \"%"TS"\"", path);
351 ret = ctx->ops->create_file(path, ctx, &inode->extract_cookie);
353 ERROR_WITH_ERRNO("Failed to create the file "
361 extract_hardlink(const tchar *oldpath, const tchar *newpath,
362 struct apply_ctx *ctx)
366 DEBUG("Creating hardlink \"%"TS"\" => \"%"TS"\"", newpath, oldpath);
367 ret = ctx->ops->create_hardlink(oldpath, newpath, ctx);
369 ERROR_WITH_ERRNO("Failed to create hardlink "
370 "\"%"TS"\" => \"%"TS"\"",
378 try_extract_rpfix(u8 *rpbuf,
380 const wchar_t *extract_root_realpath,
381 unsigned extract_root_realpath_nchars)
383 struct reparse_data rpdata;
385 size_t target_nchars;
386 size_t stripped_nchars;
387 wchar_t *stripped_target;
388 wchar_t stripped_target_nchars;
391 utf16lechar *new_target;
392 utf16lechar *new_print_name;
393 size_t new_target_nchars;
394 size_t new_print_name_nchars;
397 ret = parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata);
401 if (extract_root_realpath[0] == L'\0' ||
402 extract_root_realpath[1] != L':' ||
403 extract_root_realpath[2] != L'\\')
404 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
406 ret = parse_substitute_name(rpdata.substitute_name,
407 rpdata.substitute_name_nbytes,
411 stripped_nchars = ret;
412 target = rpdata.substitute_name;
413 target_nchars = rpdata.substitute_name_nbytes / sizeof(utf16lechar);
414 stripped_target = target + stripped_nchars;
415 stripped_target_nchars = target_nchars - stripped_nchars;
417 new_target = alloca((6 + extract_root_realpath_nchars +
418 stripped_target_nchars) * sizeof(utf16lechar));
421 if (stripped_nchars == 6) {
422 /* Include \??\ prefix if it was present before */
423 p = wmempcpy(p, L"\\??\\", 4);
426 /* Print name excludes the \??\ if present. */
428 if (stripped_nchars != 0) {
429 /* Get drive letter from real path to extract root, if a drive
430 * letter was present before. */
431 *p++ = extract_root_realpath[0];
432 *p++ = extract_root_realpath[1];
434 /* Copy the rest of the extract root */
435 p = wmempcpy(p, extract_root_realpath + 2, extract_root_realpath_nchars - 2);
437 /* Append the stripped target */
438 p = wmempcpy(p, stripped_target, stripped_target_nchars);
439 new_target_nchars = p - new_target;
440 new_print_name_nchars = p - new_print_name;
442 if (new_target_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE ||
443 new_print_name_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE)
444 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
446 rpdata.substitute_name = new_target;
447 rpdata.substitute_name_nbytes = new_target_nchars * sizeof(utf16lechar);
448 rpdata.print_name = new_print_name;
449 rpdata.print_name_nbytes = new_print_name_nchars * sizeof(utf16lechar);
450 return make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
452 #endif /* __WIN32__ */
454 /* Set reparse data on extracted file or directory that has
455 * FILE_ATTRIBUTE_REPARSE_POINT set. */
457 extract_reparse_data(const tchar *path, struct apply_ctx *ctx,
458 struct wim_inode *inode,
459 struct wim_lookup_table_entry *lte_override)
462 u8 rpbuf[REPARSE_POINT_MAX_SIZE];
465 ret = wim_inode_get_reparse_data(inode, rpbuf, &rpbuflen, lte_override);
470 /* Fix up target of absolute symbolic link or junction points so
471 * that they point into the actual extraction target. */
472 if ((ctx->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX) &&
473 (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
474 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT) &&
475 !inode->i_not_rpfixed)
477 ret = try_extract_rpfix(rpbuf, &rpbuflen, ctx->realtarget,
478 ctx->realtarget_nchars);
479 if (ret && !(ctx->extract_flags &
480 WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS))
482 WARNING("Reparse point fixup of \"%"TS"\" "
491 ret = ctx->ops->set_reparse_data(path, rpbuf, rpbuflen, ctx);
493 /* On Windows, the SeCreateSymbolicLink privilege is required to create
494 * symbolic links. To be more friendly towards non-Administrator users,
495 * we merely warn the user if symbolic links cannot be created due to
496 * insufficient permissions or privileges, unless
497 * WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS was provided. */
499 if (ret && inode_is_symlink(inode) &&
500 (errno == EACCES || errno == EPERM) &&
501 !(ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS))
503 WARNING("Can't set reparse data on \"%"TS"\": "
505 " You may be trying to "
506 "extract a symbolic link without the\n"
507 " SeCreateSymbolicLink privilege, "
508 "which by default non-Administrator\n"
509 " accounts do not have.",
517 /* Account for reparse data consumed. */
518 update_extract_progress(ctx,
519 (lte_override ? lte_override :
520 inode_unnamed_lte_resolved(inode)));
524 ERROR_WITH_ERRNO("Failed to set reparse data on \"%"TS"\"", path);
529 * Extract zero or more streams to a file.
531 * This function operates slightly differently depending on whether @lte_spec is
532 * NULL or not. When @lte_spec is NULL, the behavior is to extract the default
533 * file contents (unnamed stream), and, if named data streams are supported in
534 * the extract mode and volume, any named data streams. When @lte_spec is NULL,
535 * the behavior is to extract only all copies of the stream @lte_spec, and in
536 * addition use @lte_spec to set the reparse data or create the symbolic link if
540 * Path to file to extract (as can be passed to apply_operations
545 * WIM dentry that corresponds to the file being extracted.
547 * If non-NULL, specifies the lookup table entry for a stream to extract,
548 * and only that stream will be extracted (although there may be more than
549 * one instance of it).
551 * Used only if @lte_spec != NULL; it is passed to the extraction functions
552 * rather than @lte_spec, allowing the location of the stream to be
553 * overridden. (This is used when the WIM is being read from a nonseekable
554 * file, such as a pipe, when streams need to be used more than once; each
555 * such stream is extracted to a temporary file.)
558 extract_streams(const tchar *path, struct apply_ctx *ctx,
559 struct wim_dentry *dentry,
560 struct wim_lookup_table_entry *lte_spec,
561 struct wim_lookup_table_entry *lte_override)
563 struct wim_inode *inode = dentry->d_inode;
564 struct wim_lookup_table_entry *lte;
565 file_spec_t file_spec;
568 if (dentry->was_hardlinked)
575 for (unsigned i = 0; i < SHA1_HASH_SIZE; i++)
576 p += sprintf(p, "%02x", lte_override->hash[i]);
577 DEBUG("Extracting stream SHA1=%s to \"%"TS"\"",
578 sha1_str, path, inode->i_ino);
580 DEBUG("Extracting streams to \"%"TS"\"", path, inode->i_ino);
584 if (ctx->ops->uses_cookies)
585 file_spec.cookie = inode->extract_cookie;
587 file_spec.path = path;
589 /* Unnamed data stream. */
590 lte = inode_unnamed_lte_resolved(inode);
591 if (lte && (!lte_spec || lte == lte_spec)) {
594 if (!(inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
595 FILE_ATTRIBUTE_REPARSE_POINT)))
597 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED &&
598 ctx->supported_features.encrypted_files) {
599 if (!ctx->ops->extract_encrypted_stream_creates_file) {
600 ret = ctx->ops->extract_encrypted_stream(
606 ret = ctx->ops->extract_unnamed_stream(
607 file_spec, lte, ctx);
611 update_extract_progress(ctx, lte);
613 else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
616 if (ctx->supported_features.reparse_points)
617 ret = extract_reparse_data(path, ctx, inode, lte);
619 else if ((inode_is_symlink(inode) &&
620 ctx->supported_features.symlink_reparse_points))
621 ret = extract_symlink(path, ctx, inode, lte);
628 /* Named data streams. */
629 if (can_extract_named_data_streams(ctx)) {
630 for (u16 i = 0; i < inode->i_num_ads; i++) {
631 struct wim_ads_entry *entry = &inode->i_ads_entries[i];
633 if (!ads_entry_is_named_stream(entry))
638 if (lte_spec && lte_spec != lte)
642 ret = ctx->ops->extract_named_stream(file_spec, entry->stream_name,
643 entry->stream_name_nbytes / 2,
647 update_extract_progress(ctx, lte);
653 ERROR_WITH_ERRNO("Failed to extract data of \"%"TS"\"", path);
657 /* Set attributes on an extracted file or directory if supported by the
658 * extraction mode. */
660 extract_file_attributes(const tchar *path, struct apply_ctx *ctx,
661 struct wim_dentry *dentry, unsigned pass)
665 if (ctx->ops->set_file_attributes &&
666 !(dentry == ctx->extract_root && ctx->root_dentry_is_special)) {
667 u32 attributes = dentry->d_inode->i_attributes;
669 /* Clear unsupported attributes. */
670 attributes &= ctx->supported_attributes_mask;
672 if ((attributes & FILE_ATTRIBUTE_DIRECTORY &&
673 !ctx->supported_features.encrypted_directories) ||
674 (!(attributes & FILE_ATTRIBUTE_DIRECTORY) &&
675 !ctx->supported_features.encrypted_files))
677 attributes &= ~FILE_ATTRIBUTE_ENCRYPTED;
681 attributes = FILE_ATTRIBUTE_NORMAL;
683 ret = ctx->ops->set_file_attributes(path, attributes, ctx, pass);
685 ERROR_WITH_ERRNO("Failed to set attributes on "
694 /* Set or remove the short (DOS) name on an extracted file or directory if
695 * supported by the extraction mode. Since DOS names are unimportant and it's
696 * easy to run into problems setting them on Windows (SetFileShortName()
697 * requires SE_RESTORE privilege, which only the Administrator can request, and
698 * also requires DELETE access to the file), failure is ignored unless
699 * WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES is set. */
701 extract_short_name(const tchar *path, struct apply_ctx *ctx,
702 struct wim_dentry *dentry)
706 /* The root of the dentry tree being extracted may not be extracted to
707 * its original name, so its short name should be ignored. */
708 if (dentry == ctx->extract_root)
711 if (ctx->supported_features.short_names) {
712 ret = ctx->ops->set_short_name(path,
714 dentry->short_name_nbytes / 2,
716 if (ret && (ctx->extract_flags &
717 WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES))
719 ERROR_WITH_ERRNO("Failed to set short name of "
727 /* Set security descriptor, UNIX data, or neither on an extracted file, taking
728 * into account the current extraction mode and flags. */
730 extract_security(const tchar *path, struct apply_ctx *ctx,
731 struct wim_dentry *dentry)
734 struct wim_inode *inode = dentry->d_inode;
736 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
739 if ((ctx->extract_root == dentry) && ctx->root_dentry_is_special)
743 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
744 struct wimlib_unix_data data;
746 ret = inode_get_unix_data(inode, &data, NULL);
750 ret = ctx->ops->set_unix_data(path, &data, ctx);
752 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
753 ERROR_WITH_ERRNO("Failed to set UNIX owner, "
754 "group, and/or mode on "
758 WARNING_WITH_ERRNO("Failed to set UNIX owner, "
759 "group, and/or/mode on "
765 #endif /* __WIN32__ */
766 if (ctx->supported_features.security_descriptors &&
767 inode->i_security_id != -1)
769 const struct wim_security_data *sd;
773 sd = wim_const_security_data(ctx->wim);
774 desc = sd->descriptors[inode->i_security_id];
775 desc_size = sd->sizes[inode->i_security_id];
777 ret = ctx->ops->set_security_descriptor(path, desc,
780 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
781 ERROR_WITH_ERRNO("Failed to set security "
782 "descriptor on \"%"TS"\"", path);
786 if (errno != EACCES) {
787 WARNING_WITH_ERRNO("Failed to set "
788 "security descriptor "
789 "on \"%"TS"\"", path);
792 ctx->no_security_descriptors++;
799 /* Set timestamps on an extracted file. Failure is warning-only unless
800 * WIMLIB_EXTRACT_FLAG_STRICT_TIMESTAMPS is set. */
802 extract_timestamps(const tchar *path, struct apply_ctx *ctx,
803 struct wim_dentry *dentry)
805 struct wim_inode *inode = dentry->d_inode;
808 if ((ctx->extract_root == dentry) && ctx->root_dentry_is_special)
811 if (ctx->ops->set_timestamps) {
812 ret = ctx->ops->set_timestamps(path,
813 inode->i_creation_time,
814 inode->i_last_write_time,
815 inode->i_last_access_time,
818 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_TIMESTAMPS) {
819 ERROR_WITH_ERRNO("Failed to set timestamps "
820 "on \"%"TS"\"", path);
823 WARNING_WITH_ERRNO("Failed to set timestamps "
824 "on \"%"TS"\"", path);
831 /* Check whether the extraction of a dentry should be skipped completely. */
833 dentry_is_supported(struct wim_dentry *dentry,
834 const struct wim_features *supported_features)
836 struct wim_inode *inode = dentry->d_inode;
838 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
839 return supported_features->reparse_points ||
840 (inode_is_symlink(inode) &&
841 supported_features->symlink_reparse_points);
843 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
844 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
845 return supported_features->encrypted_directories != 0;
847 return supported_features->encrypted_files != 0;
852 /* Given a WIM dentry to extract, build the path to which to extract it, in the
853 * format understood by the callbacks in the apply_operations being used.
855 * Write the resulting path into @path, which must have room for at least
856 * ctx->ops->max_path characters including the null-terminator.
858 * Return %true if successful; %false if this WIM dentry doesn't actually need
859 * to be extracted or if the calculated path exceeds ctx->ops->max_path
862 * This function clobbers the tmp_list member of @dentry and its ancestors up
863 * until the extraction root. */
865 build_extraction_path(tchar path[], struct wim_dentry *dentry,
866 struct apply_ctx *ctx)
869 LIST_HEAD(ancestor_list);
871 const tchar *target_prefix;
872 size_t target_prefix_nchars;
873 struct wim_dentry *d;
875 if (dentry->extraction_skipped)
878 path_nchars = ctx->ops->path_prefix_nchars;
880 if (ctx->ops->requires_realtarget_in_paths) {
881 target_prefix = ctx->realtarget;
882 target_prefix_nchars = ctx->realtarget_nchars;
883 } else if (ctx->ops->requires_target_in_paths) {
884 target_prefix = ctx->target;
885 target_prefix_nchars = ctx->target_nchars;
887 target_prefix = NULL;
888 target_prefix_nchars = 0;
890 path_nchars += target_prefix_nchars;
892 for (d = dentry; d != ctx->extract_root; d = d->parent) {
893 path_nchars += d->extraction_name_nchars + 1;
894 list_add(&d->tmp_list, &ancestor_list);
897 path_nchars++; /* null terminator */
899 if (path_nchars > ctx->ops->path_max) {
900 WARNING("\"%"TS"\": Path too long to extract",
901 dentry_full_path(dentry));
905 p = tmempcpy(p, ctx->ops->path_prefix, ctx->ops->path_prefix_nchars);
906 p = tmempcpy(p, target_prefix, target_prefix_nchars);
907 list_for_each_entry(d, &ancestor_list, tmp_list) {
908 *p++ = ctx->ops->path_separator;
909 p = tmempcpy(p, d->extraction_name, d->extraction_name_nchars);
912 wimlib_assert(p - path == path_nchars);
917 get_num_path_components(const tchar *path, tchar path_separator)
919 unsigned num_components = 0;
921 /* Ignore drive letter. */
922 if (path[0] != L'\0' && path[1] == L':')
927 while (*path == path_separator)
931 while (*path && *path != path_separator)
934 return num_components;
938 extract_multiimage_symlink(const tchar *oldpath, const tchar *newpath,
939 struct apply_ctx *ctx, struct wim_dentry *dentry)
941 size_t num_raw_path_components;
942 const struct wim_dentry *d;
943 size_t num_target_path_components;
948 num_raw_path_components = 0;
949 for (d = dentry; d != ctx->extract_root; d = d->parent)
950 num_raw_path_components++;
952 if (ctx->ops->requires_realtarget_in_paths)
953 num_target_path_components = get_num_path_components(ctx->realtarget,
954 ctx->ops->path_separator);
955 else if (ctx->ops->requires_target_in_paths)
956 num_target_path_components = get_num_path_components(ctx->target,
957 ctx->ops->path_separator);
959 num_target_path_components = 0;
961 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_MULTI_IMAGE) {
962 wimlib_assert(num_target_path_components > 0);
963 num_raw_path_components++;
964 num_target_path_components--;
967 p_old = oldpath + ctx->ops->path_prefix_nchars;
969 if (p_old[0] != L'\0' && p_old[1] == ':')
972 while (*p_old == ctx->ops->path_separator)
974 while (--num_target_path_components) {
975 while (*p_old != ctx->ops->path_separator)
977 while (*p_old == ctx->ops->path_separator)
981 tchar symlink_target[tstrlen(p_old) + 3 * num_raw_path_components + 1];
983 p = &symlink_target[0];
984 while (num_raw_path_components--) {
987 *p++ = ctx->ops->path_separator;
990 DEBUG("Creating symlink \"%"TS"\" => \"%"TS"\"",
991 newpath, symlink_target);
992 ret = ctx->ops->create_symlink(symlink_target, newpath, ctx);
994 ERROR_WITH_ERRNO("Failed to create symlink "
995 "\"%"TS"\" => \"%"TS"\"",
996 newpath, symlink_target);
1001 /* Create the "skeleton" of an extracted file or directory. Don't yet extract
1002 * data streams, reparse data (including symbolic links), timestamps, and
1003 * security descriptors. Basically, everything that doesn't require reading
1004 * non-metadata resources from the WIM file and isn't delayed until the final
1007 do_dentry_extract_skeleton(tchar path[], struct wim_dentry *dentry,
1008 struct apply_ctx *ctx)
1010 struct wim_inode *inode = dentry->d_inode;
1012 const tchar *oldpath;
1014 if (unlikely(is_linked_extraction(ctx))) {
1015 struct wim_lookup_table_entry *unnamed_lte;
1017 unnamed_lte = inode_unnamed_lte_resolved(dentry->d_inode);
1018 if (unnamed_lte && unnamed_lte->extracted_file) {
1019 oldpath = unnamed_lte->extracted_file;
1020 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_HARDLINK)
1027 /* Create hard link if this dentry corresponds to an already-extracted
1029 if (inode->i_extracted_file) {
1030 oldpath = inode->i_extracted_file;
1034 /* Skip symlinks unless they can be extracted as reparse points rather
1035 * than created directly. */
1036 if (inode_is_symlink(inode) && !ctx->supported_features.reparse_points)
1039 /* Create this file or directory unless it's the extraction root, which
1040 * was already created if necessary. */
1041 if (dentry != ctx->extract_root) {
1042 ret = extract_inode(path, ctx, inode);
1047 /* Create empty named data streams. */
1048 if (can_extract_named_data_streams(ctx)) {
1049 for (u16 i = 0; i < inode->i_num_ads; i++) {
1050 file_spec_t file_spec;
1051 struct wim_ads_entry *entry = &inode->i_ads_entries[i];
1053 if (!ads_entry_is_named_stream(entry))
1057 if (ctx->ops->uses_cookies)
1058 file_spec.cookie = inode->extract_cookie;
1060 file_spec.path = path;
1061 ret = ctx->ops->extract_named_stream(file_spec,
1063 entry->stream_name_nbytes / 2,
1066 ERROR_WITH_ERRNO("\"%"TS"\": failed to create "
1067 "empty named data stream",
1074 /* Set file attributes (if supported). */
1075 ret = extract_file_attributes(path, ctx, dentry, 0);
1079 /* Set or remove file short name (if supported). */
1080 ret = extract_short_name(path, ctx, dentry);
1084 /* If inode has multiple links and hard links are supported in this
1085 * extraction mode and volume, save the path to the extracted file in
1086 * case it's needed to create a hard link. */
1087 if (unlikely(is_linked_extraction(ctx))) {
1088 struct wim_lookup_table_entry *unnamed_lte;
1090 unnamed_lte = inode_unnamed_lte_resolved(dentry->d_inode);
1092 unnamed_lte->extracted_file = TSTRDUP(path);
1093 if (!unnamed_lte->extracted_file)
1094 return WIMLIB_ERR_NOMEM;
1096 } else if (inode->i_nlink > 1 && ctx->supported_features.hard_links) {
1097 inode->i_extracted_file = TSTRDUP(path);
1098 if (!inode->i_extracted_file)
1099 return WIMLIB_ERR_NOMEM;
1104 ret = extract_multiimage_symlink(oldpath, path, ctx, dentry);
1107 dentry->was_hardlinked = 1;
1111 ret = extract_hardlink(oldpath, path, ctx);
1114 dentry->was_hardlinked = 1;
1119 dentry_extract_skeleton(struct wim_dentry *dentry, void *_ctx)
1121 struct apply_ctx *ctx = _ctx;
1122 tchar path[ctx->ops->path_max];
1123 struct wim_dentry *orig_dentry;
1124 struct wim_dentry *other_dentry;
1127 /* Here we may re-order the extraction of multiple names (hard links)
1128 * for the same file in the same directory in order to ensure the short
1129 * (DOS) name is set correctly. A short name is always associated with
1130 * exactly one long name, and at least on NTFS, only one long name for a
1131 * file can have a short name associated with it. (More specifically,
1132 * there can be unlimited names in the POSIX namespace, but only one
1133 * name can be in the Win32+DOS namespace, or one name in the Win32
1134 * namespace with a corresponding name in the DOS namespace.) To ensure
1135 * the short name of a file is associated with the correct long name in
1136 * a directory, we extract the long name with a corresponding short name
1137 * before any additional names. This can affect NTFS-3g extraction
1138 * (which uses ntfs_set_ntfs_dos_name(), which doesn't allow specifying
1139 * the long name to associate with a short name) and may affect Win32
1140 * extraction as well (which uses SetFileShortName()). */
1142 if (dentry->skeleton_extracted)
1145 if (ctx->supported_features.short_names
1146 && !dentry_has_short_name(dentry)
1147 && !dentry->d_inode->i_dos_name_extracted)
1149 inode_for_each_dentry(other_dentry, dentry->d_inode) {
1150 if (dentry_has_short_name(other_dentry)
1151 && !other_dentry->skeleton_extracted
1152 && other_dentry->parent == dentry->parent)
1154 DEBUG("Creating %"TS" before %"TS" "
1155 "to guarantee correct DOS name extraction",
1156 dentry_full_path(other_dentry),
1157 dentry_full_path(dentry));
1158 orig_dentry = dentry;
1159 dentry = other_dentry;
1165 if (!build_extraction_path(path, dentry, ctx))
1167 ret = do_dentry_extract_skeleton(path, dentry, ctx);
1171 dentry->skeleton_extracted = 1;
1174 dentry = orig_dentry;
1178 dentry->d_inode->i_dos_name_extracted = 1;
1182 /* Create a file or directory, then immediately extract all streams. This
1183 * assumes that WIMLIB_EXTRACT_FLAG_SEQUENTIAL is not specified, since the WIM
1184 * may not be read sequentially by this function. */
1186 dentry_extract(struct wim_dentry *dentry, void *_ctx)
1188 struct apply_ctx *ctx = _ctx;
1189 tchar path[ctx->ops->path_max];
1192 ret = dentry_extract_skeleton(dentry, ctx);
1196 if (!build_extraction_path(path, dentry, ctx))
1199 return extract_streams(path, ctx, dentry, NULL, NULL);
1202 /* Extract all instances of the stream @lte that are being extracted in this
1203 * call of extract_tree(). @can_seek specifies whether the WIM file descriptor
1204 * is seekable or not (e.g. is a pipe). If not and the stream needs to be
1205 * extracted multiple times, it is extracted to a temporary file first.
1207 * This is intended for use with sequential extraction of a WIM image
1208 * (WIMLIB_EXTRACT_FLAG_SEQUENTIAL specified). */
1210 extract_stream_instances(struct wim_lookup_table_entry *lte,
1211 struct apply_ctx *ctx, bool can_seek)
1213 struct wim_dentry **lte_dentries;
1214 struct wim_lookup_table_entry *lte_tmp = NULL;
1215 struct wim_lookup_table_entry *lte_override;
1216 tchar *stream_tmp_filename = NULL;
1217 tchar path[ctx->ops->path_max];
1221 if (lte->out_refcnt <= ARRAY_LEN(lte->inline_lte_dentries))
1222 lte_dentries = lte->inline_lte_dentries;
1224 lte_dentries = lte->lte_dentries;
1226 if (likely(can_seek || lte->out_refcnt < 2)) {
1229 /* Need to extract stream to temporary file. */
1233 stream_tmp_filename = ttempnam(NULL, T("wimlib"));
1234 if (!stream_tmp_filename) {
1235 ERROR_WITH_ERRNO("Failed to create temporary filename");
1236 ret = WIMLIB_ERR_OPEN;
1240 lte_tmp = memdup(lte, sizeof(struct wim_lookup_table_entry));
1242 ret = WIMLIB_ERR_NOMEM;
1243 goto out_free_stream_tmp_filename;
1245 lte_tmp->resource_location = RESOURCE_IN_FILE_ON_DISK;
1246 lte_tmp->file_on_disk = stream_tmp_filename;
1247 lte_override = lte_tmp;
1249 raw_fd = topen(stream_tmp_filename,
1250 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0600);
1252 ERROR_WITH_ERRNO("Failed to open temporary file");
1253 ret = WIMLIB_ERR_OPEN;
1254 goto out_free_lte_tmp;
1256 filedes_init(&fd, raw_fd);
1257 ret = extract_wim_resource_to_fd(lte, &fd,
1258 wim_resource_size(lte));
1259 if (filedes_close(&fd) && !ret)
1260 ret = WIMLIB_ERR_WRITE;
1262 goto out_unlink_stream_tmp_file;
1265 /* Extract all instances of the stream, reading either from the stream
1266 * in the WIM file or from the temporary file containing the stream.
1267 * dentry->tmp_flag is used to ensure that each dentry is processed only
1268 * once regardless of how many times this stream appears in the streams
1269 * of the corresponding inode. */
1270 for (i = 0; i < lte->out_refcnt; i++) {
1271 struct wim_dentry *dentry = lte_dentries[i];
1273 if (dentry->tmp_flag)
1275 if (!build_extraction_path(path, dentry, ctx))
1277 ret = extract_streams(path, ctx, dentry,
1280 goto out_clear_tmp_flags;
1281 dentry->tmp_flag = 1;
1284 out_clear_tmp_flags:
1285 for (i = 0; i < lte->out_refcnt; i++)
1286 lte_dentries[i]->tmp_flag = 0;
1287 out_unlink_stream_tmp_file:
1288 if (stream_tmp_filename)
1289 tunlink(stream_tmp_filename);
1292 out_free_stream_tmp_filename:
1293 FREE(stream_tmp_filename);
1298 /* Extracts a list of streams (ctx.stream_list), assuming that the directory
1299 * structure and empty files were already created. This relies on the
1300 * per-`struct wim_lookup_table_entry' list of dentries that reference each
1301 * stream that was constructed earlier. Streams are extracted exactly in the
1302 * order of the stream list; however, unless the WIM's file descriptor is
1303 * detected to be non-seekable, streams may be read from the WIM file more than
1304 * one time if multiple copies need to be extracted. */
1306 extract_stream_list(struct apply_ctx *ctx)
1308 struct wim_lookup_table_entry *lte;
1312 can_seek = (lseek(ctx->wim->in_fd.fd, 0, SEEK_CUR) != -1);
1313 list_for_each_entry(lte, &ctx->stream_list, extraction_list) {
1314 ret = extract_stream_instances(lte, ctx, can_seek);
1321 #define PWM_ALLOW_WIM_HDR 0x00001
1322 #define PWM_SILENT_EOF 0x00002
1324 /* Read the header from a stream in a pipable WIM. */
1326 read_pwm_stream_header(WIMStruct *pwm, struct wim_lookup_table_entry *lte,
1327 int flags, struct wim_header_disk *hdr_ret)
1330 struct pwm_stream_hdr stream_hdr;
1331 struct wim_header_disk pwm_hdr;
1335 ret = full_read(&pwm->in_fd, &buf.stream_hdr, sizeof(buf.stream_hdr));
1339 if ((flags & PWM_ALLOW_WIM_HDR) && buf.stream_hdr.magic == PWM_MAGIC) {
1340 BUILD_BUG_ON(sizeof(buf.pwm_hdr) < sizeof(buf.stream_hdr));
1341 ret = full_read(&pwm->in_fd, &buf.stream_hdr + 1,
1342 sizeof(buf.pwm_hdr) - sizeof(buf.stream_hdr));
1346 lte->resource_location = RESOURCE_NONEXISTENT;
1347 memcpy(hdr_ret, &buf.pwm_hdr, sizeof(buf.pwm_hdr));
1351 if (buf.stream_hdr.magic != PWM_STREAM_MAGIC) {
1352 ERROR("Data read on pipe is invalid (expected stream header).");
1353 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1356 lte->resource_entry.original_size = le64_to_cpu(buf.stream_hdr.uncompressed_size);
1357 copy_hash(lte->hash, buf.stream_hdr.hash);
1358 lte->resource_entry.flags = le32_to_cpu(buf.stream_hdr.flags);
1359 lte->resource_entry.offset = pwm->in_fd.offset;
1360 lte->resource_location = RESOURCE_IN_WIM;
1362 if (lte->resource_entry.flags & WIM_RESHDR_FLAG_COMPRESSED) {
1363 lte->compression_type = pwm->compression_type;
1364 lte->resource_entry.size = 0;
1366 lte->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1367 lte->resource_entry.size = lte->resource_entry.original_size;
1369 lte->is_pipable = 1;
1373 if (ret != WIMLIB_ERR_UNEXPECTED_END_OF_FILE || !(flags & PWM_SILENT_EOF))
1374 ERROR_WITH_ERRNO("Error reading pipable WIM from pipe");
1378 /* Skip over an unneeded stream in a pipable WIM being read from a pipe. */
1380 skip_pwm_stream(struct wim_lookup_table_entry *lte)
1382 return read_partial_wim_resource(lte, wim_resource_size(lte),
1384 WIMLIB_READ_RESOURCE_FLAG_SEEK_ONLY,
1389 extract_streams_from_pipe(struct apply_ctx *ctx)
1391 struct wim_lookup_table_entry *found_lte;
1392 struct wim_lookup_table_entry *needed_lte;
1393 struct wim_lookup_table *lookup_table;
1394 struct wim_header_disk pwm_hdr;
1398 ret = WIMLIB_ERR_NOMEM;
1399 found_lte = new_lookup_table_entry();
1403 lookup_table = ctx->wim->lookup_table;
1404 pwm_flags = PWM_ALLOW_WIM_HDR;
1405 if ((ctx->extract_flags & WIMLIB_EXTRACT_FLAG_RESUME))
1406 pwm_flags |= PWM_SILENT_EOF;
1407 memcpy(ctx->progress.extract.guid, ctx->wim->hdr.guid, WIM_GID_LEN);
1408 ctx->progress.extract.part_number = ctx->wim->hdr.part_number;
1409 ctx->progress.extract.total_parts = ctx->wim->hdr.total_parts;
1410 if (ctx->progress_func)
1411 ctx->progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_SPWM_PART_BEGIN,
1413 while (ctx->num_streams_remaining) {
1414 ret = read_pwm_stream_header(ctx->wim, found_lte, pwm_flags,
1417 if (ret == WIMLIB_ERR_UNEXPECTED_END_OF_FILE &&
1418 (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_RESUME))
1422 goto out_free_found_lte;
1425 if ((found_lte->resource_location != RESOURCE_NONEXISTENT)
1426 && !(found_lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA)
1427 && (needed_lte = __lookup_resource(lookup_table, found_lte->hash))
1428 && (needed_lte->out_refcnt))
1430 copy_resource_entry(&needed_lte->resource_entry,
1431 &found_lte->resource_entry);
1432 needed_lte->resource_location = found_lte->resource_location;
1433 needed_lte->wim = found_lte->wim;
1434 needed_lte->compression_type = found_lte->compression_type;
1435 needed_lte->is_pipable = found_lte->is_pipable;
1437 ret = extract_stream_instances(needed_lte, ctx, false);
1439 goto out_free_found_lte;
1440 ctx->num_streams_remaining--;
1441 } else if (found_lte->resource_location != RESOURCE_NONEXISTENT) {
1442 ret = skip_pwm_stream(found_lte);
1444 goto out_free_found_lte;
1446 u16 part_number = le16_to_cpu(pwm_hdr.part_number);
1447 u16 total_parts = le16_to_cpu(pwm_hdr.total_parts);
1449 if (part_number != ctx->progress.extract.part_number ||
1450 total_parts != ctx->progress.extract.total_parts ||
1451 memcmp(pwm_hdr.guid, ctx->progress.extract.guid,
1454 ctx->progress.extract.part_number = part_number;
1455 ctx->progress.extract.total_parts = total_parts;
1456 memcpy(ctx->progress.extract.guid,
1457 pwm_hdr.guid, WIM_GID_LEN);
1458 if (ctx->progress_func) {
1460 WIMLIB_PROGRESS_MSG_EXTRACT_SPWM_PART_BEGIN,
1469 free_lookup_table_entry(found_lte);
1478 /* Finish extracting a file, directory, or symbolic link by setting file
1479 * security and timestamps. */
1481 dentry_extract_final(struct wim_dentry *dentry, void *_ctx)
1483 struct apply_ctx *ctx = _ctx;
1485 tchar path[ctx->ops->path_max];
1487 if (!build_extraction_path(path, dentry, ctx))
1490 ret = extract_security(path, ctx, dentry);
1494 if (ctx->ops->requires_final_set_attributes_pass) {
1495 /* Set file attributes (if supported). */
1496 ret = extract_file_attributes(path, ctx, dentry, 1);
1501 return extract_timestamps(path, ctx, dentry);
1505 * Extract a WIM dentry to standard output.
1507 * This obviously doesn't make sense in all cases. We return an error if the
1508 * dentry does not correspond to a regular file. Otherwise we extract the
1509 * unnamed data stream only.
1512 extract_dentry_to_stdout(struct wim_dentry *dentry)
1515 if (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
1516 FILE_ATTRIBUTE_DIRECTORY))
1518 ERROR("\"%"TS"\" is not a regular file and therefore cannot be "
1519 "extracted to standard output", dentry_full_path(dentry));
1520 ret = WIMLIB_ERR_NOT_A_REGULAR_FILE;
1522 struct wim_lookup_table_entry *lte;
1524 lte = inode_unnamed_lte_resolved(dentry->d_inode);
1526 struct filedes _stdout;
1527 filedes_init(&_stdout, STDOUT_FILENO);
1528 ret = extract_wim_resource_to_fd(lte, &_stdout,
1529 wim_resource_size(lte));
1536 static const utf16lechar replacement_char = cpu_to_le16(0xfffd);
1538 static const utf16lechar replacement_char = cpu_to_le16('?');
1542 file_name_valid(utf16lechar *name, size_t num_chars, bool fix)
1548 for (i = 0; i < num_chars; i++) {
1551 case cpu_to_le16('\\'):
1552 case cpu_to_le16(':'):
1553 case cpu_to_le16('*'):
1554 case cpu_to_le16('?'):
1555 case cpu_to_le16('"'):
1556 case cpu_to_le16('<'):
1557 case cpu_to_le16('>'):
1558 case cpu_to_le16('|'):
1560 case cpu_to_le16('/'):
1561 case cpu_to_le16('\0'):
1563 name[i] = replacement_char;
1570 if (name[num_chars - 1] == cpu_to_le16(' ') ||
1571 name[num_chars - 1] == cpu_to_le16('.'))
1574 name[num_chars - 1] = replacement_char;
1583 dentry_is_dot_or_dotdot(const struct wim_dentry *dentry)
1585 const utf16lechar *file_name = dentry->file_name;
1586 return file_name != NULL &&
1587 file_name[0] == cpu_to_le16('.') &&
1588 (file_name[1] == cpu_to_le16('\0') ||
1589 (file_name[1] == cpu_to_le16('.') &&
1590 file_name[2] == cpu_to_le16('\0')));
1594 dentry_mark_skipped(struct wim_dentry *dentry, void *_ignore)
1596 dentry->extraction_skipped = 1;
1601 * dentry_calculate_extraction_path-
1603 * Calculate the actual filename component at which a WIM dentry will be
1604 * extracted, handling invalid filenames "properly".
1606 * dentry->extraction_name usually will be set the same as dentry->file_name (on
1607 * UNIX, converted into the platform's multibyte encoding). However, if the
1608 * file name contains characters that are not valid on the current platform or
1609 * has some other format that is not valid, leave dentry->extraction_name as
1610 * NULL and set dentry->extraction_skipped to indicate that this dentry should
1611 * not be extracted, unless the appropriate flag
1612 * WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES is set in the extract flags, in
1613 * which case a substitute filename will be created and set instead.
1615 * Conflicts with case-insensitive names on Windows are handled similarly; see
1619 dentry_calculate_extraction_path(struct wim_dentry *dentry, void *_args)
1621 struct apply_ctx *ctx = _args;
1624 if (dentry == ctx->extract_root || dentry->extraction_skipped)
1627 if (!dentry_is_supported(dentry, &ctx->supported_features))
1630 if (dentry_is_dot_or_dotdot(dentry)) {
1631 /* WIM files shouldn't contain . or .. entries. But if they are
1632 * there, don't attempt to extract them. */
1633 WARNING("Skipping extraction of unexpected . or .. file "
1634 "\"%"TS"\"", dentry_full_path(dentry));
1639 if (!ctx->ops->supports_case_sensitive_filenames)
1641 struct wim_dentry *other;
1642 list_for_each_entry(other, &dentry->case_insensitive_conflict_list,
1643 case_insensitive_conflict_list)
1645 if (ctx->extract_flags &
1646 WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS) {
1647 WARNING("\"%"TS"\" has the same "
1648 "case-insensitive name as "
1649 "\"%"TS"\"; extracting "
1650 "dummy name instead",
1651 dentry_full_path(dentry),
1652 dentry_full_path(other));
1655 WARNING("Not extracting \"%"TS"\": "
1656 "has same case-insensitive "
1657 "name as \"%"TS"\"",
1658 dentry_full_path(dentry),
1659 dentry_full_path(other));
1664 #else /* __WIN32__ */
1665 wimlib_assert(ctx->ops->supports_case_sensitive_filenames);
1666 #endif /* !__WIN32__ */
1668 if (file_name_valid(dentry->file_name, dentry->file_name_nbytes / 2, false)) {
1670 dentry->extraction_name = dentry->file_name;
1671 dentry->extraction_name_nchars = dentry->file_name_nbytes / 2;
1674 return utf16le_to_tstr(dentry->file_name,
1675 dentry->file_name_nbytes,
1676 &dentry->extraction_name,
1677 &dentry->extraction_name_nchars);
1680 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES)
1682 WARNING("\"%"TS"\" has an invalid filename "
1683 "that is not supported on this platform; "
1684 "extracting dummy name instead",
1685 dentry_full_path(dentry));
1688 WARNING("Not extracting \"%"TS"\": has an invalid filename "
1689 "that is not supported on this platform",
1690 dentry_full_path(dentry));
1697 utf16lechar utf16_name_copy[dentry->file_name_nbytes / 2];
1699 memcpy(utf16_name_copy, dentry->file_name, dentry->file_name_nbytes);
1700 file_name_valid(utf16_name_copy, dentry->file_name_nbytes / 2, true);
1703 size_t tchar_nchars;
1705 tchar_name = utf16_name_copy;
1706 tchar_nchars = dentry->file_name_nbytes / 2;
1708 ret = utf16le_to_tstr(utf16_name_copy,
1709 dentry->file_name_nbytes,
1710 &tchar_name, &tchar_nchars);
1714 size_t fixed_name_num_chars = tchar_nchars;
1715 tchar fixed_name[tchar_nchars + 50];
1717 tmemcpy(fixed_name, tchar_name, tchar_nchars);
1718 fixed_name_num_chars += tsprintf(fixed_name + tchar_nchars,
1719 T(" (invalid filename #%lu)"),
1720 ++ctx->invalid_sequence);
1724 dentry->extraction_name = memdup(fixed_name,
1725 2 * fixed_name_num_chars + 2);
1726 if (!dentry->extraction_name)
1727 return WIMLIB_ERR_NOMEM;
1728 dentry->extraction_name_nchars = fixed_name_num_chars;
1733 for_dentry_in_tree(dentry, dentry_mark_skipped, NULL);
1737 /* Clean up dentry and inode structure after extraction. */
1739 dentry_reset_needs_extraction(struct wim_dentry *dentry, void *_ignore)
1741 struct wim_inode *inode = dentry->d_inode;
1743 dentry->extraction_skipped = 0;
1744 dentry->was_hardlinked = 0;
1745 dentry->skeleton_extracted = 0;
1746 inode->i_visited = 0;
1747 FREE(inode->i_extracted_file);
1748 inode->i_extracted_file = NULL;
1749 inode->i_dos_name_extracted = 0;
1750 if ((void*)dentry->extraction_name != (void*)dentry->file_name)
1751 FREE(dentry->extraction_name);
1752 dentry->extraction_name = NULL;
1756 /* Tally features necessary to extract a dentry and the corresponding inode. */
1758 dentry_tally_features(struct wim_dentry *dentry, void *_features)
1760 struct wim_features *features = _features;
1761 struct wim_inode *inode = dentry->d_inode;
1763 if (inode->i_attributes & FILE_ATTRIBUTE_ARCHIVE)
1764 features->archive_files++;
1765 if (inode->i_attributes & FILE_ATTRIBUTE_HIDDEN)
1766 features->hidden_files++;
1767 if (inode->i_attributes & FILE_ATTRIBUTE_SYSTEM)
1768 features->system_files++;
1769 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED)
1770 features->compressed_files++;
1771 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1772 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1773 features->encrypted_directories++;
1775 features->encrypted_files++;
1777 if (inode->i_attributes & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED)
1778 features->not_context_indexed_files++;
1779 if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE)
1780 features->sparse_files++;
1781 if (inode_has_named_stream(inode))
1782 features->named_data_streams++;
1783 if (inode->i_visited)
1784 features->hard_links++;
1785 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1786 features->reparse_points++;
1787 if (inode_is_symlink(inode))
1788 features->symlink_reparse_points++;
1790 features->other_reparse_points++;
1792 if (inode->i_security_id != -1)
1793 features->security_descriptors++;
1794 if (dentry->short_name_nbytes)
1795 features->short_names++;
1796 if (inode_has_unix_data(inode))
1797 features->unix_data++;
1798 inode->i_visited = 1;
1803 dentry_clear_inode_visited(struct wim_dentry *dentry, void *_ignore)
1805 dentry->d_inode->i_visited = 0;
1809 /* Tally the features necessary to extract a dentry tree. */
1811 dentry_tree_get_features(struct wim_dentry *root, struct wim_features *features)
1813 memset(features, 0, sizeof(struct wim_features));
1814 for_dentry_in_tree(root, dentry_tally_features, features);
1815 for_dentry_in_tree(root, dentry_clear_inode_visited, NULL);
1819 compute_supported_attributes_mask(const struct wim_features *supported_features)
1823 if (!supported_features->archive_files)
1824 mask &= ~FILE_ATTRIBUTE_ARCHIVE;
1826 if (!supported_features->hidden_files)
1827 mask &= ~FILE_ATTRIBUTE_HIDDEN;
1829 if (!supported_features->system_files)
1830 mask &= ~FILE_ATTRIBUTE_SYSTEM;
1832 if (!supported_features->not_context_indexed_files)
1833 mask &= ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
1835 if (!supported_features->compressed_files)
1836 mask &= ~FILE_ATTRIBUTE_COMPRESSED;
1838 if (!supported_features->sparse_files)
1839 mask &= ~FILE_ATTRIBUTE_SPARSE_FILE;
1841 if (!supported_features->reparse_points)
1842 mask &= ~FILE_ATTRIBUTE_REPARSE_POINT;
1848 do_feature_check(const struct wim_features *required_features,
1849 const struct wim_features *supported_features,
1851 const struct apply_operations *ops,
1852 const tchar *wim_source_path)
1855 const tchar *mode = T("this extraction mode");
1857 if (wim_source_path[0] == '\0')
1858 loc = T("the WIM image");
1860 loc = wim_source_path;
1862 /* We're an archive program, so theoretically we can do what we want
1863 * with FILE_ATTRIBUTE_ARCHIVE (which is a dumb flag anyway). Don't
1864 * bother the user about it. */
1866 if (required_features->archive_files && !supported_features->archive_files)
1869 "%lu files in %"TS" are marked as archived, but this attribute\n"
1870 " is not supported in %"TS".",
1871 required_features->archive_files, loc, mode);
1875 if (required_features->hidden_files && !supported_features->hidden_files)
1878 "%lu files in %"TS" are marked as hidden, but this\n"
1879 " attribute is not supported in %"TS".",
1880 required_features->hidden_files, loc, mode);
1883 if (required_features->system_files && !supported_features->system_files)
1886 "%lu files in %"TS" are marked as system files,\n"
1887 " but this attribute is not supported in %"TS".",
1888 required_features->system_files, loc, mode);
1891 if (required_features->compressed_files && !supported_features->compressed_files)
1894 "%lu files in %"TS" are marked as being transparently\n"
1895 " compressed, but transparent compression is not supported in\n"
1896 " %"TS". These files will be extracted as uncompressed.",
1897 required_features->compressed_files, loc, mode);
1900 if (required_features->encrypted_files && !supported_features->encrypted_files)
1903 "%lu files in %"TS" are marked as being encrypted,\n"
1904 " but encryption is not supported in %"TS". These files\n"
1905 " will not be extracted.",
1906 required_features->encrypted_files, loc, mode);
1909 if (required_features->encrypted_directories &&
1910 !supported_features->encrypted_directories)
1913 "%lu directories in %"TS" are marked as being encrypted,\n"
1914 " but encryption is not supported in %"TS".\n"
1915 " These directories will be extracted as unencrypted.",
1916 required_features->encrypted_directories, loc, mode);
1919 if (required_features->not_context_indexed_files &&
1920 !supported_features->not_context_indexed_files)
1923 "%lu files in %"TS" are marked as not content indexed,\n"
1924 " but this attribute is not supported in %"TS".",
1925 required_features->not_context_indexed_files, loc, mode);
1928 if (required_features->sparse_files && !supported_features->sparse_files)
1931 "%lu files in %"TS" are marked as sparse, but creating\n"
1932 " sparse files is not supported in %"TS". These files\n"
1933 " will be extracted as non-sparse.",
1934 required_features->sparse_files, loc, mode);
1937 if (required_features->named_data_streams &&
1938 !supported_features->named_data_streams)
1941 "%lu files in %"TS" contain one or more alternate (named)\n"
1942 " data streams, which are not supported in %"TS".\n"
1943 " Alternate data streams will NOT be extracted.",
1944 required_features->named_data_streams, loc, mode);
1947 if (unlikely(extract_flags & (WIMLIB_EXTRACT_FLAG_HARDLINK |
1948 WIMLIB_EXTRACT_FLAG_SYMLINK)) &&
1949 required_features->named_data_streams &&
1950 supported_features->named_data_streams)
1953 "%lu files in %"TS" contain one or more alternate (named)\n"
1954 " data streams, which are not supported in linked extraction mode.\n"
1955 " Alternate data streams will NOT be extracted.",
1956 required_features->named_data_streams, loc);
1959 if (required_features->hard_links && !supported_features->hard_links)
1962 "%lu files in %"TS" are hard links, but hard links are\n"
1963 " not supported in %"TS". Hard links will be extracted as\n"
1964 " duplicate copies of the linked files.",
1965 required_features->hard_links, loc, mode);
1968 if (required_features->reparse_points && !supported_features->reparse_points)
1970 if (supported_features->symlink_reparse_points) {
1971 if (required_features->other_reparse_points) {
1973 "%lu files in %"TS" are reparse points that are neither\n"
1974 " symbolic links nor junction points and are not supported in\n"
1975 " %"TS". These reparse points will not be extracted.",
1976 required_features->other_reparse_points, loc,
1981 "%lu files in %"TS" are reparse points, which are\n"
1982 " not supported in %"TS" and will not be extracted.",
1983 required_features->reparse_points, loc, mode);
1987 if (required_features->security_descriptors &&
1988 !supported_features->security_descriptors)
1991 "%lu files in %"TS" have Windows NT security descriptors,\n"
1992 " but extracting security descriptors is not supported in\n"
1993 " %"TS". No security descriptors will be extracted.",
1994 required_features->security_descriptors, loc, mode);
1997 if (required_features->short_names && !supported_features->short_names)
2000 "%lu files in %"TS" have short (DOS) names, but\n"
2001 " extracting short names is not supported in %"TS".\n"
2002 " Short names will not be extracted.\n",
2003 required_features->short_names, loc, mode);
2006 if ((extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) &&
2007 required_features->unix_data && !supported_features->unix_data)
2009 ERROR("Extracting UNIX data is not supported in %"TS, mode);
2010 return WIMLIB_ERR_UNSUPPORTED;
2012 if ((extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES) &&
2013 required_features->short_names && !supported_features->short_names)
2015 ERROR("Extracting short names is not supported in %"TS"", mode);
2016 return WIMLIB_ERR_UNSUPPORTED;
2018 if ((extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_TIMESTAMPS) &&
2019 !ops->set_timestamps)
2021 ERROR("Extracting timestamps is not supported in %"TS"", mode);
2022 return WIMLIB_ERR_UNSUPPORTED;
2024 if (((extract_flags & (WIMLIB_EXTRACT_FLAG_STRICT_ACLS |
2025 WIMLIB_EXTRACT_FLAG_UNIX_DATA))
2026 == WIMLIB_EXTRACT_FLAG_STRICT_ACLS) &&
2027 required_features->security_descriptors &&
2028 !supported_features->security_descriptors)
2030 ERROR("Extracting security descriptors is not supported in %"TS, mode);
2031 return WIMLIB_ERR_UNSUPPORTED;
2034 if ((extract_flags & WIMLIB_EXTRACT_FLAG_HARDLINK) &&
2035 !supported_features->hard_links)
2037 ERROR("Hard link extraction mode requested, but "
2038 "%"TS" does not support hard links!", mode);
2039 return WIMLIB_ERR_UNSUPPORTED;
2042 if ((extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS) &&
2043 required_features->symlink_reparse_points &&
2044 !(supported_features->symlink_reparse_points ||
2045 supported_features->reparse_points))
2047 ERROR("Extracting symbolic links is not supported in %"TS, mode);
2048 return WIMLIB_ERR_UNSUPPORTED;
2051 if ((extract_flags & WIMLIB_EXTRACT_FLAG_SYMLINK) &&
2052 !supported_features->symlink_reparse_points)
2054 ERROR("Symbolic link extraction mode requested, but "
2055 "%"TS" does not support symbolic "
2057 return WIMLIB_ERR_UNSUPPORTED;
2063 do_extract_warnings(struct apply_ctx *ctx)
2065 if (ctx->partial_security_descriptors == 0 &&
2066 ctx->no_security_descriptors == 0)
2069 WARNING("Extraction of \"%"TS"\" complete, but with one or more warnings:",
2071 if (ctx->partial_security_descriptors != 0) {
2072 WARNING("- Could only partially set the security descriptor\n"
2073 " on %lu files or directories.",
2074 ctx->partial_security_descriptors);
2076 if (ctx->no_security_descriptors != 0) {
2077 WARNING("- Could not set security descriptor at all\n"
2078 " on %lu files or directories.",
2079 ctx->no_security_descriptors);
2082 WARNING("To fully restore all security descriptors, run the program\n"
2083 " with Administrator rights.");
2088 * extract_tree - Extract a file or directory tree from the currently selected
2091 * @wim: WIMStruct for the WIM file, with the desired image selected
2092 * (as wim->current_image).
2095 * "Canonical" (i.e. no leading or trailing slashes, path
2096 * separators WIM_PATH_SEPARATOR) path inside the WIM image to
2097 * extract. An empty string means the full image.
2100 * Filesystem path to extract the file or directory tree to.
2101 * (Or, with WIMLIB_EXTRACT_FLAG_NTFS: the name of a NTFS volume.)
2104 * WIMLIB_EXTRACT_FLAG_*. Also, the private flag
2105 * WIMLIB_EXTRACT_FLAG_MULTI_IMAGE will be set if this is being
2106 * called through wimlib_extract_image() with WIMLIB_ALL_IMAGES as
2110 * If non-NULL, progress function for the extraction. The messages
2111 * that may be sent in this function are:
2113 * WIMLIB_PROGRESS_MSG_EXTRACT_TREE_BEGIN or
2114 * WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN;
2115 * WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN;
2116 * WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_END;
2117 * WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY;
2118 * WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS;
2119 * WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS;
2120 * WIMLIB_PROGRESS_MSG_EXTRACT_TREE_END or
2121 * WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END.
2123 * Returns 0 on success; a positive WIMLIB_ERR_* code on failure.
2126 extract_tree(WIMStruct *wim, const tchar *wim_source_path, const tchar *target,
2127 int extract_flags, wimlib_progress_func_t progress_func)
2129 struct wim_dentry *root;
2130 struct wim_features required_features;
2131 struct apply_ctx ctx;
2133 struct wim_lookup_table_entry *lte;
2135 /* Start initializing the apply_ctx. */
2136 memset(&ctx, 0, sizeof(struct apply_ctx));
2138 ctx.extract_flags = extract_flags;
2139 ctx.target = target;
2140 ctx.target_nchars = tstrlen(target);
2141 ctx.progress_func = progress_func;
2142 if (progress_func) {
2143 ctx.progress.extract.wimfile_name = wim->filename;
2144 ctx.progress.extract.image = wim->current_image;
2145 ctx.progress.extract.extract_flags = (extract_flags &
2146 WIMLIB_EXTRACT_MASK_PUBLIC);
2147 ctx.progress.extract.image_name = wimlib_get_image_name(wim,
2148 wim->current_image);
2149 ctx.progress.extract.extract_root_wim_source_path = wim_source_path;
2150 ctx.progress.extract.target = target;
2152 INIT_LIST_HEAD(&ctx.stream_list);
2154 /* Translate the path to extract into the corresponding
2155 * `struct wim_dentry', which will be the root of the
2156 * "dentry tree" to extract. */
2157 root = get_dentry(wim, wim_source_path);
2159 ERROR("Path \"%"TS"\" does not exist in WIM image %d",
2160 wim_source_path, wim->current_image);
2161 ret = WIMLIB_ERR_PATH_DOES_NOT_EXIST;
2165 ctx.extract_root = root;
2167 /* Select the appropriate apply_operations based on the
2168 * platform and extract_flags. */
2170 ctx.ops = &win32_apply_ops;
2172 ctx.ops = &unix_apply_ops;
2176 if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS)
2177 ctx.ops = &ntfs_3g_apply_ops;
2180 /* Call the start_extract() callback. This gives the apply_operations
2181 * implementation a chance to do any setup needed to access the volume.
2182 * Furthermore, it's expected to set the supported features of this
2183 * extraction mode (ctx.supported_features), which are determined at
2184 * runtime as they may vary depending on the actual volume. These
2185 * features are then compared with the actual features extracting this
2186 * dentry tree requires. Some mismatches will merely produce warnings
2187 * and the unsupported data will be ignored; others will produce errors.
2189 ret = ctx.ops->start_extract(target, &ctx);
2193 dentry_tree_get_features(root, &required_features);
2194 ret = do_feature_check(&required_features, &ctx.supported_features,
2195 extract_flags, ctx.ops, wim_source_path);
2197 goto out_finish_or_abort_extract;
2199 ctx.supported_attributes_mask =
2200 compute_supported_attributes_mask(&ctx.supported_features);
2202 /* Figure out whether the root dentry is being extracted to the root of
2203 * a volume and therefore needs to be treated "specially", for example
2204 * not being explicitly created and not having attributes set. */
2205 if (ctx.ops->target_is_root && ctx.ops->root_directory_is_special)
2206 ctx.root_dentry_is_special = ctx.ops->target_is_root(target);
2208 /* Calculate the actual filename component of each extracted dentry. In
2209 * the process, set the dentry->extraction_skipped flag on dentries that
2210 * are being skipped for some reason (e.g. invalid filename). */
2211 ret = for_dentry_in_tree(root, dentry_calculate_extraction_path, &ctx);
2213 goto out_dentry_reset_needs_extraction;
2215 /* Build the list of the streams that need to be extracted and
2216 * initialize ctx.progress.extract with stream information. */
2217 ret = for_dentry_in_tree(ctx.extract_root,
2218 dentry_resolve_and_zero_lte_refcnt, &ctx);
2220 goto out_dentry_reset_needs_extraction;
2222 ret = for_dentry_in_tree(ctx.extract_root,
2223 dentry_add_streams_to_extract, &ctx);
2225 goto out_teardown_stream_list;
2227 if (extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE) {
2228 /* When extracting from a pipe, the number of bytes of data to
2229 * extract can't be determined in the normal way (examining the
2230 * lookup table), since at this point all we have is a set of
2231 * SHA1 message digests of streams that need to be extracted.
2232 * However, we can get a reasonably accurate estimate by taking
2233 * <TOTALBYTES> from the corresponding <IMAGE> in the WIM XML
2234 * data. This does assume that a full image is being extracted,
2235 * but currently there is no API for doing otherwise. (Also,
2236 * subtract <HARDLINKBYTES> from this if hard links are
2237 * supported by the extraction mode.) */
2238 ctx.progress.extract.total_bytes =
2239 wim_info_get_image_total_bytes(wim->wim_info,
2240 wim->current_image);
2241 if (ctx.supported_features.hard_links) {
2242 ctx.progress.extract.total_bytes -=
2243 wim_info_get_image_hard_link_bytes(wim->wim_info,
2244 wim->current_image);
2248 /* Handle the special case of extracting a file to standard
2249 * output. In that case, "root" should be a single file, not a
2250 * directory tree. (If not, extract_dentry_to_stdout() will
2251 * return an error.) */
2252 if (extract_flags & WIMLIB_EXTRACT_FLAG_TO_STDOUT) {
2253 ret = extract_dentry_to_stdout(root);
2254 goto out_teardown_stream_list;
2257 /* If a sequential extraction was specified, sort the streams to be
2258 * extracted by their position in the WIM file so that the WIM file can
2259 * be read sequentially. */
2260 if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SEQUENTIAL |
2261 WIMLIB_EXTRACT_FLAG_FROM_PIPE))
2262 == WIMLIB_EXTRACT_FLAG_SEQUENTIAL)
2264 ret = sort_stream_list_by_sequential_order(
2266 offsetof(struct wim_lookup_table_entry,
2269 goto out_teardown_stream_list;
2272 if (ctx.ops->realpath_works_on_nonexisting_files &&
2273 ((extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX) ||
2274 ctx.ops->requires_realtarget_in_paths))
2276 ctx.realtarget = realpath(target, NULL);
2277 if (!ctx.realtarget) {
2278 ret = WIMLIB_ERR_NOMEM;
2279 goto out_teardown_stream_list;
2281 ctx.realtarget_nchars = tstrlen(ctx.realtarget);
2284 if (progress_func) {
2285 progress_func(*wim_source_path ? WIMLIB_PROGRESS_MSG_EXTRACT_TREE_BEGIN :
2286 WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN,
2290 if (!ctx.root_dentry_is_special)
2292 tchar path[ctx.ops->path_max];
2293 if (build_extraction_path(path, root, &ctx))
2295 ret = extract_inode(path, &ctx, root->d_inode);
2297 goto out_free_realtarget;
2301 /* If we need to fix up the targets of absolute symbolic links
2302 * (WIMLIB_EXTRACT_FLAG_RPFIX) or the extraction mode requires paths to
2303 * be absolute, use realpath() (or its replacement on Windows) to get
2304 * the absolute path to the extraction target. Note that this requires
2305 * the target directory to exist, unless
2306 * realpath_works_on_nonexisting_files is set in the apply_operations.
2308 if (!ctx.realtarget &&
2309 (((extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX) &&
2310 required_features.symlink_reparse_points) ||
2311 ctx.ops->requires_realtarget_in_paths))
2313 ctx.realtarget = realpath(target, NULL);
2314 if (!ctx.realtarget) {
2315 ret = WIMLIB_ERR_NOMEM;
2316 goto out_free_realtarget;
2318 ctx.realtarget_nchars = tstrlen(ctx.realtarget);
2321 /* Finally, the important part: extract the tree of files. */
2322 if (extract_flags & (WIMLIB_EXTRACT_FLAG_SEQUENTIAL |
2323 WIMLIB_EXTRACT_FLAG_FROM_PIPE)) {
2324 /* Sequential extraction requested, so two passes are needed
2325 * (one for directory structure, one for streams.) */
2327 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN,
2330 if (!(extract_flags & WIMLIB_EXTRACT_FLAG_RESUME)) {
2331 ret = for_dentry_in_tree(root, dentry_extract_skeleton, &ctx);
2333 goto out_free_realtarget;
2336 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_END,
2338 if (extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE)
2339 ret = extract_streams_from_pipe(&ctx);
2341 ret = extract_stream_list(&ctx);
2343 goto out_free_realtarget;
2345 /* Sequential extraction was not requested, so we can make do
2346 * with one pass where we both create the files and extract
2349 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN,
2351 ret = for_dentry_in_tree(root, dentry_extract, &ctx);
2353 goto out_free_realtarget;
2355 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_END,
2359 /* If the total number of bytes to extract was miscalculated, just jump
2360 * to the calculated number in order to avoid confusing the progress
2361 * function. This should only occur when extracting from a pipe. */
2362 if (ctx.progress.extract.completed_bytes != ctx.progress.extract.total_bytes)
2364 DEBUG("Calculated %"PRIu64" bytes to extract, but actually "
2365 "extracted %"PRIu64,
2366 ctx.progress.extract.total_bytes,
2367 ctx.progress.extract.completed_bytes);
2369 if (progress_func &&
2370 ctx.progress.extract.completed_bytes < ctx.progress.extract.total_bytes)
2372 ctx.progress.extract.completed_bytes = ctx.progress.extract.total_bytes;
2373 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS, &ctx.progress);
2376 /* Apply security descriptors and timestamps. This is done at the end,
2377 * and in a depth-first manner, to prevent timestamps from getting
2378 * changed by subsequent extract operations and to minimize the chance
2379 * of the restored security descriptors getting in our way. */
2381 progress_func(WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS,
2383 ret = for_dentry_in_tree_depth(root, dentry_extract_final, &ctx);
2385 goto out_free_realtarget;
2387 if (progress_func) {
2388 progress_func(*wim_source_path ? WIMLIB_PROGRESS_MSG_EXTRACT_TREE_END :
2389 WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END,
2393 do_extract_warnings(&ctx);
2396 out_free_realtarget:
2397 FREE(ctx.realtarget);
2398 out_teardown_stream_list:
2399 /* Free memory allocated as part of the mapping from each
2400 * wim_lookup_table_entry to the dentries that reference it. */
2401 if (ctx.extract_flags & WIMLIB_EXTRACT_FLAG_SEQUENTIAL)
2402 list_for_each_entry(lte, &ctx.stream_list, extraction_list)
2403 if (lte->out_refcnt > ARRAY_LEN(lte->inline_lte_dentries))
2404 FREE(lte->lte_dentries);
2405 out_dentry_reset_needs_extraction:
2406 for_dentry_in_tree(root, dentry_reset_needs_extraction, NULL);
2407 out_finish_or_abort_extract:
2409 if (ctx.ops->abort_extract)
2410 ctx.ops->abort_extract(&ctx);
2412 if (ctx.ops->finish_extract)
2413 ret = ctx.ops->finish_extract(&ctx);
2419 /* Validates a single wimlib_extract_command, mostly checking to make sure the
2420 * extract flags make sense. */
2422 check_extract_command(struct wimlib_extract_command *cmd, int wim_header_flags)
2426 /* Empty destination path? */
2427 if (cmd->fs_dest_path[0] == T('\0'))
2428 return WIMLIB_ERR_INVALID_PARAM;
2430 extract_flags = cmd->extract_flags;
2432 /* Check for invalid flag combinations */
2433 if ((extract_flags &
2434 (WIMLIB_EXTRACT_FLAG_SYMLINK |
2435 WIMLIB_EXTRACT_FLAG_HARDLINK)) == (WIMLIB_EXTRACT_FLAG_SYMLINK |
2436 WIMLIB_EXTRACT_FLAG_HARDLINK))
2437 return WIMLIB_ERR_INVALID_PARAM;
2439 if ((extract_flags &
2440 (WIMLIB_EXTRACT_FLAG_NO_ACLS |
2441 WIMLIB_EXTRACT_FLAG_STRICT_ACLS)) == (WIMLIB_EXTRACT_FLAG_NO_ACLS |
2442 WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2443 return WIMLIB_ERR_INVALID_PARAM;
2445 if ((extract_flags &
2446 (WIMLIB_EXTRACT_FLAG_RPFIX |
2447 WIMLIB_EXTRACT_FLAG_NORPFIX)) == (WIMLIB_EXTRACT_FLAG_RPFIX |
2448 WIMLIB_EXTRACT_FLAG_NORPFIX))
2449 return WIMLIB_ERR_INVALID_PARAM;
2451 if ((extract_flags &
2452 (WIMLIB_EXTRACT_FLAG_RESUME |
2453 WIMLIB_EXTRACT_FLAG_FROM_PIPE)) == WIMLIB_EXTRACT_FLAG_RESUME)
2454 return WIMLIB_ERR_INVALID_PARAM;
2456 if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
2457 #ifndef WITH_NTFS_3G
2458 ERROR("wimlib was compiled without support for NTFS-3g, so\n"
2459 " we cannot apply a WIM image directly to a NTFS volume.");
2460 return WIMLIB_ERR_UNSUPPORTED;
2464 if ((extract_flags & (WIMLIB_EXTRACT_FLAG_RPFIX |
2465 WIMLIB_EXTRACT_FLAG_NORPFIX)) == 0)
2467 /* Do reparse point fixups by default if the WIM header says
2468 * they are enabled and we are extracting a full image. */
2469 if (wim_header_flags & WIM_HDR_FLAG_RP_FIX)
2470 extract_flags |= WIMLIB_EXTRACT_FLAG_RPFIX;
2473 /* TODO: Since UNIX data entries are stored in the file resources, in a
2474 * completely sequential extraction they may come up before the
2475 * corresponding file or symbolic link data. This needs to be handled
2477 if ((extract_flags & (WIMLIB_EXTRACT_FLAG_UNIX_DATA |
2478 WIMLIB_EXTRACT_FLAG_SEQUENTIAL))
2479 == (WIMLIB_EXTRACT_FLAG_UNIX_DATA |
2480 WIMLIB_EXTRACT_FLAG_SEQUENTIAL))
2482 if (extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE) {
2483 WARNING("Setting UNIX file/owner group may "
2484 "be impossible on some\n"
2486 "when applying from a pipe.");
2488 extract_flags &= ~WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
2489 WARNING("Disabling sequential extraction for "
2494 cmd->extract_flags = extract_flags;
2499 /* Internal function to execute extraction commands for a WIM image. The paths
2500 * in the extract commands are expected to be already "canonicalized". */
2502 do_wimlib_extract_files(WIMStruct *wim,
2504 struct wimlib_extract_command *cmds,
2506 wimlib_progress_func_t progress_func)
2509 bool found_link_cmd = false;
2510 bool found_nolink_cmd = false;
2512 /* Select the image from which we are extracting files */
2513 ret = select_wim_image(wim, image);
2517 /* Make sure there are no streams in the WIM that have not been
2518 * checksummed yet. */
2519 ret = wim_checksum_unhashed_streams(wim);
2523 /* Check for problems with the extraction commands */
2524 for (size_t i = 0; i < num_cmds; i++) {
2525 ret = check_extract_command(&cmds[i], wim->hdr.flags);
2528 if (cmds[i].extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
2529 WIMLIB_EXTRACT_FLAG_HARDLINK)) {
2530 found_link_cmd = true;
2532 found_nolink_cmd = true;
2534 if (found_link_cmd && found_nolink_cmd) {
2535 ERROR("Symlink or hardlink extraction mode must "
2536 "be set on all extraction commands");
2537 return WIMLIB_ERR_INVALID_PARAM;
2541 /* Execute the extraction commands */
2542 for (size_t i = 0; i < num_cmds; i++) {
2543 ret = extract_tree(wim,
2544 cmds[i].wim_source_path,
2545 cmds[i].fs_dest_path,
2546 cmds[i].extract_flags,
2554 /* API function documented in wimlib.h */
2556 wimlib_extract_files(WIMStruct *wim,
2558 const struct wimlib_extract_command *cmds,
2560 int default_extract_flags,
2561 WIMStruct **additional_swms,
2562 unsigned num_additional_swms,
2563 wimlib_progress_func_t progress_func)
2566 struct wimlib_extract_command *cmds_copy;
2569 default_extract_flags &= WIMLIB_EXTRACT_MASK_PUBLIC;
2571 ret = verify_swm_set(wim, additional_swms, num_additional_swms);
2578 if (num_additional_swms)
2579 merge_lookup_tables(wim, additional_swms, num_additional_swms);
2581 cmds_copy = CALLOC(num_cmds, sizeof(cmds[0]));
2583 ret = WIMLIB_ERR_NOMEM;
2584 goto out_restore_lookup_table;
2587 for (size_t i = 0; i < num_cmds; i++) {
2588 cmds_copy[i].extract_flags = (default_extract_flags |
2589 cmds[i].extract_flags)
2590 & WIMLIB_EXTRACT_MASK_PUBLIC;
2591 all_flags |= cmds_copy[i].extract_flags;
2593 cmds_copy[i].wim_source_path = canonicalize_wim_path(cmds[i].wim_source_path);
2594 if (!cmds_copy[i].wim_source_path) {
2595 ret = WIMLIB_ERR_NOMEM;
2596 goto out_free_cmds_copy;
2599 cmds_copy[i].fs_dest_path = canonicalize_fs_path(cmds[i].fs_dest_path);
2600 if (!cmds_copy[i].fs_dest_path) {
2601 ret = WIMLIB_ERR_NOMEM;
2602 goto out_free_cmds_copy;
2606 ret = do_wimlib_extract_files(wim, image,
2607 cmds_copy, num_cmds,
2610 if (all_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
2611 WIMLIB_EXTRACT_FLAG_HARDLINK))
2613 for_lookup_table_entry(wim->lookup_table,
2614 lte_free_extracted_file, NULL);
2617 for (size_t i = 0; i < num_cmds; i++) {
2618 FREE(cmds_copy[i].wim_source_path);
2619 FREE(cmds_copy[i].fs_dest_path);
2622 out_restore_lookup_table:
2623 if (num_additional_swms)
2624 unmerge_lookup_table(wim);
2630 * Extracts an image from a WIM file.
2632 * @wim: WIMStruct for the WIM file.
2634 * @image: Number of the single image to extract.
2636 * @target: Directory or NTFS volume to extract the image to.
2638 * @extract_flags: Bitwise or of WIMLIB_EXTRACT_FLAG_*.
2640 * @progress_func: If non-NULL, a progress function to be called
2643 * Returns 0 on success; nonzero on failure.
2646 extract_single_image(WIMStruct *wim, int image,
2647 const tchar *target, int extract_flags,
2648 wimlib_progress_func_t progress_func)
2651 tchar *target_copy = canonicalize_fs_path(target);
2653 return WIMLIB_ERR_NOMEM;
2654 struct wimlib_extract_command cmd = {
2655 .wim_source_path = T(""),
2656 .fs_dest_path = target_copy,
2657 .extract_flags = extract_flags,
2659 ret = do_wimlib_extract_files(wim, image, &cmd, 1, progress_func);
2664 static const tchar * const filename_forbidden_chars =
2673 /* This function checks if it is okay to use a WIM image's name as a directory
2676 image_name_ok_as_dir(const tchar *image_name)
2678 return image_name && *image_name &&
2679 !tstrpbrk(image_name, filename_forbidden_chars) &&
2680 tstrcmp(image_name, T(".")) &&
2681 tstrcmp(image_name, T(".."));
2684 /* Extracts all images from the WIM to the directory @target, with the images
2685 * placed in subdirectories named by their image names. */
2687 extract_all_images(WIMStruct *wim,
2688 const tchar *target,
2690 wimlib_progress_func_t progress_func)
2692 size_t image_name_max_len = max(xml_get_max_image_name_len(wim), 20);
2693 size_t output_path_len = tstrlen(target);
2694 tchar buf[output_path_len + 1 + image_name_max_len + 1];
2697 const tchar *image_name;
2700 extract_flags |= WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
2702 if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
2703 ERROR("Cannot extract multiple images in NTFS extraction mode.");
2704 return WIMLIB_ERR_INVALID_PARAM;
2707 if (tstat(target, &stbuf)) {
2708 if (errno == ENOENT) {
2709 if (tmkdir(target, 0755)) {
2710 ERROR_WITH_ERRNO("Failed to create directory \"%"TS"\"", target);
2711 return WIMLIB_ERR_MKDIR;
2714 ERROR_WITH_ERRNO("Failed to stat \"%"TS"\"", target);
2715 return WIMLIB_ERR_STAT;
2717 } else if (!S_ISDIR(stbuf.st_mode)) {
2718 ERROR("\"%"TS"\" is not a directory", target);
2719 return WIMLIB_ERR_NOTDIR;
2722 tmemcpy(buf, target, output_path_len);
2723 buf[output_path_len] = OS_PREFERRED_PATH_SEPARATOR;
2724 for (image = 1; image <= wim->hdr.image_count; image++) {
2725 image_name = wimlib_get_image_name(wim, image);
2726 if (image_name_ok_as_dir(image_name)) {
2727 tstrcpy(buf + output_path_len + 1, image_name);
2729 /* Image name is empty or contains forbidden characters.
2730 * Use image number instead. */
2731 tsprintf(buf + output_path_len + 1, T("%d"), image);
2733 ret = extract_single_image(wim, image, buf, extract_flags,
2742 do_wimlib_extract_image(WIMStruct *wim,
2744 const tchar *target,
2746 WIMStruct **additional_swms,
2747 unsigned num_additional_swms,
2748 wimlib_progress_func_t progress_func)
2752 if (extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE) {
2753 wimlib_assert(wim->hdr.part_number == 1);
2754 wimlib_assert(num_additional_swms == 0);
2756 ret = verify_swm_set(wim, additional_swms, num_additional_swms);
2760 if (num_additional_swms)
2761 merge_lookup_tables(wim, additional_swms, num_additional_swms);
2764 if (image == WIMLIB_ALL_IMAGES) {
2765 ret = extract_all_images(wim, target, extract_flags,
2768 ret = extract_single_image(wim, image, target, extract_flags,
2772 if (extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
2773 WIMLIB_EXTRACT_FLAG_HARDLINK))
2775 for_lookup_table_entry(wim->lookup_table,
2776 lte_free_extracted_file,
2779 if (num_additional_swms)
2780 unmerge_lookup_table(wim);
2784 /* API function documented in wimlib.h */
2786 wimlib_extract_image_from_pipe(int pipe_fd, const tchar *image_num_or_name,
2787 const tchar *target, int extract_flags,
2788 wimlib_progress_func_t progress_func)
2792 struct filedes *in_fd;
2796 extract_flags &= WIMLIB_EXTRACT_MASK_PUBLIC;
2798 if (extract_flags & WIMLIB_EXTRACT_FLAG_TO_STDOUT)
2799 return WIMLIB_ERR_INVALID_PARAM;
2801 extract_flags |= WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
2803 /* Read the WIM header from the pipe and get a WIMStruct to represent
2804 * the pipable WIM. Caveats: Unlike getting a WIMStruct with
2805 * wimlib_open_wim(), getting a WIMStruct in this way will result in
2806 * an empty lookup table, no XML data read, and no filename set. */
2807 ret = open_wim_as_WIMStruct(&pipe_fd,
2808 WIMLIB_OPEN_FLAG_FROM_PIPE |
2809 WIMLIB_OPEN_FLAG_SPLIT_OK,
2810 &pwm, progress_func);
2814 /* Sanity check to make sure this is a pipable WIM. */
2815 if (pwm->hdr.magic != PWM_MAGIC) {
2816 ERROR("The WIM being read from file descriptor %d "
2817 "is not pipable!", pipe_fd);
2818 ret = WIMLIB_ERR_NOT_PIPABLE;
2819 goto out_wimlib_free;
2822 /* Sanity check to make sure the first part of a pipable split WIM is
2823 * sent over the pipe first. */
2824 if (pwm->hdr.part_number != 1) {
2825 ERROR("The first part of the split WIM must be "
2826 "sent over the pipe first.");
2827 ret = WIMLIB_ERR_INVALID_PIPABLE_WIM;
2828 goto out_wimlib_free;
2831 in_fd = &pwm->in_fd;
2832 wimlib_assert(in_fd->offset == WIM_HEADER_DISK_SIZE);
2834 /* As mentioned, the WIMStruct we created from the pipe does not have
2835 * XML data yet. Fix this by reading the extra copy of the XML data
2836 * that directly follows the header in pipable WIMs. (Note: see
2837 * write_pipable_wim() for more details about the format of pipable
2840 struct wim_lookup_table_entry xml_lte;
2841 ret = read_pwm_stream_header(pwm, &xml_lte, 0, NULL);
2843 goto out_wimlib_free;
2845 if (!(xml_lte.resource_entry.flags & WIM_RESHDR_FLAG_METADATA))
2847 ERROR("Expected XML data, but found non-metadata "
2849 ret = WIMLIB_ERR_INVALID_PIPABLE_WIM;
2850 goto out_wimlib_free;
2853 copy_resource_entry(&pwm->hdr.xml_res_entry,
2854 &xml_lte.resource_entry);
2856 ret = read_wim_xml_data(pwm);
2858 goto out_wimlib_free;
2859 if (wim_info_get_num_images(pwm->wim_info) != pwm->hdr.image_count) {
2860 ERROR("Image count in XML data is not the same as in WIM header.");
2861 ret = WIMLIB_ERR_XML;
2862 goto out_wimlib_free;
2866 /* Get image index (this may use the XML data that was just read to
2867 * resolve an image name). */
2868 if (image_num_or_name) {
2869 image = wimlib_resolve_image(pwm, image_num_or_name);
2870 if (image == WIMLIB_NO_IMAGE) {
2871 ERROR("\"%"TS"\" is not a valid image in the pipable WIM!",
2873 ret = WIMLIB_ERR_INVALID_IMAGE;
2874 goto out_wimlib_free;
2875 } else if (image == WIMLIB_ALL_IMAGES) {
2876 ERROR("Applying all images from a pipe is not supported.");
2877 ret = WIMLIB_ERR_INVALID_IMAGE;
2878 goto out_wimlib_free;
2881 if (pwm->hdr.image_count != 1) {
2882 ERROR("No image was specified, but the pipable WIM "
2883 "did not contain exactly 1 image");
2884 ret = WIMLIB_ERR_INVALID_IMAGE;
2885 goto out_wimlib_free;
2890 /* Load the needed metadata resource. */
2891 for (i = 1; i <= pwm->hdr.image_count; i++) {
2892 struct wim_lookup_table_entry *metadata_lte;
2893 struct wim_image_metadata *imd;
2895 metadata_lte = new_lookup_table_entry();
2896 if (!metadata_lte) {
2897 ret = WIMLIB_ERR_NOMEM;
2898 goto out_wimlib_free;
2901 ret = read_pwm_stream_header(pwm, metadata_lte, 0, NULL);
2902 imd = pwm->image_metadata[i - 1];
2903 imd->metadata_lte = metadata_lte;
2905 goto out_wimlib_free;
2907 if (!(metadata_lte->resource_entry.flags &
2908 WIM_RESHDR_FLAG_METADATA))
2910 ERROR("Expected metadata resource, but found "
2911 "non-metadata stream.");
2912 ret = WIMLIB_ERR_INVALID_PIPABLE_WIM;
2913 goto out_wimlib_free;
2917 /* Metadata resource is for the images being extracted.
2918 * Parse it and save the metadata in memory. */
2919 ret = read_metadata_resource(pwm, imd);
2921 goto out_wimlib_free;
2924 /* Metadata resource is not for the image being
2925 * extracted. Skip over it. */
2926 ret = skip_pwm_stream(metadata_lte);
2928 goto out_wimlib_free;
2931 /* Extract the image. */
2932 extract_flags |= WIMLIB_EXTRACT_FLAG_FROM_PIPE;
2933 ret = do_wimlib_extract_image(pwm, image, target,
2934 extract_flags, NULL, 0, progress_func);
2935 /* Clean up and return. */
2941 /* API function documented in wimlib.h */
2943 wimlib_extract_image(WIMStruct *wim,
2945 const tchar *target,
2947 WIMStruct **additional_swms,
2948 unsigned num_additional_swms,
2949 wimlib_progress_func_t progress_func)
2951 extract_flags &= WIMLIB_EXTRACT_MASK_PUBLIC;
2952 return do_wimlib_extract_image(wim, image, target, extract_flags,
2953 additional_swms, num_additional_swms,