]> wimlib.net Git - wimlib/blob - src/extract.c
do_feature_check(): Fixes, simplify warnings
[wimlib] / src / extract.c
1 /*
2  * extract.c
3  *
4  * Support for extracting WIM images, or files or directories contained in a WIM
5  * image.
6  */
7
8 /*
9  * Copyright (C) 2012, 2013 Eric Biggers
10  *
11  * This file is part of wimlib, a library for working with WIM files.
12  *
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)
16  * any later version.
17  *
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
21  * details.
22  *
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/.
25  */
26
27 /*
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
32  * or NTFS volume.
33  *
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.
39  */
40
41 #ifdef HAVE_CONFIG_H
42 #  include "config.h"
43 #endif
44
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/pathlist.h"
53 #include "wimlib/paths.h"
54 #include "wimlib/reparse.h"
55 #include "wimlib/resource.h"
56 #include "wimlib/security.h"
57 #ifdef __WIN32__
58 #  include "wimlib/win32.h" /* for realpath() equivalent */
59 #endif
60 #include "wimlib/xml.h"
61 #include "wimlib/wildcard.h"
62 #include "wimlib/wim.h"
63
64 #include <errno.h>
65 #include <fcntl.h>
66 #include <stdlib.h>
67 #include <sys/stat.h>
68 #include <unistd.h>
69
70 #define WIMLIB_EXTRACT_FLAG_MULTI_IMAGE 0x80000000
71 #define WIMLIB_EXTRACT_FLAG_FROM_PIPE   0x40000000
72 #define WIMLIB_EXTRACT_FLAG_FILEMODE    0x20000000
73 #define WIMLIB_EXTRACT_FLAG_IMAGEMODE   0x10000000
74
75 /* Keep in sync with wimlib.h  */
76 #define WIMLIB_EXTRACT_MASK_PUBLIC                              \
77         (WIMLIB_EXTRACT_FLAG_NTFS                       |       \
78          WIMLIB_EXTRACT_FLAG_HARDLINK                   |       \
79          WIMLIB_EXTRACT_FLAG_SYMLINK                    |       \
80          WIMLIB_EXTRACT_FLAG_VERBOSE                    |       \
81          WIMLIB_EXTRACT_FLAG_SEQUENTIAL                 |       \
82          WIMLIB_EXTRACT_FLAG_UNIX_DATA                  |       \
83          WIMLIB_EXTRACT_FLAG_NO_ACLS                    |       \
84          WIMLIB_EXTRACT_FLAG_STRICT_ACLS                |       \
85          WIMLIB_EXTRACT_FLAG_RPFIX                      |       \
86          WIMLIB_EXTRACT_FLAG_NORPFIX                    |       \
87          WIMLIB_EXTRACT_FLAG_TO_STDOUT                  |       \
88          WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES  |       \
89          WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS         |       \
90          WIMLIB_EXTRACT_FLAG_STRICT_TIMESTAMPS          |       \
91          WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES         |       \
92          WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS            |       \
93          WIMLIB_EXTRACT_FLAG_RESUME                     |       \
94          WIMLIB_EXTRACT_FLAG_FILE_ORDER                 |       \
95          WIMLIB_EXTRACT_FLAG_GLOB_PATHS                 |       \
96          WIMLIB_EXTRACT_FLAG_STRICT_GLOB                |       \
97          WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES              |       \
98          WIMLIB_EXTRACT_FLAG_NO_PRESERVE_DIR_STRUCTURE)
99
100 /* Given a WIM dentry in the tree to be extracted, resolve all streams in the
101  * corresponding inode and set 'out_refcnt' in each to 0.  */
102 static int
103 dentry_resolve_and_zero_lte_refcnt(struct wim_dentry *dentry, void *_ctx)
104 {
105         struct apply_ctx *ctx = _ctx;
106         struct wim_inode *inode = dentry->d_inode;
107         struct wim_lookup_table_entry *lte;
108         int ret;
109         bool force = false;
110
111         if (dentry->extraction_skipped)
112                 return 0;
113
114         /* Special case:  when extracting from a pipe, the WIM lookup table is
115          * initially empty, so "resolving" an inode's streams is initially not
116          * possible.  However, we still need to keep track of which streams,
117          * identified by SHA1 message digests, need to be extracted, so we
118          * "resolve" the inode's streams anyway by allocating new entries.  */
119         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE)
120                 force = true;
121         ret = inode_resolve_streams(inode, ctx->wim->lookup_table, force);
122         if (ret)
123                 return ret;
124         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
125                 lte = inode_stream_lte_resolved(inode, i);
126                 if (lte)
127                         lte->out_refcnt = 0;
128         }
129         return 0;
130 }
131
132 static inline bool
133 is_linked_extraction(const struct apply_ctx *ctx)
134 {
135         return 0 != (ctx->extract_flags & (WIMLIB_EXTRACT_FLAG_HARDLINK |
136                                            WIMLIB_EXTRACT_FLAG_SYMLINK));
137 }
138
139 static inline bool
140 can_extract_named_data_streams(const struct apply_ctx *ctx)
141 {
142         return ctx->supported_features.named_data_streams &&
143                 !is_linked_extraction(ctx);
144 }
145
146 static int
147 ref_stream_to_extract(struct wim_lookup_table_entry *lte,
148                       struct wim_dentry *dentry, struct apply_ctx *ctx)
149 {
150         if (!lte)
151                 return 0;
152
153         /* Tally the size only for each extraction of the stream (not hard
154          * links).  */
155         if (!(dentry->d_inode->i_visited &&
156               ctx->supported_features.hard_links) &&
157             (!is_linked_extraction(ctx) || (lte->out_refcnt == 0 &&
158                                             lte->extracted_file == NULL)))
159         {
160                 ctx->progress.extract.total_bytes += lte->size;
161                 ctx->progress.extract.num_streams++;
162         }
163
164         /* Add stream to the extraction_list only one time, even if it's going
165          * to be extracted to multiple locations.  */
166         if (lte->out_refcnt == 0) {
167                 list_add_tail(&lte->extraction_list, &ctx->stream_list);
168                 ctx->num_streams_remaining++;
169         }
170
171         if (!(ctx->extract_flags & WIMLIB_EXTRACT_FLAG_FILE_ORDER)) {
172                 struct wim_dentry **lte_dentries;
173
174                 /* Append dentry to this stream's array of dentries referencing
175                  * it.  Use inline array to avoid memory allocation until the
176                  * number of dentries becomes too large.  */
177                 if (lte->out_refcnt < ARRAY_LEN(lte->inline_lte_dentries)) {
178                         lte_dentries = lte->inline_lte_dentries;
179                 } else {
180                         struct wim_dentry **prev_lte_dentries;
181                         size_t alloc_lte_dentries;
182
183                         if (lte->out_refcnt == ARRAY_LEN(lte->inline_lte_dentries)) {
184                                 prev_lte_dentries = NULL;
185                                 alloc_lte_dentries = ARRAY_LEN(lte->inline_lte_dentries);
186                         } else {
187                                 prev_lte_dentries = lte->lte_dentries;
188                                 alloc_lte_dentries = lte->alloc_lte_dentries;
189                         }
190
191                         if (lte->out_refcnt == alloc_lte_dentries) {
192                                 alloc_lte_dentries *= 2;
193                                 lte_dentries = REALLOC(prev_lte_dentries,
194                                                        alloc_lte_dentries *
195                                                         sizeof(lte_dentries[0]));
196                                 if (lte_dentries == NULL)
197                                         return WIMLIB_ERR_NOMEM;
198                                 if (prev_lte_dentries == NULL) {
199                                         memcpy(lte_dentries,
200                                                lte->inline_lte_dentries,
201                                                sizeof(lte->inline_lte_dentries));
202                                 }
203                                 lte->lte_dentries = lte_dentries;
204                                 lte->alloc_lte_dentries = alloc_lte_dentries;
205                         }
206                         lte_dentries = lte->lte_dentries;
207                 }
208                 lte_dentries[lte->out_refcnt] = dentry;
209         }
210         lte->out_refcnt++;
211         return 0;
212 }
213
214 /* Given a WIM dentry in the tree to be extracted, iterate through streams that
215  * need to be extracted.  For each one, add it to the list of streams to be
216  * extracted (ctx->stream_list) if not already done so, and also update the
217  * progress information (ctx->progress) with the stream.  Furthermore, if doing
218  * a sequential extraction, build a mapping from each the stream to the dentries
219  * referencing it.
220  *
221  * This uses the i_visited member of the inodes (assumed to be 0 initially).  */
222 static int
223 dentry_add_streams_to_extract(struct wim_dentry *dentry, void *_ctx)
224 {
225         struct apply_ctx *ctx = _ctx;
226         struct wim_inode *inode = dentry->d_inode;
227         int ret;
228
229         /* Don't process dentries marked as skipped.  */
230         if (dentry->extraction_skipped)
231                 return 0;
232
233         /* The unnamed data stream will always be extracted, except in an
234          * unlikely case.  */
235         if (!inode_is_encrypted_directory(inode)) {
236                 ret = ref_stream_to_extract(inode_unnamed_lte_resolved(inode),
237                                             dentry, ctx);
238                 if (ret)
239                         return ret;
240         }
241
242         /* Named data streams will be extracted only if supported in the current
243          * extraction mode and volume, and to avoid complications, if not doing
244          * a linked extraction.  */
245         if (can_extract_named_data_streams(ctx)) {
246                 for (u16 i = 0; i < inode->i_num_ads; i++) {
247                         if (!ads_entry_is_named_stream(&inode->i_ads_entries[i]))
248                                 continue;
249                         ret = ref_stream_to_extract(inode->i_ads_entries[i].lte,
250                                                     dentry, ctx);
251                         if (ret)
252                                 return ret;
253                 }
254         }
255         inode->i_visited = 1;
256         return 0;
257 }
258
259 /* Inform library user of progress of stream extraction following the successful
260  * extraction of a copy of the stream specified by @lte.  */
261 static void
262 update_extract_progress(struct apply_ctx *ctx,
263                         const struct wim_lookup_table_entry *lte)
264 {
265         wimlib_progress_func_t progress_func = ctx->progress_func;
266         union wimlib_progress_info *progress = &ctx->progress;
267
268         progress->extract.completed_bytes += lte->size;
269         if (progress_func &&
270             progress->extract.completed_bytes >= ctx->next_progress)
271         {
272                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS, progress);
273                 if (progress->extract.completed_bytes >=
274                     progress->extract.total_bytes)
275                 {
276                         ctx->next_progress = ~0ULL;
277                 } else {
278                         ctx->next_progress += progress->extract.total_bytes / 128;
279                         if (ctx->next_progress > progress->extract.total_bytes)
280                                 ctx->next_progress = progress->extract.total_bytes;
281                 }
282         }
283 }
284
285 #ifndef __WIN32__
286 /* Extract a symbolic link (not directly as reparse data), handling fixing up
287  * the target of absolute symbolic links and updating the extract progress.
288  *
289  * @inode must specify the WIM inode for a symbolic link or junction reparse
290  * point.
291  *
292  * @lte_override overrides the resource used as the reparse data for the
293  * symbolic link.  */
294 static int
295 extract_symlink(const tchar *path, struct apply_ctx *ctx,
296                 struct wim_inode *inode,
297                 struct wim_lookup_table_entry *lte_override)
298 {
299         ssize_t bufsize = ctx->ops->path_max;
300         tchar target[bufsize];
301         tchar *buf = target;
302         tchar *fixed_target;
303         ssize_t sret;
304         int ret;
305
306         /* If absolute symbolic link fixups requested, reserve space in the link
307          * target buffer for the absolute path of the target directory.  */
308         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
309         {
310                 buf += ctx->realtarget_nchars;
311                 bufsize -= ctx->realtarget_nchars;
312         }
313
314         /* Translate the WIM inode's reparse data into the link target.  */
315         sret = wim_inode_readlink(inode, buf, bufsize - 1, lte_override);
316         if (sret < 0) {
317                 errno = -sret;
318                 return WIMLIB_ERR_READLINK;
319         }
320         buf[sret] = '\0';
321
322         if ((ctx->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX) &&
323             buf[0] == '/')
324         {
325                 /* Fix absolute symbolic link target to point into the
326                  * actual extraction destination.  */
327                 tmemcpy(target, ctx->realtarget, ctx->realtarget_nchars);
328                 fixed_target = target;
329         } else {
330                 /* Keep same link target.  */
331                 fixed_target = buf;
332         }
333
334         /* Call into the apply_operations to create the symbolic link.  */
335         DEBUG("Creating symlink \"%"TS"\" => \"%"TS"\"",
336               path, fixed_target);
337         ret = ctx->ops->create_symlink(fixed_target, path, ctx);
338         if (ret) {
339                 ERROR_WITH_ERRNO("Failed to create symlink "
340                                  "\"%"TS"\" => \"%"TS"\"", path, fixed_target);
341                 return ret;
342         }
343
344         /* Account for reparse data consumed.  */
345         update_extract_progress(ctx,
346                                 (lte_override ? lte_override :
347                                       inode_unnamed_lte_resolved(inode)));
348         return 0;
349 }
350 #endif /* !__WIN32__ */
351
352 /* Create a file, directory, or symbolic link.  */
353 static int
354 extract_inode(const tchar *path, struct apply_ctx *ctx, struct wim_inode *inode)
355 {
356         int ret;
357
358 #ifndef __WIN32__
359         if (ctx->supported_features.symlink_reparse_points &&
360             !ctx->supported_features.reparse_points &&
361             inode_is_symlink(inode))
362         {
363                 ret = extract_symlink(path, ctx, inode, NULL);
364         } else
365 #endif /* !__WIN32__ */
366         if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
367                 ret = ctx->ops->create_directory(path, ctx, &inode->extract_cookie);
368                 if (ret) {
369                         ERROR_WITH_ERRNO("Failed to create the directory "
370                                          "\"%"TS"\"", path);
371                 }
372         } else if ((inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) &&
373                     ctx->ops->extract_encrypted_stream_creates_file &&
374                     ctx->supported_features.encrypted_files) {
375                 ret = ctx->ops->extract_encrypted_stream(
376                                 path, inode_unnamed_lte_resolved(inode), ctx);
377                 if (ret) {
378                         ERROR_WITH_ERRNO("Failed to create and extract "
379                                          "encrypted file \"%"TS"\"", path);
380                 }
381         } else {
382                 ret = ctx->ops->create_file(path, ctx, &inode->extract_cookie);
383                 if (ret) {
384                         ERROR_WITH_ERRNO("Failed to create the file "
385                                          "\"%"TS"\"", path);
386                 }
387         }
388         return ret;
389 }
390
391 static int
392 extract_hardlink(const tchar *oldpath, const tchar *newpath,
393                  struct apply_ctx *ctx)
394 {
395         int ret;
396
397         DEBUG("Creating hardlink \"%"TS"\" => \"%"TS"\"", newpath, oldpath);
398         ret = ctx->ops->create_hardlink(oldpath, newpath, ctx);
399         if (ret) {
400                 ERROR_WITH_ERRNO("Failed to create hardlink "
401                                  "\"%"TS"\" => \"%"TS"\"",
402                                  newpath, oldpath);
403         }
404         return ret;
405 }
406
407 #ifdef __WIN32__
408 static int
409 try_extract_rpfix(u8 *rpbuf,
410                   u16 *rpbuflen_p,
411                   const wchar_t *extract_root_realpath,
412                   unsigned extract_root_realpath_nchars)
413 {
414         struct reparse_data rpdata;
415         wchar_t *target;
416         size_t target_nchars;
417         size_t stripped_nchars;
418         wchar_t *stripped_target;
419         wchar_t stripped_target_nchars;
420         int ret;
421
422         utf16lechar *new_target;
423         utf16lechar *new_print_name;
424         size_t new_target_nchars;
425         size_t new_print_name_nchars;
426         utf16lechar *p;
427
428         ret = parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata);
429         if (ret)
430                 return ret;
431
432         if (extract_root_realpath[0] == L'\0' ||
433             extract_root_realpath[1] != L':' ||
434             extract_root_realpath[2] != L'\\')
435                 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
436
437         ret = parse_substitute_name(rpdata.substitute_name,
438                                     rpdata.substitute_name_nbytes,
439                                     rpdata.rptag);
440         if (ret < 0)
441                 return 0;
442         stripped_nchars = ret;
443         target = rpdata.substitute_name;
444         target_nchars = rpdata.substitute_name_nbytes / sizeof(utf16lechar);
445         stripped_target = target + stripped_nchars;
446         stripped_target_nchars = target_nchars - stripped_nchars;
447
448         new_target = alloca((6 + extract_root_realpath_nchars +
449                              stripped_target_nchars) * sizeof(utf16lechar));
450
451         p = new_target;
452         if (stripped_nchars == 6) {
453                 /* Include \??\ prefix if it was present before */
454                 p = wmempcpy(p, L"\\??\\", 4);
455         }
456
457         /* Print name excludes the \??\ if present. */
458         new_print_name = p;
459         if (stripped_nchars != 0) {
460                 /* Get drive letter from real path to extract root, if a drive
461                  * letter was present before. */
462                 *p++ = extract_root_realpath[0];
463                 *p++ = extract_root_realpath[1];
464         }
465         /* Copy the rest of the extract root */
466         p = wmempcpy(p, extract_root_realpath + 2, extract_root_realpath_nchars - 2);
467
468         /* Append the stripped target */
469         p = wmempcpy(p, stripped_target, stripped_target_nchars);
470         new_target_nchars = p - new_target;
471         new_print_name_nchars = p - new_print_name;
472
473         if (new_target_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE ||
474             new_print_name_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE)
475                 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
476
477         rpdata.substitute_name = new_target;
478         rpdata.substitute_name_nbytes = new_target_nchars * sizeof(utf16lechar);
479         rpdata.print_name = new_print_name;
480         rpdata.print_name_nbytes = new_print_name_nchars * sizeof(utf16lechar);
481         return make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
482 }
483 #endif /* __WIN32__ */
484
485 /* Set reparse data on extracted file or directory that has
486  * FILE_ATTRIBUTE_REPARSE_POINT set.  */
487 static int
488 extract_reparse_data(const tchar *path, struct apply_ctx *ctx,
489                      struct wim_inode *inode,
490                      struct wim_lookup_table_entry *lte_override)
491 {
492         int ret;
493         u8 rpbuf[REPARSE_POINT_MAX_SIZE];
494         u16 rpbuflen;
495
496         ret = wim_inode_get_reparse_data(inode, rpbuf, &rpbuflen, lte_override);
497         if (ret)
498                 goto error;
499
500 #ifdef __WIN32__
501         /* Fix up target of absolute symbolic link or junction points so
502          * that they point into the actual extraction target.  */
503         if ((ctx->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX) &&
504             (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
505              inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT) &&
506             !inode->i_not_rpfixed)
507         {
508                 ret = try_extract_rpfix(rpbuf, &rpbuflen, ctx->realtarget,
509                                         ctx->realtarget_nchars);
510                 if (ret && !(ctx->extract_flags &
511                              WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS))
512                 {
513                         WARNING("Reparse point fixup of \"%"TS"\" "
514                                 "failed", path);
515                         ret = 0;
516                 }
517                 if (ret)
518                         goto error;
519         }
520 #endif
521
522         ret = ctx->ops->set_reparse_data(path, rpbuf, rpbuflen, ctx);
523
524         /* On Windows, the SeCreateSymbolicLink privilege is required to create
525          * symbolic links.  To be more friendly towards non-Administrator users,
526          * we merely warn the user if symbolic links cannot be created due to
527          * insufficient permissions or privileges, unless
528          * WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS was provided.  */
529 #ifdef __WIN32__
530         if (ret && inode_is_symlink(inode) &&
531             (errno == EACCES || errno == EPERM) &&
532             !(ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS))
533         {
534                 WARNING("Can't set reparse data on \"%"TS"\": "
535                         "Access denied!\n"
536                         "          You may be trying to "
537                         "extract a symbolic link without the\n"
538                         "          SeCreateSymbolicLink privilege, "
539                         "which by default non-Administrator\n"
540                         "          accounts do not have.",
541                         path);
542                 ret = 0;
543         }
544 #endif
545         if (ret)
546                 goto error;
547
548         /* Account for reparse data consumed.  */
549         update_extract_progress(ctx,
550                                 (lte_override ? lte_override :
551                                       inode_unnamed_lte_resolved(inode)));
552         return 0;
553
554 error:
555         ERROR_WITH_ERRNO("Failed to set reparse data on \"%"TS"\"", path);
556         return ret;
557 }
558
559 /*
560  * Extract zero or more streams to a file.
561  *
562  * This function operates slightly differently depending on whether @lte_spec is
563  * NULL or not.  When @lte_spec is NULL, the behavior is to extract the default
564  * file contents (unnamed stream), and, if named data streams are supported in
565  * the extract mode and volume, any named data streams.  When @lte_spec is not
566  * NULL, the behavior is to extract only all copies of the stream @lte_spec, and
567  * in addition use @lte_spec to set the reparse data or create the symbolic link
568  * if appropriate.
569  *
570  * @path
571  *      Path to file to extract (as can be passed to apply_operations
572  *      functions).
573  * @ctx
574  *      Apply context.
575  * @dentry
576  *      WIM dentry that corresponds to the file being extracted.
577  * @lte_spec
578  *      If non-NULL, specifies the lookup table entry for a stream to extract,
579  *      and only that stream will be extracted (although there may be more than
580  *      one instance of it).
581  * @lte_override
582  *      Used only if @lte_spec != NULL; it is passed to the extraction functions
583  *      rather than @lte_spec, allowing the location of the stream to be
584  *      overridden.  (This is used when the WIM is being read from a nonseekable
585  *      file, such as a pipe, when streams need to be used more than once; each
586  *      such stream is extracted to a temporary file.)
587  */
588 static int
589 extract_streams(const tchar *path, struct apply_ctx *ctx,
590                 struct wim_dentry *dentry,
591                 struct wim_lookup_table_entry *lte_spec,
592                 struct wim_lookup_table_entry *lte_override)
593 {
594         struct wim_inode *inode = dentry->d_inode;
595         struct wim_lookup_table_entry *lte;
596         file_spec_t file_spec;
597         int ret;
598
599         if (dentry->was_hardlinked)
600                 return 0;
601
602 #ifdef ENABLE_DEBUG
603         if (lte_spec) {
604                 char sha1_str[100];
605                 char *p = sha1_str;
606                 for (unsigned i = 0; i < SHA1_HASH_SIZE; i++)
607                         p += sprintf(p, "%02x", lte_override->hash[i]);
608                 DEBUG("Extracting stream SHA1=%s to \"%"TS"\"",
609                       sha1_str, path, inode->i_ino);
610         } else {
611                 DEBUG("Extracting streams to \"%"TS"\"", path, inode->i_ino);
612         }
613 #endif
614
615         if (ctx->ops->uses_cookies)
616                 file_spec.cookie = inode->extract_cookie;
617         else
618                 file_spec.path = path;
619
620         /* Unnamed data stream.  */
621         lte = inode_unnamed_lte_resolved(inode);
622         if (lte && (!lte_spec || lte == lte_spec)) {
623                 if (lte_spec)
624                         lte = lte_override;
625                 if (!(inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
626                                              FILE_ATTRIBUTE_REPARSE_POINT)))
627                 {
628                         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED &&
629                             ctx->supported_features.encrypted_files) {
630                                 if (!ctx->ops->extract_encrypted_stream_creates_file) {
631                                         ret = ctx->ops->extract_encrypted_stream(
632                                                                 path, lte, ctx);
633                                         if (ret)
634                                                 goto error;
635                                 }
636                         } else {
637                                 ret = ctx->ops->extract_unnamed_stream(
638                                                         file_spec, lte, ctx);
639                                 if (ret)
640                                         goto error;
641                         }
642                         update_extract_progress(ctx, lte);
643                 }
644                 else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
645                 {
646                         ret = 0;
647                         if (ctx->supported_features.reparse_points)
648                                 ret = extract_reparse_data(path, ctx, inode, lte);
649                 #ifndef __WIN32__
650                         else if ((inode_is_symlink(inode) &&
651                                   ctx->supported_features.symlink_reparse_points))
652                                 ret = extract_symlink(path, ctx, inode, lte);
653                 #endif
654                         if (ret)
655                                 return ret;
656                 }
657         }
658
659         /* Named data streams.  */
660         if (can_extract_named_data_streams(ctx)) {
661                 for (u16 i = 0; i < inode->i_num_ads; i++) {
662                         struct wim_ads_entry *entry = &inode->i_ads_entries[i];
663
664                         if (!ads_entry_is_named_stream(entry))
665                                 continue;
666                         lte = entry->lte;
667                         if (!lte)
668                                 continue;
669                         if (lte_spec && lte_spec != lte)
670                                 continue;
671                         if (lte_spec)
672                                 lte = lte_override;
673                         ret = ctx->ops->extract_named_stream(file_spec, entry->stream_name,
674                                                              entry->stream_name_nbytes / 2,
675                                                              lte, ctx);
676                         if (ret)
677                                 goto error;
678                         update_extract_progress(ctx, lte);
679                 }
680         }
681         return 0;
682
683 error:
684         ERROR_WITH_ERRNO("Failed to extract data of \"%"TS"\"", path);
685         return ret;
686 }
687
688 /* Set attributes on an extracted file or directory if supported by the
689  * extraction mode.  */
690 static int
691 extract_file_attributes(const tchar *path, struct apply_ctx *ctx,
692                         struct wim_dentry *dentry, unsigned pass)
693 {
694         int ret;
695
696         if (ctx->ops->set_file_attributes &&
697             !(ctx->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES) &&
698             !(dentry == ctx->extract_root && ctx->root_dentry_is_special)) {
699                 u32 attributes = dentry->d_inode->i_attributes;
700
701                 /* Clear unsupported attributes.  */
702                 attributes &= ctx->supported_attributes_mask;
703
704                 if ((attributes & FILE_ATTRIBUTE_DIRECTORY &&
705                      !ctx->supported_features.encrypted_directories) ||
706                     (!(attributes & FILE_ATTRIBUTE_DIRECTORY) &&
707                      !ctx->supported_features.encrypted_files))
708                 {
709                         attributes &= ~FILE_ATTRIBUTE_ENCRYPTED;
710                 }
711
712                 if (attributes == 0)
713                         attributes = FILE_ATTRIBUTE_NORMAL;
714
715                 ret = ctx->ops->set_file_attributes(path, attributes, ctx, pass);
716                 if (ret) {
717                         ERROR_WITH_ERRNO("Failed to set attributes on "
718                                          "\"%"TS"\"", path);
719                         return ret;
720                 }
721         }
722         return 0;
723 }
724
725
726 /* Set or remove the short (DOS) name on an extracted file or directory if
727  * supported by the extraction mode.  Since DOS names are unimportant and it's
728  * easy to run into problems setting them on Windows (SetFileShortName()
729  * requires SE_RESTORE privilege, which only the Administrator can request, and
730  * also requires DELETE access to the file), failure is ignored unless
731  * WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES is set.  */
732 static int
733 extract_short_name(const tchar *path, struct apply_ctx *ctx,
734                    struct wim_dentry *dentry)
735 {
736         int ret;
737
738         /* The root of the dentry tree being extracted may not be extracted to
739          * its original name, so its short name should be ignored.  */
740         if (dentry == ctx->extract_root)
741                 return 0;
742
743         if (ctx->supported_features.short_names) {
744                 ret = ctx->ops->set_short_name(path,
745                                                dentry->short_name,
746                                                dentry->short_name_nbytes / 2,
747                                                ctx);
748                 if (ret && (ctx->extract_flags &
749                             WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES))
750                 {
751                         ERROR_WITH_ERRNO("Failed to set short name of "
752                                          "\"%"TS"\"", path);
753                         return ret;
754                 }
755         }
756         return 0;
757 }
758
759 /* Set security descriptor, UNIX data, or neither on an extracted file, taking
760  * into account the current extraction mode and flags.  */
761 static int
762 extract_security(const tchar *path, struct apply_ctx *ctx,
763                  struct wim_dentry *dentry)
764 {
765         int ret;
766         struct wim_inode *inode = dentry->d_inode;
767
768         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
769                 return 0;
770
771         if ((ctx->extract_root == dentry) && ctx->root_dentry_is_special)
772                 return 0;
773
774 #ifndef __WIN32__
775         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
776                 struct wimlib_unix_data data;
777
778                 ret = inode_get_unix_data(inode, &data, NULL);
779                 if (ret < 0)
780                         ret = 0;
781                 else if (ret == 0)
782                         ret = ctx->ops->set_unix_data(path, &data, ctx);
783                 if (ret) {
784                         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
785                                 ERROR_WITH_ERRNO("Failed to set UNIX owner, "
786                                                  "group, and/or mode on "
787                                                  "\"%"TS"\"", path);
788                                 return ret;
789                         } else {
790                                 WARNING_WITH_ERRNO("Failed to set UNIX owner, "
791                                                    "group, and/or/mode on "
792                                                    "\"%"TS"\"", path);
793                         }
794                 }
795         }
796         else
797 #endif /* __WIN32__ */
798         if (ctx->supported_features.security_descriptors &&
799             inode->i_security_id != -1)
800         {
801                 const struct wim_security_data *sd;
802                 const u8 *desc;
803                 size_t desc_size;
804
805                 sd = wim_const_security_data(ctx->wim);
806                 desc = sd->descriptors[inode->i_security_id];
807                 desc_size = sd->sizes[inode->i_security_id];
808
809                 ret = ctx->ops->set_security_descriptor(path, desc,
810                                                         desc_size, ctx);
811                 if (ret) {
812                         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
813                                 ERROR_WITH_ERRNO("Failed to set security "
814                                                  "descriptor on \"%"TS"\"", path);
815                                 return ret;
816                         } else {
817                         #if 0
818                                 if (errno != EACCES) {
819                                         WARNING_WITH_ERRNO("Failed to set "
820                                                            "security descriptor "
821                                                            "on \"%"TS"\"", path);
822                                 }
823                         #endif
824                                 ctx->no_security_descriptors++;
825                         }
826                 }
827         }
828         return 0;
829 }
830
831 /* Set timestamps on an extracted file.  Failure is warning-only unless
832  * WIMLIB_EXTRACT_FLAG_STRICT_TIMESTAMPS is set.  */
833 static int
834 extract_timestamps(const tchar *path, struct apply_ctx *ctx,
835                    struct wim_dentry *dentry)
836 {
837         struct wim_inode *inode = dentry->d_inode;
838         int ret;
839
840         if ((ctx->extract_root == dentry) && ctx->root_dentry_is_special)
841                 return 0;
842
843         if (ctx->ops->set_timestamps) {
844                 ret = ctx->ops->set_timestamps(path,
845                                                inode->i_creation_time,
846                                                inode->i_last_write_time,
847                                                inode->i_last_access_time,
848                                                ctx);
849                 if (ret) {
850                         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_TIMESTAMPS) {
851                                 ERROR_WITH_ERRNO("Failed to set timestamps "
852                                                  "on \"%"TS"\"", path);
853                                 return ret;
854                         } else {
855                                 WARNING_WITH_ERRNO("Failed to set timestamps "
856                                                    "on \"%"TS"\"", path);
857                         }
858                 }
859         }
860         return 0;
861 }
862
863 /* Check whether the extraction of a dentry should be skipped completely.  */
864 static bool
865 dentry_is_supported(struct wim_dentry *dentry,
866                     const struct wim_features *supported_features)
867 {
868         struct wim_inode *inode = dentry->d_inode;
869
870         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
871                 return supported_features->reparse_points ||
872                         (inode_is_symlink(inode) &&
873                          supported_features->symlink_reparse_points);
874         }
875         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
876                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
877                         return supported_features->encrypted_directories != 0;
878                 else
879                         return supported_features->encrypted_files != 0;
880         }
881         return true;
882 }
883
884 /* Given a WIM dentry to extract, build the path to which to extract it, in the
885  * format understood by the callbacks in the apply_operations being used.
886  *
887  * Write the resulting path into @path, which must have room for at least
888  * ctx->ops->max_path characters including the null-terminator.
889  *
890  * Return %true if successful; %false if this WIM dentry doesn't actually need
891  * to be extracted or if the calculated path exceeds ctx->ops->max_path
892  * characters.
893  *
894  * This function clobbers the tmp_list member of @dentry and its ancestors up
895  * until the extraction root.  */
896 static bool
897 build_extraction_path(tchar path[], struct wim_dentry *dentry,
898                       struct apply_ctx *ctx)
899 {
900         size_t path_nchars;
901         LIST_HEAD(ancestor_list);
902         tchar *p = path;
903         const tchar *target_prefix;
904         size_t target_prefix_nchars;
905         struct wim_dentry *d;
906
907         if (dentry->extraction_skipped)
908                 return false;
909
910         path_nchars = ctx->ops->path_prefix_nchars;
911
912         if (ctx->ops->requires_realtarget_in_paths) {
913                 target_prefix        = ctx->realtarget;
914                 target_prefix_nchars = ctx->realtarget_nchars;
915         } else if (ctx->ops->requires_target_in_paths) {
916                 target_prefix        = ctx->target;
917                 target_prefix_nchars = ctx->target_nchars;
918         } else {
919                 target_prefix        = NULL;
920                 target_prefix_nchars = 0;
921         }
922         path_nchars += target_prefix_nchars;
923
924         for (d = dentry; d != ctx->extract_root; d = d->parent) {
925                 if (!d->in_extraction_tree || d->extraction_skipped)
926                         break;
927
928                 path_nchars += d->extraction_name_nchars + 1;
929                 list_add(&d->tmp_list, &ancestor_list);
930         }
931
932         path_nchars++; /* null terminator */
933
934         if (path_nchars > ctx->ops->path_max) {
935                 WARNING("\"%"TS"\": Path too long to extract",
936                         dentry_full_path(dentry));
937                 return false;
938         }
939
940         p = tmempcpy(p, ctx->ops->path_prefix, ctx->ops->path_prefix_nchars);
941         p = tmempcpy(p, target_prefix, target_prefix_nchars);
942         list_for_each_entry(d, &ancestor_list, tmp_list) {
943                 *p++ = ctx->ops->path_separator;
944                 p = tmempcpy(p, d->extraction_name, d->extraction_name_nchars);
945         }
946         *p++ = T('\0');
947         wimlib_assert(p - path == path_nchars);
948         return true;
949 }
950
951 static unsigned
952 get_num_path_components(const tchar *path, tchar path_separator)
953 {
954         unsigned num_components = 0;
955 #ifdef __WIN32__
956         /* Ignore drive letter.  */
957         if (path[0] != L'\0' && path[1] == L':')
958                 path += 2;
959 #endif
960
961         while (*path) {
962                 while (*path == path_separator)
963                         path++;
964                 if (*path)
965                         num_components++;
966                 while (*path && *path != path_separator)
967                         path++;
968         }
969         return num_components;
970 }
971
972 static int
973 extract_multiimage_symlink(const tchar *oldpath, const tchar *newpath,
974                            struct apply_ctx *ctx, struct wim_dentry *dentry)
975 {
976         size_t num_raw_path_components;
977         const struct wim_dentry *d;
978         size_t num_target_path_components;
979         tchar *p;
980         const tchar *p_old;
981         int ret;
982
983         num_raw_path_components = 0;
984         for (d = dentry; d != ctx->extract_root; d = d->parent)
985                 num_raw_path_components++;
986
987         if (ctx->ops->requires_realtarget_in_paths)
988                 num_target_path_components = get_num_path_components(ctx->realtarget,
989                                                                      ctx->ops->path_separator);
990         else if (ctx->ops->requires_target_in_paths)
991                 num_target_path_components = get_num_path_components(ctx->target,
992                                                                      ctx->ops->path_separator);
993         else
994                 num_target_path_components = 0;
995
996         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_MULTI_IMAGE) {
997                 wimlib_assert(num_target_path_components > 0);
998                 num_raw_path_components++;
999                 num_target_path_components--;
1000         }
1001
1002         p_old = oldpath + ctx->ops->path_prefix_nchars;
1003 #ifdef __WIN32__
1004         if (p_old[0] != L'\0' && p_old[1] == ':')
1005                 p_old += 2;
1006 #endif
1007         while (*p_old == ctx->ops->path_separator)
1008                 p_old++;
1009         while (--num_target_path_components) {
1010                 while (*p_old != ctx->ops->path_separator)
1011                         p_old++;
1012                 while (*p_old == ctx->ops->path_separator)
1013                         p_old++;
1014         }
1015
1016         tchar symlink_target[tstrlen(p_old) + 3 * num_raw_path_components + 1];
1017
1018         p = &symlink_target[0];
1019         while (num_raw_path_components--) {
1020                 *p++ = '.';
1021                 *p++ = '.';
1022                 *p++ = ctx->ops->path_separator;
1023         }
1024         tstrcpy(p, p_old);
1025         DEBUG("Creating symlink \"%"TS"\" => \"%"TS"\"",
1026               newpath, symlink_target);
1027         ret = ctx->ops->create_symlink(symlink_target, newpath, ctx);
1028         if (ret) {
1029                 ERROR_WITH_ERRNO("Failed to create symlink "
1030                                  "\"%"TS"\" => \"%"TS"\"",
1031                                  newpath, symlink_target);
1032         }
1033         return ret;
1034 }
1035
1036 /* Create the "skeleton" of an extracted file or directory.  Don't yet extract
1037  * data streams, reparse data (including symbolic links), timestamps, and
1038  * security descriptors.  Basically, everything that doesn't require reading
1039  * non-metadata resources from the WIM file and isn't delayed until the final
1040  * pass.  */
1041 static int
1042 do_dentry_extract_skeleton(tchar path[], struct wim_dentry *dentry,
1043                            struct apply_ctx *ctx)
1044 {
1045         struct wim_inode *inode = dentry->d_inode;
1046         int ret;
1047         const tchar *oldpath;
1048
1049         if (unlikely(is_linked_extraction(ctx))) {
1050                 struct wim_lookup_table_entry *unnamed_lte;
1051
1052                 unnamed_lte = inode_unnamed_lte_resolved(dentry->d_inode);
1053                 if (unnamed_lte && unnamed_lte->extracted_file) {
1054                         oldpath = unnamed_lte->extracted_file;
1055                         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_HARDLINK)
1056                                 goto hardlink;
1057                         else
1058                                 goto symlink;
1059                 }
1060         }
1061
1062         /* Create hard link if this dentry corresponds to an already-extracted
1063          * inode.  */
1064         if (inode->i_extracted_file) {
1065                 oldpath = inode->i_extracted_file;
1066                 goto hardlink;
1067         }
1068
1069         /* Skip symlinks unless they can be extracted as reparse points rather
1070          * than created directly.  */
1071         if (inode_is_symlink(inode) && !ctx->supported_features.reparse_points)
1072                 return 0;
1073
1074         /* Create this file or directory unless it's the extraction root, which
1075          * was already created if necessary.  */
1076         if (dentry != ctx->extract_root) {
1077                 ret = extract_inode(path, ctx, inode);
1078                 if (ret)
1079                         return ret;
1080         }
1081
1082         /* Create empty named data streams.  */
1083         if (can_extract_named_data_streams(ctx)) {
1084                 for (u16 i = 0; i < inode->i_num_ads; i++) {
1085                         file_spec_t file_spec;
1086                         struct wim_ads_entry *entry = &inode->i_ads_entries[i];
1087
1088                         if (!ads_entry_is_named_stream(entry))
1089                                 continue;
1090                         if (entry->lte)
1091                                 continue;
1092                         if (ctx->ops->uses_cookies)
1093                                 file_spec.cookie = inode->extract_cookie;
1094                         else
1095                                 file_spec.path = path;
1096                         ret = ctx->ops->extract_named_stream(file_spec,
1097                                                              entry->stream_name,
1098                                                              entry->stream_name_nbytes / 2,
1099                                                              entry->lte, ctx);
1100                         if (ret) {
1101                                 ERROR_WITH_ERRNO("\"%"TS"\": failed to create "
1102                                                  "empty named data stream",
1103                                                  path);
1104                                 return ret;
1105                         }
1106                 }
1107         }
1108
1109         /* Set file attributes (if supported).  */
1110         ret = extract_file_attributes(path, ctx, dentry, 0);
1111         if (ret)
1112                 return ret;
1113
1114         /* Set or remove file short name (if supported).  */
1115         ret = extract_short_name(path, ctx, dentry);
1116         if (ret)
1117                 return ret;
1118
1119         /* If inode has multiple links and hard links are supported in this
1120          * extraction mode and volume, save the path to the extracted file in
1121          * case it's needed to create a hard link.  */
1122         if (unlikely(is_linked_extraction(ctx))) {
1123                 struct wim_lookup_table_entry *unnamed_lte;
1124
1125                 unnamed_lte = inode_unnamed_lte_resolved(dentry->d_inode);
1126                 if (unnamed_lte) {
1127                         unnamed_lte->extracted_file = TSTRDUP(path);
1128                         if (!unnamed_lte->extracted_file)
1129                                 return WIMLIB_ERR_NOMEM;
1130                 }
1131         } else if (inode->i_nlink > 1 && ctx->supported_features.hard_links) {
1132                 inode->i_extracted_file = TSTRDUP(path);
1133                 if (!inode->i_extracted_file)
1134                         return WIMLIB_ERR_NOMEM;
1135         }
1136         return 0;
1137
1138 symlink:
1139         ret = extract_multiimage_symlink(oldpath, path, ctx, dentry);
1140         if (ret)
1141                 return ret;
1142         dentry->was_hardlinked = 1;
1143         return 0;
1144
1145 hardlink:
1146         ret = extract_hardlink(oldpath, path, ctx);
1147         if (ret)
1148                 return ret;
1149         dentry->was_hardlinked = 1;
1150         return 0;
1151 }
1152
1153 /* This is a wrapper around do_dentry_extract_skeleton() that handles building
1154  * the path, doing short name reordering.  This is also idempotent; dentries
1155  * already processed have skeleton_extracted set and no action is taken.  See
1156  * apply_operations.requires_short_name_reordering for more details about short
1157  * name reordering.  */
1158 static int
1159 dentry_extract_skeleton(struct wim_dentry *dentry, void *_ctx)
1160 {
1161         struct apply_ctx *ctx = _ctx;
1162         tchar path[ctx->ops->path_max];
1163         struct wim_dentry *orig_dentry;
1164         struct wim_dentry *other_dentry;
1165         int ret;
1166
1167         if (dentry->skeleton_extracted)
1168                 return 0;
1169
1170         orig_dentry = NULL;
1171         if (ctx->supported_features.short_names
1172             && ctx->ops->requires_short_name_reordering
1173             && !dentry_has_short_name(dentry)
1174             && !dentry->d_inode->i_dos_name_extracted)
1175         {
1176                 inode_for_each_dentry(other_dentry, dentry->d_inode) {
1177                         if (dentry_has_short_name(other_dentry)
1178                             && !other_dentry->skeleton_extracted
1179                             && other_dentry->in_extraction_tree
1180                             && !other_dentry->extraction_skipped)
1181                         {
1182                                 DEBUG("Creating %"TS" before %"TS" "
1183                                       "to guarantee correct DOS name extraction",
1184                                       dentry_full_path(other_dentry),
1185                                       dentry_full_path(dentry));
1186                                 orig_dentry = dentry;
1187                                 dentry = other_dentry;
1188                                 break;
1189                         }
1190                 }
1191         }
1192 again:
1193         if (!build_extraction_path(path, dentry, ctx))
1194                 return 0;
1195         ret = do_dentry_extract_skeleton(path, dentry, ctx);
1196         if (ret)
1197                 return ret;
1198
1199         dentry->skeleton_extracted = 1;
1200
1201         if (orig_dentry) {
1202                 dentry = orig_dentry;
1203                 orig_dentry = NULL;
1204                 goto again;
1205         }
1206         dentry->d_inode->i_dos_name_extracted = 1;
1207         return 0;
1208 }
1209
1210 static int
1211 dentry_extract_dir_skeleton(struct wim_dentry *dentry, void *_ctx)
1212 {
1213         if (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1214                 return dentry_extract_skeleton(dentry, _ctx);
1215         return 0;
1216 }
1217
1218 /* Create a file or directory, then immediately extract all streams.  The WIM
1219  * may not be read sequentially by this function.  */
1220 static int
1221 dentry_extract(struct wim_dentry *dentry, void *_ctx)
1222 {
1223         struct apply_ctx *ctx = _ctx;
1224         tchar path[ctx->ops->path_max];
1225         int ret;
1226
1227         ret = dentry_extract_skeleton(dentry, ctx);
1228         if (ret)
1229                 return ret;
1230
1231         if (!build_extraction_path(path, dentry, ctx))
1232                 return 0;
1233
1234         return extract_streams(path, ctx, dentry, NULL, NULL);
1235 }
1236
1237 /* Creates a temporary file opened for writing.  The open file descriptor is
1238  * returned in @fd_ret and its name is returned in @name_ret (dynamically
1239  * allocated).  */
1240 static int
1241 create_temporary_file(struct filedes *fd_ret, tchar **name_ret)
1242 {
1243         tchar *name;
1244         int raw_fd;
1245
1246 retry:
1247         name = ttempnam(NULL, T("wimlib"));
1248         if (name == NULL) {
1249                 ERROR_WITH_ERRNO("Failed to create temporary filename");
1250                 return WIMLIB_ERR_NOMEM;
1251         }
1252
1253         raw_fd = topen(name, O_WRONLY | O_CREAT | O_EXCL | O_BINARY, 0600);
1254
1255         if (raw_fd < 0) {
1256                 if (errno == EEXIST) {
1257                         FREE(name);
1258                         goto retry;
1259                 }
1260                 ERROR_WITH_ERRNO("Failed to open temporary file \"%"TS"\"", name);
1261                 FREE(name);
1262                 return WIMLIB_ERR_OPEN;
1263         }
1264
1265         filedes_init(fd_ret, raw_fd);
1266         *name_ret = name;
1267         return 0;
1268 }
1269
1270 /* Extract all instances of the stream @lte that are being extracted in this
1271  * call of extract_tree(), but actually read the stream data from @lte_override.
1272  */
1273 static int
1274 extract_stream_instances(struct wim_lookup_table_entry *lte,
1275                          struct wim_lookup_table_entry *lte_override,
1276                          struct apply_ctx *ctx)
1277 {
1278         struct wim_dentry **lte_dentries;
1279         tchar path[ctx->ops->path_max];
1280         size_t i;
1281         int ret;
1282
1283         if (lte->out_refcnt <= ARRAY_LEN(lte->inline_lte_dentries))
1284                 lte_dentries = lte->inline_lte_dentries;
1285         else
1286                 lte_dentries = lte->lte_dentries;
1287
1288         for (i = 0; i < lte->out_refcnt; i++) {
1289                 struct wim_dentry *dentry = lte_dentries[i];
1290
1291                 if (dentry->tmp_flag)
1292                         continue;
1293                 if (!build_extraction_path(path, dentry, ctx))
1294                         continue;
1295                 ret = extract_streams(path, ctx, dentry, lte, lte_override);
1296                 if (ret)
1297                         goto out_clear_tmp_flags;
1298                 dentry->tmp_flag = 1;
1299         }
1300         ret = 0;
1301 out_clear_tmp_flags:
1302         for (i = 0; i < lte->out_refcnt; i++)
1303                 lte_dentries[i]->tmp_flag = 0;
1304         return ret;
1305 }
1306
1307 /* Determine whether the specified stream needs to be extracted to a temporary
1308  * file or not.
1309  *
1310  * @lte->out_refcnt specifies the number of instances of this stream that must
1311  * be extracted.
1312  *
1313  * @is_partial_res is %true if this stream is just one of multiple in a single
1314  * WIM resource being extracted.  */
1315 static bool
1316 need_tmpfile_to_extract(struct wim_lookup_table_entry *lte,
1317                         bool is_partial_res)
1318 {
1319         /* Temporary file is always required when reading a partial resource,
1320          * since in that case we retrieve all the contained streams in one pass.
1321          * */
1322         if (is_partial_res)
1323                 return true;
1324
1325         /* Otherwise we don't need a temporary file if only a single instance of
1326          * the stream is needed.  */
1327         if (lte->out_refcnt == 1)
1328                 return false;
1329
1330         wimlib_assert(lte->out_refcnt >= 2);
1331
1332         /* We also don't need a temporary file if random access to the stream is
1333          * allowed.  */
1334         if (lte->resource_location != RESOURCE_IN_WIM ||
1335             filedes_is_seekable(&lte->rspec->wim->in_fd))
1336                 return false;
1337
1338         return true;
1339 }
1340
1341 static int
1342 begin_extract_stream_to_tmpfile(struct wim_lookup_table_entry *lte,
1343                                 bool is_partial_res,
1344                                 void *_ctx)
1345 {
1346         struct apply_ctx *ctx = _ctx;
1347         int ret;
1348
1349         if (!need_tmpfile_to_extract(lte, is_partial_res)) {
1350                 DEBUG("Temporary file not needed "
1351                       "for stream (size=%"PRIu64")", lte->size);
1352                 ret = extract_stream_instances(lte, lte, ctx);
1353                 if (ret)
1354                         return ret;
1355
1356                 return BEGIN_STREAM_STATUS_SKIP_STREAM;
1357         }
1358
1359         DEBUG("Temporary file needed for stream (size=%"PRIu64")", lte->size);
1360         return create_temporary_file(&ctx->tmpfile_fd, &ctx->tmpfile_name);
1361 }
1362
1363 static int
1364 end_extract_stream_to_tmpfile(struct wim_lookup_table_entry *lte,
1365                               int status, void *_ctx)
1366 {
1367         struct apply_ctx *ctx = _ctx;
1368         struct wim_lookup_table_entry lte_override;
1369         int ret;
1370         int errno_save = errno;
1371
1372         ret = filedes_close(&ctx->tmpfile_fd);
1373
1374         if (status) {
1375                 ret = status;
1376                 errno = errno_save;
1377                 goto out_delete_tmpfile;
1378         }
1379
1380         if (ret) {
1381                 ERROR_WITH_ERRNO("Error writing temporary file %"TS, ctx->tmpfile_name);
1382                 ret = WIMLIB_ERR_WRITE;
1383                 goto out_delete_tmpfile;
1384         }
1385
1386         /* Now that a full stream has been extracted to a temporary file,
1387          * extract all instances of it to the actual target.  */
1388
1389         memcpy(&lte_override, lte, sizeof(struct wim_lookup_table_entry));
1390         lte_override.resource_location = RESOURCE_IN_FILE_ON_DISK;
1391         lte_override.file_on_disk = ctx->tmpfile_name;
1392
1393         ret = extract_stream_instances(lte, &lte_override, ctx);
1394
1395 out_delete_tmpfile:
1396         errno_save = errno;
1397         tunlink(ctx->tmpfile_name);
1398         FREE(ctx->tmpfile_name);
1399         errno = errno_save;
1400         return ret;
1401 }
1402
1403 /* Extracts a list of streams (ctx.stream_list), assuming that the directory
1404  * structure and empty files were already created.  This relies on the
1405  * per-`struct wim_lookup_table_entry' list of dentries that reference each
1406  * stream that was constructed earlier.  */
1407 static int
1408 extract_stream_list(struct apply_ctx *ctx)
1409 {
1410         struct read_stream_list_callbacks cbs = {
1411                 .begin_stream           = begin_extract_stream_to_tmpfile,
1412                 .begin_stream_ctx       = ctx,
1413                 .consume_chunk          = extract_chunk_to_fd,
1414                 .consume_chunk_ctx      = &ctx->tmpfile_fd,
1415                 .end_stream             = end_extract_stream_to_tmpfile,
1416                 .end_stream_ctx         = ctx,
1417         };
1418         return read_stream_list(&ctx->stream_list,
1419                                 offsetof(struct wim_lookup_table_entry, extraction_list),
1420                                 &cbs, VERIFY_STREAM_HASHES);
1421 }
1422
1423 #define PWM_ALLOW_WIM_HDR 0x00001
1424 #define PWM_SILENT_EOF    0x00002
1425
1426 /* Read the header from a stream in a pipable WIM.  */
1427 static int
1428 read_pwm_stream_header(WIMStruct *pwm, struct wim_lookup_table_entry *lte,
1429                        struct wim_resource_spec *rspec,
1430                        int flags, struct wim_header_disk *hdr_ret)
1431 {
1432         union {
1433                 struct pwm_stream_hdr stream_hdr;
1434                 struct wim_header_disk pwm_hdr;
1435         } buf;
1436         struct wim_reshdr reshdr;
1437         int ret;
1438
1439         ret = full_read(&pwm->in_fd, &buf.stream_hdr, sizeof(buf.stream_hdr));
1440         if (ret)
1441                 goto read_error;
1442
1443         if ((flags & PWM_ALLOW_WIM_HDR) && buf.stream_hdr.magic == PWM_MAGIC) {
1444                 BUILD_BUG_ON(sizeof(buf.pwm_hdr) < sizeof(buf.stream_hdr));
1445                 ret = full_read(&pwm->in_fd, &buf.stream_hdr + 1,
1446                                 sizeof(buf.pwm_hdr) - sizeof(buf.stream_hdr));
1447
1448                 if (ret)
1449                         goto read_error;
1450                 lte->resource_location = RESOURCE_NONEXISTENT;
1451                 memcpy(hdr_ret, &buf.pwm_hdr, sizeof(buf.pwm_hdr));
1452                 return 0;
1453         }
1454
1455         if (le64_to_cpu(buf.stream_hdr.magic) != PWM_STREAM_MAGIC) {
1456                 ERROR("Data read on pipe is invalid (expected stream header).");
1457                 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1458         }
1459
1460         copy_hash(lte->hash, buf.stream_hdr.hash);
1461
1462         reshdr.size_in_wim = 0;
1463         reshdr.flags = le32_to_cpu(buf.stream_hdr.flags);
1464         reshdr.offset_in_wim = pwm->in_fd.offset;
1465         reshdr.uncompressed_size = le64_to_cpu(buf.stream_hdr.uncompressed_size);
1466         wim_res_hdr_to_spec(&reshdr, pwm, rspec);
1467         lte_bind_wim_resource_spec(lte, rspec);
1468         lte->flags = rspec->flags;
1469         lte->size = rspec->uncompressed_size;
1470         lte->offset_in_res = 0;
1471         return 0;
1472
1473 read_error:
1474         if (ret != WIMLIB_ERR_UNEXPECTED_END_OF_FILE || !(flags & PWM_SILENT_EOF))
1475                 ERROR_WITH_ERRNO("Error reading pipable WIM from pipe");
1476         return ret;
1477 }
1478
1479 static int
1480 extract_streams_from_pipe(struct apply_ctx *ctx)
1481 {
1482         struct wim_lookup_table_entry *found_lte;
1483         struct wim_resource_spec *rspec;
1484         struct wim_lookup_table_entry *needed_lte;
1485         struct wim_lookup_table *lookup_table;
1486         struct wim_header_disk pwm_hdr;
1487         int ret;
1488         int pwm_flags;
1489
1490         ret = WIMLIB_ERR_NOMEM;
1491         found_lte = new_lookup_table_entry();
1492         if (found_lte == NULL)
1493                 goto out;
1494
1495         rspec = MALLOC(sizeof(struct wim_resource_spec));
1496         if (rspec == NULL)
1497                 goto out_free_found_lte;
1498
1499         lookup_table = ctx->wim->lookup_table;
1500         pwm_flags = PWM_ALLOW_WIM_HDR;
1501         if ((ctx->extract_flags & WIMLIB_EXTRACT_FLAG_RESUME))
1502                 pwm_flags |= PWM_SILENT_EOF;
1503         memcpy(ctx->progress.extract.guid, ctx->wim->hdr.guid, WIM_GID_LEN);
1504         ctx->progress.extract.part_number = ctx->wim->hdr.part_number;
1505         ctx->progress.extract.total_parts = ctx->wim->hdr.total_parts;
1506         if (ctx->progress_func)
1507                 ctx->progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_SPWM_PART_BEGIN,
1508                                    &ctx->progress);
1509         while (ctx->num_streams_remaining) {
1510                 if (found_lte->resource_location != RESOURCE_NONEXISTENT)
1511                         lte_unbind_wim_resource_spec(found_lte);
1512                 ret = read_pwm_stream_header(ctx->wim, found_lte, rspec,
1513                                              pwm_flags, &pwm_hdr);
1514                 if (ret) {
1515                         if (ret == WIMLIB_ERR_UNEXPECTED_END_OF_FILE &&
1516                             (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_RESUME))
1517                         {
1518                                 goto resume_done;
1519                         }
1520                         goto out_free_found_lte;
1521                 }
1522
1523                 if ((found_lte->resource_location != RESOURCE_NONEXISTENT)
1524                     && !(found_lte->flags & WIM_RESHDR_FLAG_METADATA)
1525                     && (needed_lte = lookup_stream(lookup_table, found_lte->hash))
1526                     && (needed_lte->out_refcnt))
1527                 {
1528                         tchar *tmpfile_name = NULL;
1529                         struct wim_lookup_table_entry *lte_override;
1530                         struct wim_lookup_table_entry tmpfile_lte;
1531
1532                         needed_lte->offset_in_res = found_lte->offset_in_res;
1533                         needed_lte->flags = found_lte->flags;
1534                         needed_lte->size = found_lte->size;
1535
1536                         lte_unbind_wim_resource_spec(found_lte);
1537                         lte_bind_wim_resource_spec(needed_lte, rspec);
1538
1539                         if (needed_lte->out_refcnt > 1) {
1540
1541                                 struct filedes tmpfile_fd;
1542
1543                                 /* Extract stream to temporary file.  */
1544                                 ret = create_temporary_file(&tmpfile_fd, &tmpfile_name);
1545                                 if (ret) {
1546                                         lte_unbind_wim_resource_spec(needed_lte);
1547                                         goto out_free_found_lte;
1548                                 }
1549
1550                                 ret = extract_full_stream_to_fd(needed_lte,
1551                                                                 &tmpfile_fd);
1552                                 if (ret) {
1553                                         filedes_close(&tmpfile_fd);
1554                                         goto delete_tmpfile;
1555                                 }
1556
1557                                 if (filedes_close(&tmpfile_fd)) {
1558                                         ERROR_WITH_ERRNO("Error writing to temporary "
1559                                                          "file \"%"TS"\"", tmpfile_name);
1560                                         ret = WIMLIB_ERR_WRITE;
1561                                         goto delete_tmpfile;
1562                                 }
1563                                 memcpy(&tmpfile_lte, needed_lte,
1564                                        sizeof(struct wim_lookup_table_entry));
1565                                 tmpfile_lte.resource_location = RESOURCE_IN_FILE_ON_DISK;
1566                                 tmpfile_lte.file_on_disk = tmpfile_name;
1567                                 lte_override = &tmpfile_lte;
1568                         } else {
1569                                 lte_override = needed_lte;
1570                         }
1571
1572                         ret = extract_stream_instances(needed_lte, lte_override, ctx);
1573                 delete_tmpfile:
1574                         lte_unbind_wim_resource_spec(needed_lte);
1575                         if (tmpfile_name) {
1576                                 tunlink(tmpfile_name);
1577                                 FREE(tmpfile_name);
1578                         }
1579                         if (ret)
1580                                 goto out_free_found_lte;
1581                         ctx->num_streams_remaining--;
1582                 } else if (found_lte->resource_location != RESOURCE_NONEXISTENT) {
1583                         ret = skip_wim_stream(found_lte);
1584                         if (ret)
1585                                 goto out_free_found_lte;
1586                 } else {
1587                         u16 part_number = le16_to_cpu(pwm_hdr.part_number);
1588                         u16 total_parts = le16_to_cpu(pwm_hdr.total_parts);
1589
1590                         if (part_number != ctx->progress.extract.part_number ||
1591                             total_parts != ctx->progress.extract.total_parts ||
1592                             memcmp(pwm_hdr.guid, ctx->progress.extract.guid,
1593                                    WIM_GID_LEN))
1594                         {
1595                                 ctx->progress.extract.part_number = part_number;
1596                                 ctx->progress.extract.total_parts = total_parts;
1597                                 memcpy(ctx->progress.extract.guid,
1598                                        pwm_hdr.guid, WIM_GID_LEN);
1599                                 if (ctx->progress_func) {
1600                                         ctx->progress_func(
1601                                                 WIMLIB_PROGRESS_MSG_EXTRACT_SPWM_PART_BEGIN,
1602                                                            &ctx->progress);
1603                                 }
1604
1605                         }
1606                 }
1607         }
1608         ret = 0;
1609 out_free_found_lte:
1610         if (found_lte->resource_location != RESOURCE_IN_WIM)
1611                 FREE(rspec);
1612         free_lookup_table_entry(found_lte);
1613 out:
1614         return ret;
1615
1616 resume_done:
1617         /* TODO */
1618         return 0;
1619 }
1620
1621 /* Finish extracting a file, directory, or symbolic link by setting file
1622  * security and timestamps.  */
1623 static int
1624 dentry_extract_final(struct wim_dentry *dentry, void *_ctx)
1625 {
1626         struct apply_ctx *ctx = _ctx;
1627         int ret;
1628         tchar path[ctx->ops->path_max];
1629
1630         if (!build_extraction_path(path, dentry, ctx))
1631                 return 0;
1632
1633         ret = extract_security(path, ctx, dentry);
1634         if (ret)
1635                 return ret;
1636
1637         if (ctx->ops->requires_final_set_attributes_pass) {
1638                 /* Set file attributes (if supported).  */
1639                 ret = extract_file_attributes(path, ctx, dentry, 1);
1640                 if (ret)
1641                         return ret;
1642         }
1643
1644         return extract_timestamps(path, ctx, dentry);
1645 }
1646
1647 /*
1648  * Extract a WIM dentry to standard output.
1649  *
1650  * This obviously doesn't make sense in all cases.  We return an error if the
1651  * dentry does not correspond to a regular file.  Otherwise we extract the
1652  * unnamed data stream only.
1653  */
1654 static int
1655 extract_dentry_to_stdout(struct wim_dentry *dentry)
1656 {
1657         int ret = 0;
1658         if (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
1659                                              FILE_ATTRIBUTE_DIRECTORY))
1660         {
1661                 ERROR("\"%"TS"\" is not a regular file and therefore cannot be "
1662                       "extracted to standard output", dentry_full_path(dentry));
1663                 ret = WIMLIB_ERR_NOT_A_REGULAR_FILE;
1664         } else {
1665                 struct wim_lookup_table_entry *lte;
1666
1667                 lte = inode_unnamed_lte_resolved(dentry->d_inode);
1668                 if (lte) {
1669                         struct filedes _stdout;
1670                         filedes_init(&_stdout, STDOUT_FILENO);
1671                         ret = extract_full_stream_to_fd(lte, &_stdout);
1672                 }
1673         }
1674         return ret;
1675 }
1676
1677 #ifdef __WIN32__
1678 static const utf16lechar replacement_char = cpu_to_le16(0xfffd);
1679 #else
1680 static const utf16lechar replacement_char = cpu_to_le16('?');
1681 #endif
1682
1683 static bool
1684 file_name_valid(utf16lechar *name, size_t num_chars, bool fix)
1685 {
1686         size_t i;
1687
1688         if (num_chars == 0)
1689                 return true;
1690         for (i = 0; i < num_chars; i++) {
1691                 switch (name[i]) {
1692         #ifdef __WIN32__
1693                 case cpu_to_le16('\\'):
1694                 case cpu_to_le16(':'):
1695                 case cpu_to_le16('*'):
1696                 case cpu_to_le16('?'):
1697                 case cpu_to_le16('"'):
1698                 case cpu_to_le16('<'):
1699                 case cpu_to_le16('>'):
1700                 case cpu_to_le16('|'):
1701         #endif
1702                 case cpu_to_le16('/'):
1703                 case cpu_to_le16('\0'):
1704                         if (fix)
1705                                 name[i] = replacement_char;
1706                         else
1707                                 return false;
1708                 }
1709         }
1710
1711 #ifdef __WIN32__
1712         if (name[num_chars - 1] == cpu_to_le16(' ') ||
1713             name[num_chars - 1] == cpu_to_le16('.'))
1714         {
1715                 if (fix)
1716                         name[num_chars - 1] = replacement_char;
1717                 else
1718                         return false;
1719         }
1720 #endif
1721         return true;
1722 }
1723
1724 static int
1725 dentry_mark_skipped(struct wim_dentry *dentry, void *_ignore)
1726 {
1727         dentry->extraction_skipped = 1;
1728         return 0;
1729 }
1730
1731 /*
1732  * dentry_calculate_extraction_path-
1733  *
1734  * Calculate the actual filename component at which a WIM dentry will be
1735  * extracted, handling invalid filenames "properly".
1736  *
1737  * dentry->extraction_name usually will be set the same as dentry->file_name (on
1738  * UNIX, converted into the platform's multibyte encoding).  However, if the
1739  * file name contains characters that are not valid on the current platform or
1740  * has some other format that is not valid, leave dentry->extraction_name as
1741  * NULL and set dentry->extraction_skipped to indicate that this dentry should
1742  * not be extracted, unless the appropriate flag
1743  * WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES is set in the extract flags, in
1744  * which case a substitute filename will be created and set instead.
1745  *
1746  * Conflicts with case-insensitive names on Windows are handled similarly; see
1747  * below.
1748  */
1749 static int
1750 dentry_calculate_extraction_path(struct wim_dentry *dentry, void *_args)
1751 {
1752         struct apply_ctx *ctx = _args;
1753         int ret;
1754
1755         if (dentry == ctx->extract_root || dentry->extraction_skipped)
1756                 return 0;
1757
1758         if (!dentry_is_supported(dentry, &ctx->supported_features))
1759                 goto skip_dentry;
1760
1761         if (!ctx->ops->supports_case_sensitive_filenames)
1762         {
1763                 struct wim_dentry *other;
1764                 list_for_each_entry(other, &dentry->case_insensitive_conflict_list,
1765                                     case_insensitive_conflict_list)
1766                 {
1767                         if (!other->extraction_skipped) {
1768                                 if (ctx->extract_flags &
1769                                     WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS) {
1770                                         WARNING("\"%"TS"\" has the same "
1771                                                 "case-insensitive name as "
1772                                                 "\"%"TS"\"; extracting "
1773                                                 "dummy name instead",
1774                                                 dentry_full_path(dentry),
1775                                                 dentry_full_path(other));
1776                                         goto out_replace;
1777                                 } else {
1778                                         WARNING("Not extracting \"%"TS"\": "
1779                                                 "has same case-insensitive "
1780                                                 "name as \"%"TS"\"",
1781                                                 dentry_full_path(dentry),
1782                                                 dentry_full_path(other));
1783                                         goto skip_dentry;
1784                                 }
1785                         }
1786                 }
1787         }
1788
1789         if (file_name_valid(dentry->file_name, dentry->file_name_nbytes / 2, false)) {
1790 #if TCHAR_IS_UTF16LE
1791                 dentry->extraction_name = dentry->file_name;
1792                 dentry->extraction_name_nchars = dentry->file_name_nbytes / 2;
1793                 return 0;
1794 #else
1795                 return utf16le_to_tstr(dentry->file_name,
1796                                        dentry->file_name_nbytes,
1797                                        &dentry->extraction_name,
1798                                        &dentry->extraction_name_nchars);
1799 #endif
1800         } else {
1801                 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES)
1802                 {
1803                         WARNING("\"%"TS"\" has an invalid filename "
1804                                 "that is not supported on this platform; "
1805                                 "extracting dummy name instead",
1806                                 dentry_full_path(dentry));
1807                         goto out_replace;
1808                 } else {
1809                         WARNING("Not extracting \"%"TS"\": has an invalid filename "
1810                                 "that is not supported on this platform",
1811                                 dentry_full_path(dentry));
1812                         goto skip_dentry;
1813                 }
1814         }
1815
1816 out_replace:
1817         {
1818                 utf16lechar utf16_name_copy[dentry->file_name_nbytes / 2];
1819
1820                 memcpy(utf16_name_copy, dentry->file_name, dentry->file_name_nbytes);
1821                 file_name_valid(utf16_name_copy, dentry->file_name_nbytes / 2, true);
1822
1823                 tchar *tchar_name;
1824                 size_t tchar_nchars;
1825         #if TCHAR_IS_UTF16LE
1826                 tchar_name = utf16_name_copy;
1827                 tchar_nchars = dentry->file_name_nbytes / 2;
1828         #else
1829                 ret = utf16le_to_tstr(utf16_name_copy,
1830                                       dentry->file_name_nbytes,
1831                                       &tchar_name, &tchar_nchars);
1832                 if (ret)
1833                         return ret;
1834         #endif
1835                 size_t fixed_name_num_chars = tchar_nchars;
1836                 tchar fixed_name[tchar_nchars + 50];
1837
1838                 tmemcpy(fixed_name, tchar_name, tchar_nchars);
1839                 fixed_name_num_chars += tsprintf(fixed_name + tchar_nchars,
1840                                                  T(" (invalid filename #%lu)"),
1841                                                  ++ctx->invalid_sequence);
1842         #if !TCHAR_IS_UTF16LE
1843                 FREE(tchar_name);
1844         #endif
1845                 dentry->extraction_name = memdup(fixed_name,
1846                                                  2 * fixed_name_num_chars + 2);
1847                 if (!dentry->extraction_name)
1848                         return WIMLIB_ERR_NOMEM;
1849                 dentry->extraction_name_nchars = fixed_name_num_chars;
1850         }
1851         return 0;
1852
1853 skip_dentry:
1854         for_dentry_in_tree(dentry, dentry_mark_skipped, NULL);
1855         return 0;
1856 }
1857
1858 /* Clean up dentry and inode structure after extraction.  */
1859 static int
1860 dentry_reset_needs_extraction(struct wim_dentry *dentry, void *_ignore)
1861 {
1862         struct wim_inode *inode = dentry->d_inode;
1863
1864         dentry->in_extraction_tree = 0;
1865         dentry->extraction_skipped = 0;
1866         dentry->was_hardlinked = 0;
1867         dentry->skeleton_extracted = 0;
1868         inode->i_visited = 0;
1869         FREE(inode->i_extracted_file);
1870         inode->i_extracted_file = NULL;
1871         inode->i_dos_name_extracted = 0;
1872         if ((void*)dentry->extraction_name != (void*)dentry->file_name)
1873                 FREE(dentry->extraction_name);
1874         dentry->extraction_name = NULL;
1875         return 0;
1876 }
1877
1878 /* Tally features necessary to extract a dentry and the corresponding inode.  */
1879 static int
1880 dentry_tally_features(struct wim_dentry *dentry, void *_features)
1881 {
1882         struct wim_features *features = _features;
1883         struct wim_inode *inode = dentry->d_inode;
1884
1885         if (dentry->extraction_skipped)
1886                 return 0;
1887
1888         if (inode->i_attributes & FILE_ATTRIBUTE_ARCHIVE)
1889                 features->archive_files++;
1890         if (inode->i_attributes & FILE_ATTRIBUTE_HIDDEN)
1891                 features->hidden_files++;
1892         if (inode->i_attributes & FILE_ATTRIBUTE_SYSTEM)
1893                 features->system_files++;
1894         if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED)
1895                 features->compressed_files++;
1896         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1897                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1898                         features->encrypted_directories++;
1899                 else
1900                         features->encrypted_files++;
1901         }
1902         if (inode->i_attributes & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED)
1903                 features->not_context_indexed_files++;
1904         if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE)
1905                 features->sparse_files++;
1906         if (inode_has_named_stream(inode))
1907                 features->named_data_streams++;
1908         if (inode->i_visited)
1909                 features->hard_links++;
1910         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1911                 features->reparse_points++;
1912                 if (inode_is_symlink(inode))
1913                         features->symlink_reparse_points++;
1914                 else
1915                         features->other_reparse_points++;
1916         }
1917         if (inode->i_security_id != -1)
1918                 features->security_descriptors++;
1919         if (dentry->short_name_nbytes)
1920                 features->short_names++;
1921         if (inode_has_unix_data(inode))
1922                 features->unix_data++;
1923         inode->i_visited = 1;
1924         return 0;
1925 }
1926
1927 /* Tally the features necessary to extract a dentry tree.  */
1928 static void
1929 dentry_tree_get_features(struct wim_dentry *root, struct wim_features *features)
1930 {
1931         memset(features, 0, sizeof(struct wim_features));
1932         for_dentry_in_tree(root, dentry_tally_features, features);
1933         dentry_tree_clear_inode_visited(root);
1934 }
1935
1936 static u32
1937 compute_supported_attributes_mask(const struct wim_features *supported_features)
1938 {
1939         u32 mask = ~(u32)0;
1940
1941         if (!supported_features->archive_files)
1942                 mask &= ~FILE_ATTRIBUTE_ARCHIVE;
1943
1944         if (!supported_features->hidden_files)
1945                 mask &= ~FILE_ATTRIBUTE_HIDDEN;
1946
1947         if (!supported_features->system_files)
1948                 mask &= ~FILE_ATTRIBUTE_SYSTEM;
1949
1950         if (!supported_features->not_context_indexed_files)
1951                 mask &= ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
1952
1953         if (!supported_features->compressed_files)
1954                 mask &= ~FILE_ATTRIBUTE_COMPRESSED;
1955
1956         if (!supported_features->sparse_files)
1957                 mask &= ~FILE_ATTRIBUTE_SPARSE_FILE;
1958
1959         if (!supported_features->reparse_points)
1960                 mask &= ~FILE_ATTRIBUTE_REPARSE_POINT;
1961
1962         return mask;
1963 }
1964
1965 static int
1966 do_feature_check(const struct wim_features *required_features,
1967                  const struct wim_features *supported_features,
1968                  int extract_flags, const struct apply_operations *ops)
1969 {
1970         /* File attributes.  */
1971         if (!(extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)) {
1972                 /* Note: Don't bother the user about FILE_ATTRIBUTE_ARCHIVE.
1973                  * We're an archive program, so theoretically we can do what we
1974                  * want with it.  */
1975
1976                 if (required_features->hidden_files &&
1977                     !supported_features->hidden_files)
1978                         WARNING("Ignoring FILE_ATTRIBUTE_HIDDEN of %lu files",
1979                                 required_features->hidden_files);
1980
1981                 if (required_features->system_files &&
1982                     !supported_features->system_files)
1983                         WARNING("Ignoring FILE_ATTRIBUTE_SYSTEM of %lu files",
1984                                 required_features->system_files);
1985
1986                 if (required_features->compressed_files &&
1987                     !supported_features->compressed_files)
1988                         WARNING("Ignoring FILE_ATTRIBUTE_COMPRESSED of %lu files",
1989                                 required_features->compressed_files);
1990
1991                 if (required_features->not_context_indexed_files &&
1992                     !supported_features->not_context_indexed_files)
1993                         WARNING("Ignoring FILE_ATTRIBUTE_NOT_CONTENT_INDEXED of %lu files",
1994                                 required_features->not_context_indexed_files);
1995
1996                 if (required_features->sparse_files &&
1997                     !supported_features->sparse_files)
1998                         WARNING("Ignoring FILE_ATTRIBUTE_SPARSE_FILE of %lu files",
1999                                 required_features->sparse_files);
2000
2001                 if (required_features->encrypted_directories &&
2002                     !supported_features->encrypted_directories)
2003                         WARNING("Ignoring FILE_ATTRIBUTE_ENCRYPTED of %lu directories",
2004                                 required_features->encrypted_directories);
2005         }
2006
2007         /* Encrypted files.  */
2008         if (required_features->encrypted_files &&
2009             !supported_features->encrypted_files)
2010                 WARNING("Ignoring %lu encrypted files",
2011                         required_features->encrypted_files);
2012
2013         /* Named data streams.  */
2014         if (required_features->named_data_streams &&
2015             (!supported_features->named_data_streams ||
2016              (extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
2017                                WIMLIB_EXTRACT_FLAG_HARDLINK))))
2018                 WARNING("Ignoring named data streams of %lu files",
2019                         required_features->named_data_streams);
2020
2021         /* Hard links.  */
2022         if ((extract_flags & WIMLIB_EXTRACT_FLAG_HARDLINK) &&
2023             !supported_features->hard_links)
2024         {
2025                 ERROR("Extraction backend does not support hard links!");
2026                 return WIMLIB_ERR_UNSUPPORTED;
2027         }
2028         if (required_features->hard_links && !supported_features->hard_links)
2029                 WARNING("Extracting %lu hard links as independent files",
2030                         required_features->hard_links);
2031
2032         /* Symbolic links and reparse points.  */
2033         if ((extract_flags & WIMLIB_EXTRACT_FLAG_SYMLINK) &&
2034             !supported_features->symlink_reparse_points)
2035         {
2036                 ERROR("Extraction backend does not support symbolic links!");
2037                 return WIMLIB_ERR_UNSUPPORTED;
2038         }
2039         if ((extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS) &&
2040             required_features->symlink_reparse_points &&
2041             !supported_features->symlink_reparse_points &&
2042             !supported_features->reparse_points)
2043         {
2044                 ERROR("Extraction backend does not support symbolic links!");
2045                 return WIMLIB_ERR_UNSUPPORTED;
2046         }
2047         if (required_features->reparse_points &&
2048             !supported_features->reparse_points)
2049         {
2050                 if (supported_features->symlink_reparse_points) {
2051                         if (required_features->other_reparse_points) {
2052                                 WARNING("Ignoring %lu non-symlink/junction "
2053                                         "reparse point files",
2054                                         required_features->other_reparse_points);
2055                         }
2056                 } else {
2057                         WARNING("Ignoring %lu reparse point files",
2058                                 required_features->reparse_points);
2059                 }
2060         }
2061
2062         /* Security descriptors.  */
2063         if (((extract_flags & (WIMLIB_EXTRACT_FLAG_STRICT_ACLS |
2064                                WIMLIB_EXTRACT_FLAG_UNIX_DATA))
2065              == WIMLIB_EXTRACT_FLAG_STRICT_ACLS) &&
2066             required_features->security_descriptors &&
2067             !supported_features->security_descriptors)
2068         {
2069                 ERROR("Extraction backend does not support security descriptors!");
2070                 return WIMLIB_ERR_UNSUPPORTED;
2071         }
2072         if (!(extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS) && 
2073             required_features->security_descriptors &&
2074             !supported_features->security_descriptors)
2075                 WARNING("Ignoring Windows NT security descriptors of %lu files",
2076                         required_features->security_descriptors);
2077
2078         /* UNIX data.  */
2079         if ((extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) &&
2080             required_features->unix_data && !supported_features->unix_data)
2081         {
2082                 ERROR("Extraction backend does not support UNIX data!");
2083                 return WIMLIB_ERR_UNSUPPORTED;
2084         }
2085
2086         /* DOS Names.  */
2087         if (required_features->short_names &&
2088             !supported_features->short_names)
2089         {
2090                 if (extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES) {
2091                         ERROR("Extraction backend does not support DOS names!");
2092                         return WIMLIB_ERR_UNSUPPORTED;
2093                 }
2094                 WARNING("Ignoring DOS names of %lu files",
2095                         required_features->short_names);
2096         }
2097
2098         /* Timestamps.  */
2099         if ((extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_TIMESTAMPS) &&
2100             !ops->set_timestamps)
2101         {
2102                 ERROR("Extraction backend does not support timestamps!");
2103                 return WIMLIB_ERR_UNSUPPORTED;
2104         }
2105
2106         return 0;
2107 }
2108
2109 static void
2110 do_extract_warnings(struct apply_ctx *ctx)
2111 {
2112         if (ctx->partial_security_descriptors == 0 &&
2113             ctx->no_security_descriptors == 0)
2114                 return;
2115
2116         WARNING("Extraction to \"%"TS"\" complete, but with one or more warnings:",
2117                 ctx->target);
2118         if (ctx->partial_security_descriptors != 0) {
2119                 WARNING("- Could only partially set the security descriptor\n"
2120                         "            on %lu files or directories.",
2121                         ctx->partial_security_descriptors);
2122         }
2123         if (ctx->no_security_descriptors != 0) {
2124                 WARNING("- Could not set security descriptor at all\n"
2125                         "            on %lu files or directories.",
2126                         ctx->no_security_descriptors);
2127         }
2128 #ifdef __WIN32__
2129         WARNING("To fully restore all security descriptors, run the program\n"
2130                 "          with Administrator rights.");
2131 #endif
2132 }
2133
2134 static int
2135 dentry_set_skipped(struct wim_dentry *dentry, void *_ignore)
2136 {
2137         dentry->in_extraction_tree = 1;
2138         dentry->extraction_skipped = 1;
2139         return 0;
2140 }
2141
2142 static int
2143 dentry_set_not_skipped(struct wim_dentry *dentry, void *_ignore)
2144 {
2145         dentry->in_extraction_tree = 1;
2146         dentry->extraction_skipped = 0;
2147         return 0;
2148 }
2149
2150 static int
2151 extract_trees(WIMStruct *wim, struct wim_dentry **trees, size_t num_trees,
2152               const tchar *target, int extract_flags,
2153               wimlib_progress_func_t progress_func)
2154 {
2155         struct wim_features required_features;
2156         struct apply_ctx ctx;
2157         int ret;
2158         struct wim_lookup_table_entry *lte;
2159
2160         /* Start initializing the apply_ctx.  */
2161         memset(&ctx, 0, sizeof(struct apply_ctx));
2162         ctx.wim = wim;
2163         ctx.extract_flags = extract_flags;
2164         ctx.target = target;
2165         ctx.target_nchars = tstrlen(target);
2166         ctx.progress_func = progress_func;
2167         if (progress_func) {
2168                 ctx.progress.extract.wimfile_name = wim->filename;
2169                 ctx.progress.extract.image = wim->current_image;
2170                 ctx.progress.extract.extract_flags = (extract_flags &
2171                                                       WIMLIB_EXTRACT_MASK_PUBLIC);
2172                 ctx.progress.extract.image_name = wimlib_get_image_name(wim,
2173                                                                         wim->current_image);
2174                 ctx.progress.extract.target = target;
2175         }
2176         INIT_LIST_HEAD(&ctx.stream_list);
2177
2178         if (extract_flags & WIMLIB_EXTRACT_FLAG_FILEMODE) {
2179                 /* File mode --- target is explicit.  */
2180                 wimlib_assert(num_trees == 1);
2181                 ret = calculate_dentry_full_path(trees[0]);
2182                 if (ret)
2183                         return ret;
2184                 ctx.progress.extract.extract_root_wim_source_path = trees[0]->_full_path;
2185                 ctx.extract_root = trees[0];
2186                 for_dentry_in_tree(ctx.extract_root, dentry_set_not_skipped, NULL);
2187         } else {
2188                 /* Targets are to be set relative to the root of the image
2189                  * (preserving original directory structure).  */
2190
2191                 ctx.progress.extract.extract_root_wim_source_path = T("");
2192                 ctx.extract_root = wim_root_dentry(wim);
2193                 for_dentry_in_tree(ctx.extract_root, dentry_set_skipped, NULL);
2194
2195                 for (size_t i = 0; i < num_trees; i++) {
2196                         struct wim_dentry *d;
2197
2198                         for_dentry_in_tree(trees[i], dentry_set_not_skipped, NULL);
2199                         d = trees[i];
2200
2201                         /* Extract directories up to image root if preserving
2202                          * directory structure.  */
2203                         if (!(extract_flags & WIMLIB_EXTRACT_FLAG_NO_PRESERVE_DIR_STRUCTURE)) {
2204                                 while (d != ctx.extract_root) {
2205                                         d = d->parent;
2206                                         dentry_set_not_skipped(d, NULL);
2207                                 }
2208                         }
2209                 }
2210         }
2211
2212         /* Select the appropriate apply_operations based on the
2213          * platform and extract_flags.  */
2214 #ifdef __WIN32__
2215         ctx.ops = &win32_apply_ops;
2216 #else
2217         ctx.ops = &unix_apply_ops;
2218 #endif
2219
2220 #ifdef WITH_NTFS_3G
2221         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS)
2222                 ctx.ops = &ntfs_3g_apply_ops;
2223 #endif
2224
2225         /* Call the start_extract() callback.  This gives the apply_operations
2226          * implementation a chance to do any setup needed to access the volume.
2227          * Furthermore, it's expected to set the supported features of this
2228          * extraction mode (ctx.supported_features), which are determined at
2229          * runtime as they may vary depending on the actual volume.  These
2230          * features are then compared with the actual features extracting this
2231          * dentry tree requires.  Some mismatches will merely produce warnings
2232          * and the unsupported data will be ignored; others will produce errors.
2233          */
2234         ret = ctx.ops->start_extract(target, &ctx);
2235         if (ret)
2236                 goto out_dentry_reset_needs_extraction;
2237
2238         /* Get and check the features required to extract the dentry tree.  */
2239         dentry_tree_get_features(ctx.extract_root, &required_features);
2240         ret = do_feature_check(&required_features, &ctx.supported_features,
2241                                extract_flags, ctx.ops);
2242         if (ret)
2243                 goto out_finish_or_abort_extract;
2244
2245         ctx.supported_attributes_mask =
2246                 compute_supported_attributes_mask(&ctx.supported_features);
2247
2248         /* Figure out whether the root dentry is being extracted to the root of
2249          * a volume and therefore needs to be treated "specially", for example
2250          * not being explicitly created and not having attributes set.  */
2251         if (ctx.ops->target_is_root && ctx.ops->root_directory_is_special)
2252                 ctx.root_dentry_is_special = ctx.ops->target_is_root(target);
2253
2254         /* Calculate the actual filename component of each extracted dentry.  In
2255          * the process, set the dentry->extraction_skipped flag on dentries that
2256          * are being skipped because of filename or supported features problems.  */
2257         ret = for_dentry_in_tree(ctx.extract_root,
2258                                  dentry_calculate_extraction_path, &ctx);
2259         if (ret)
2260                 goto out_dentry_reset_needs_extraction;
2261
2262         /* Build the list of the streams that need to be extracted and
2263          * initialize ctx.progress.extract with stream information.  */
2264         ret = for_dentry_in_tree(ctx.extract_root,
2265                                  dentry_resolve_and_zero_lte_refcnt, &ctx);
2266         if (ret)
2267                 goto out_dentry_reset_needs_extraction;
2268
2269         ret = for_dentry_in_tree(ctx.extract_root,
2270                                  dentry_add_streams_to_extract, &ctx);
2271         if (ret)
2272                 goto out_teardown_stream_list;
2273
2274         if (extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE) {
2275                 /* When extracting from a pipe, the number of bytes of data to
2276                  * extract can't be determined in the normal way (examining the
2277                  * lookup table), since at this point all we have is a set of
2278                  * SHA1 message digests of streams that need to be extracted.
2279                  * However, we can get a reasonably accurate estimate by taking
2280                  * <TOTALBYTES> from the corresponding <IMAGE> in the WIM XML
2281                  * data.  This does assume that a full image is being extracted,
2282                  * but currently there is no API for doing otherwise.  (Also,
2283                  * subtract <HARDLINKBYTES> from this if hard links are
2284                  * supported by the extraction mode.)  */
2285                 ctx.progress.extract.total_bytes =
2286                         wim_info_get_image_total_bytes(wim->wim_info,
2287                                                        wim->current_image);
2288                 if (ctx.supported_features.hard_links) {
2289                         ctx.progress.extract.total_bytes -=
2290                                 wim_info_get_image_hard_link_bytes(wim->wim_info,
2291                                                                    wim->current_image);
2292                 }
2293         }
2294
2295         /* Handle the special case of extracting a file to standard
2296          * output.  In that case, "root" should be a single file, not a
2297          * directory tree.  (If not, extract_dentry_to_stdout() will
2298          * return an error.)  */
2299         if (extract_flags & WIMLIB_EXTRACT_FLAG_TO_STDOUT) {
2300                 ret = 0;
2301                 for (size_t i = 0; i < num_trees; i++) {
2302                         ret = extract_dentry_to_stdout(trees[i]);
2303                         if (ret)
2304                                 break;
2305                 }
2306                 goto out_teardown_stream_list;
2307         }
2308
2309         if (ctx.ops->realpath_works_on_nonexisting_files &&
2310             ((extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX) ||
2311              ctx.ops->requires_realtarget_in_paths))
2312         {
2313                 ctx.realtarget = realpath(target, NULL);
2314                 if (!ctx.realtarget) {
2315                         ret = WIMLIB_ERR_NOMEM;
2316                         goto out_teardown_stream_list;
2317                 }
2318                 ctx.realtarget_nchars = tstrlen(ctx.realtarget);
2319         }
2320
2321         if (progress_func) {
2322                 int msg;
2323                 if (extract_flags & WIMLIB_EXTRACT_FLAG_IMAGEMODE)
2324                         msg = WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN;
2325                 else
2326                         msg = WIMLIB_PROGRESS_MSG_EXTRACT_TREE_BEGIN;
2327                 progress_func(msg, &ctx.progress);
2328         }
2329
2330         if (!ctx.root_dentry_is_special)
2331         {
2332                 tchar path[ctx.ops->path_max];
2333                 if (build_extraction_path(path, ctx.extract_root, &ctx))
2334                 {
2335                         ret = extract_inode(path, &ctx, ctx.extract_root->d_inode);
2336                         if (ret)
2337                                 goto out_free_realtarget;
2338                 }
2339         }
2340
2341         /* If we need to fix up the targets of absolute symbolic links
2342          * (WIMLIB_EXTRACT_FLAG_RPFIX) or the extraction mode requires paths to
2343          * be absolute, use realpath() (or its replacement on Windows) to get
2344          * the absolute path to the extraction target.  Note that this requires
2345          * the target directory to exist, unless
2346          * realpath_works_on_nonexisting_files is set in the apply_operations.
2347          * */
2348         if (!ctx.realtarget &&
2349             (((extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX) &&
2350               required_features.symlink_reparse_points) ||
2351              ctx.ops->requires_realtarget_in_paths))
2352         {
2353                 ctx.realtarget = realpath(target, NULL);
2354                 if (!ctx.realtarget) {
2355                         ret = WIMLIB_ERR_NOMEM;
2356                         goto out_free_realtarget;
2357                 }
2358                 ctx.realtarget_nchars = tstrlen(ctx.realtarget);
2359         }
2360
2361         if (ctx.ops->requires_short_name_reordering) {
2362                 ret = for_dentry_in_tree(ctx.extract_root, dentry_extract_dir_skeleton,
2363                                          &ctx);
2364                 if (ret)
2365                         goto out_free_realtarget;
2366         }
2367
2368         /* Finally, the important part: extract the tree of files.  */
2369         if (!(extract_flags & WIMLIB_EXTRACT_FLAG_FILE_ORDER)) {
2370                 /* Sequential extraction requested, so two passes are needed
2371                  * (one for directory structure, one for streams.)  */
2372                 if (progress_func)
2373                         progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN,
2374                                       &ctx.progress);
2375
2376                 if (!(extract_flags & WIMLIB_EXTRACT_FLAG_RESUME)) {
2377                         ret = for_dentry_in_tree(ctx.extract_root, dentry_extract_skeleton, &ctx);
2378                         if (ret)
2379                                 goto out_free_realtarget;
2380                 }
2381                 if (progress_func)
2382                         progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_END,
2383                                       &ctx.progress);
2384                 if (extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE)
2385                         ret = extract_streams_from_pipe(&ctx);
2386                 else
2387                         ret = extract_stream_list(&ctx);
2388                 if (ret)
2389                         goto out_free_realtarget;
2390         } else {
2391                 /* Sequential extraction was not requested, so we can make do
2392                  * with one pass where we both create the files and extract
2393                  * streams.   */
2394                 if (progress_func)
2395                         progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN,
2396                                       &ctx.progress);
2397                 ret = for_dentry_in_tree(ctx.extract_root, dentry_extract, &ctx);
2398                 if (ret)
2399                         goto out_free_realtarget;
2400                 if (progress_func)
2401                         progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_END,
2402                                       &ctx.progress);
2403         }
2404
2405         /* If the total number of bytes to extract was miscalculated, just jump
2406          * to the calculated number in order to avoid confusing the progress
2407          * function.  This should only occur when extracting from a pipe.  */
2408         if (ctx.progress.extract.completed_bytes != ctx.progress.extract.total_bytes)
2409         {
2410                 DEBUG("Calculated %"PRIu64" bytes to extract, but actually "
2411                       "extracted %"PRIu64,
2412                       ctx.progress.extract.total_bytes,
2413                       ctx.progress.extract.completed_bytes);
2414         }
2415         if (progress_func &&
2416             ctx.progress.extract.completed_bytes < ctx.progress.extract.total_bytes)
2417         {
2418                 ctx.progress.extract.completed_bytes = ctx.progress.extract.total_bytes;
2419                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS, &ctx.progress);
2420         }
2421
2422         /* Apply security descriptors and timestamps.  This is done at the end,
2423          * and in a depth-first manner, to prevent timestamps from getting
2424          * changed by subsequent extract operations and to minimize the chance
2425          * of the restored security descriptors getting in our way.  */
2426         if (progress_func)
2427                 progress_func(WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS,
2428                               &ctx.progress);
2429         ret = for_dentry_in_tree_depth(ctx.extract_root, dentry_extract_final, &ctx);
2430         if (ret)
2431                 goto out_free_realtarget;
2432
2433         if (progress_func) {
2434                 int msg;
2435                 if (extract_flags & WIMLIB_EXTRACT_FLAG_IMAGEMODE)
2436                         msg = WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END;
2437                 else
2438                         msg = WIMLIB_PROGRESS_MSG_EXTRACT_TREE_END;
2439                 progress_func(msg, &ctx.progress);
2440         }
2441
2442         do_extract_warnings(&ctx);
2443
2444         ret = 0;
2445 out_free_realtarget:
2446         FREE(ctx.realtarget);
2447 out_teardown_stream_list:
2448         /* Free memory allocated as part of the mapping from each
2449          * wim_lookup_table_entry to the dentries that reference it.  */
2450         if (!(ctx.extract_flags & WIMLIB_EXTRACT_FLAG_FILE_ORDER))
2451                 list_for_each_entry(lte, &ctx.stream_list, extraction_list)
2452                         if (lte->out_refcnt > ARRAY_LEN(lte->inline_lte_dentries))
2453                                 FREE(lte->lte_dentries);
2454 out_finish_or_abort_extract:
2455         if (ret) {
2456                 if (ctx.ops->abort_extract)
2457                         ctx.ops->abort_extract(&ctx);
2458         } else {
2459                 if (ctx.ops->finish_extract)
2460                         ret = ctx.ops->finish_extract(&ctx);
2461         }
2462 out_dentry_reset_needs_extraction:
2463         for_dentry_in_tree(ctx.extract_root, dentry_reset_needs_extraction, NULL);
2464         return ret;
2465 }
2466
2467 /* Make sure the extraction flags make sense, and update them if needed.  */
2468 static int
2469 check_extract_flags(const WIMStruct *wim, int *extract_flags_p)
2470 {
2471         int extract_flags = *extract_flags_p;
2472
2473         /* Check for invalid flag combinations  */
2474         if ((extract_flags &
2475              (WIMLIB_EXTRACT_FLAG_SYMLINK |
2476               WIMLIB_EXTRACT_FLAG_HARDLINK)) == (WIMLIB_EXTRACT_FLAG_SYMLINK |
2477                                                  WIMLIB_EXTRACT_FLAG_HARDLINK))
2478                 return WIMLIB_ERR_INVALID_PARAM;
2479
2480         if ((extract_flags &
2481              (WIMLIB_EXTRACT_FLAG_NO_ACLS |
2482               WIMLIB_EXTRACT_FLAG_STRICT_ACLS)) == (WIMLIB_EXTRACT_FLAG_NO_ACLS |
2483                                                     WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2484                 return WIMLIB_ERR_INVALID_PARAM;
2485
2486         if ((extract_flags &
2487              (WIMLIB_EXTRACT_FLAG_RPFIX |
2488               WIMLIB_EXTRACT_FLAG_NORPFIX)) == (WIMLIB_EXTRACT_FLAG_RPFIX |
2489                                                 WIMLIB_EXTRACT_FLAG_NORPFIX))
2490                 return WIMLIB_ERR_INVALID_PARAM;
2491
2492         if ((extract_flags &
2493              (WIMLIB_EXTRACT_FLAG_RESUME |
2494               WIMLIB_EXTRACT_FLAG_FROM_PIPE)) == WIMLIB_EXTRACT_FLAG_RESUME)
2495                 return WIMLIB_ERR_INVALID_PARAM;
2496
2497 #ifndef WITH_NTFS_3G
2498         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
2499                 ERROR("wimlib was compiled without support for NTFS-3g, so\n"
2500                       "        we cannot apply a WIM image directly to a NTFS volume.");
2501                 return WIMLIB_ERR_UNSUPPORTED;
2502         }
2503 #endif
2504
2505         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_RPFIX |
2506                               WIMLIB_EXTRACT_FLAG_NORPFIX |
2507                               WIMLIB_EXTRACT_FLAG_IMAGEMODE)) ==
2508                                         WIMLIB_EXTRACT_FLAG_IMAGEMODE)
2509         {
2510                 /* Do reparse point fixups by default if the WIM header says
2511                  * they are enabled.  */
2512                 if (wim->hdr.flags & WIM_HDR_FLAG_RP_FIX)
2513                         extract_flags |= WIMLIB_EXTRACT_FLAG_RPFIX;
2514         }
2515
2516         /* TODO: Since UNIX data entries are stored in the file resources, in a
2517          * completely sequential extraction they may come up before the
2518          * corresponding file or symbolic link data.  This needs to be handled
2519          * better.  */
2520         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_UNIX_DATA |
2521                               WIMLIB_EXTRACT_FLAG_FILE_ORDER))
2522                                     == WIMLIB_EXTRACT_FLAG_UNIX_DATA)
2523         {
2524                 if (extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE) {
2525                         WARNING("Setting UNIX file/owner group may "
2526                                 "be impossible on some\n"
2527                                 "          symbolic links "
2528                                 "when applying from a pipe.");
2529                 } else {
2530                         extract_flags |= WIMLIB_EXTRACT_FLAG_FILE_ORDER;
2531                         WARNING("Disabling sequential extraction for "
2532                                 "UNIX data mode");
2533                 }
2534         }
2535
2536         *extract_flags_p = extract_flags;
2537         return 0;
2538 }
2539
2540 static u32
2541 get_wildcard_flags(int extract_flags)
2542 {
2543         u32 wildcard_flags = 0;
2544
2545         if (extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_GLOB)
2546                 wildcard_flags |= WILDCARD_FLAG_ERROR_IF_NO_MATCH;
2547         else
2548                 wildcard_flags |= WILDCARD_FLAG_WARN_IF_NO_MATCH;
2549
2550         if (default_ignore_case)
2551                 wildcard_flags |= WILDCARD_FLAG_CASE_INSENSITIVE;
2552
2553         return wildcard_flags;
2554 }
2555
2556 struct append_dentry_ctx {
2557         struct wim_dentry **dentries;
2558         size_t num_dentries;
2559         size_t num_alloc_dentries;
2560 };
2561
2562 static int
2563 append_dentry_cb(struct wim_dentry *dentry, void *_ctx)
2564 {
2565         struct append_dentry_ctx *ctx = _ctx;
2566
2567         if (ctx->num_dentries == ctx->num_alloc_dentries) {
2568                 struct wim_dentry **new_dentries;
2569                 size_t new_length;
2570
2571                 new_length = max(ctx->num_alloc_dentries + 8,
2572                                  ctx->num_alloc_dentries * 3 / 2);
2573                 new_dentries = REALLOC(ctx->dentries,
2574                                        new_length * sizeof(ctx->dentries[0]));
2575                 if (new_dentries == NULL)
2576                         return WIMLIB_ERR_NOMEM;
2577                 ctx->dentries = new_dentries;
2578                 ctx->num_alloc_dentries = new_length;
2579         }
2580         ctx->dentries[ctx->num_dentries++] = dentry;
2581         return 0;
2582 }
2583
2584 static int
2585 do_wimlib_extract_paths(WIMStruct *wim,
2586                         int image,
2587                         const tchar *target,
2588                         const tchar * const *paths,
2589                         size_t num_paths,
2590                         int extract_flags,
2591                         wimlib_progress_func_t progress_func)
2592 {
2593         int ret;
2594         struct wim_dentry **trees;
2595         size_t num_trees;
2596
2597         if (wim == NULL || target == NULL || target[0] == T('\0') ||
2598             (num_paths != 0 && paths == NULL))
2599                 return WIMLIB_ERR_INVALID_PARAM;
2600
2601         ret = check_extract_flags(wim, &extract_flags);
2602         if (ret)
2603                 return ret;
2604
2605         ret = select_wim_image(wim, image);
2606         if (ret)
2607                 return ret;
2608
2609         ret = wim_checksum_unhashed_streams(wim);
2610         if (ret)
2611                 return ret;
2612
2613         if (extract_flags & WIMLIB_EXTRACT_FLAG_GLOB_PATHS) {
2614
2615                 struct append_dentry_ctx append_dentry_ctx = {
2616                         .dentries = NULL,
2617                         .num_dentries = 0,
2618                         .num_alloc_dentries = 0,
2619                 };
2620
2621                 u32 wildcard_flags = get_wildcard_flags(extract_flags);
2622
2623                 for (size_t i = 0; i < num_paths; i++) {
2624                         tchar *path = canonicalize_wim_path(paths[i]);
2625                         if (path == NULL) {
2626                                 ret = WIMLIB_ERR_NOMEM;
2627                                 trees = append_dentry_ctx.dentries;
2628                                 goto out_free_trees;
2629                         }
2630                         ret = expand_wildcard(wim, path,
2631                                               append_dentry_cb,
2632                                               &append_dentry_ctx,
2633                                               wildcard_flags);
2634                         FREE(path);
2635                         if (ret) {
2636                                 trees = append_dentry_ctx.dentries;
2637                                 goto out_free_trees;
2638                         }
2639                 }
2640                 trees = append_dentry_ctx.dentries;
2641                 num_trees = append_dentry_ctx.num_dentries;
2642         } else {
2643                 trees = MALLOC(num_paths * sizeof(trees[0]));
2644                 if (trees == NULL)
2645                         return WIMLIB_ERR_NOMEM;
2646
2647                 for (size_t i = 0; i < num_paths; i++) {
2648
2649                         tchar *path = canonicalize_wim_path(paths[i]);
2650                         if (path == NULL) {
2651                                 ret = WIMLIB_ERR_NOMEM;
2652                                 goto out_free_trees;
2653                         }
2654
2655                         trees[i] = get_dentry(wim, path,
2656                                               WIMLIB_CASE_PLATFORM_DEFAULT);
2657                         FREE(path);
2658                         if (trees[i] == NULL) {
2659                                   ERROR("Path \"%"TS"\" does not exist "
2660                                         "in WIM image %d",
2661                                         paths[i], wim->current_image);
2662                                   ret = WIMLIB_ERR_PATH_DOES_NOT_EXIST;
2663                                   goto out_free_trees;
2664                         }
2665                 }
2666                 num_trees = num_paths;
2667         }
2668
2669         if (num_trees == 0) {
2670                 ret = 0;
2671                 goto out_free_trees;
2672         }
2673
2674         ret = extract_trees(wim, trees, num_trees,
2675                             target, extract_flags, progress_func);
2676 out_free_trees:
2677         FREE(trees);
2678         return ret;
2679 }
2680
2681 static int
2682 extract_single_image(WIMStruct *wim, int image,
2683                      const tchar *target, int extract_flags,
2684                      wimlib_progress_func_t progress_func)
2685 {
2686         const tchar *path = T("");
2687         return do_wimlib_extract_paths(wim, image, target, &path, 1,
2688                                        extract_flags | WIMLIB_EXTRACT_FLAG_IMAGEMODE,
2689                                        progress_func);
2690 }
2691
2692 static const tchar * const filename_forbidden_chars =
2693 T(
2694 #ifdef __WIN32__
2695 "<>:\"/\\|?*"
2696 #else
2697 "/"
2698 #endif
2699 );
2700
2701 /* This function checks if it is okay to use a WIM image's name as a directory
2702  * name.  */
2703 static bool
2704 image_name_ok_as_dir(const tchar *image_name)
2705 {
2706         return image_name && *image_name &&
2707                 !tstrpbrk(image_name, filename_forbidden_chars) &&
2708                 tstrcmp(image_name, T(".")) &&
2709                 tstrcmp(image_name, T(".."));
2710 }
2711
2712 /* Extracts all images from the WIM to the directory @target, with the images
2713  * placed in subdirectories named by their image names. */
2714 static int
2715 extract_all_images(WIMStruct *wim,
2716                    const tchar *target,
2717                    int extract_flags,
2718                    wimlib_progress_func_t progress_func)
2719 {
2720         size_t image_name_max_len = max(xml_get_max_image_name_len(wim), 20);
2721         size_t output_path_len = tstrlen(target);
2722         tchar buf[output_path_len + 1 + image_name_max_len + 1];
2723         int ret;
2724         int image;
2725         const tchar *image_name;
2726         struct stat stbuf;
2727
2728         extract_flags |= WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
2729
2730         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
2731                 ERROR("Cannot extract multiple images in NTFS extraction mode.");
2732                 return WIMLIB_ERR_INVALID_PARAM;
2733         }
2734
2735         if (tstat(target, &stbuf)) {
2736                 if (errno == ENOENT) {
2737                         if (tmkdir(target, 0755)) {
2738                                 ERROR_WITH_ERRNO("Failed to create directory \"%"TS"\"", target);
2739                                 return WIMLIB_ERR_MKDIR;
2740                         }
2741                 } else {
2742                         ERROR_WITH_ERRNO("Failed to stat \"%"TS"\"", target);
2743                         return WIMLIB_ERR_STAT;
2744                 }
2745         } else if (!S_ISDIR(stbuf.st_mode)) {
2746                 ERROR("\"%"TS"\" is not a directory", target);
2747                 return WIMLIB_ERR_NOTDIR;
2748         }
2749
2750         tmemcpy(buf, target, output_path_len);
2751         buf[output_path_len] = OS_PREFERRED_PATH_SEPARATOR;
2752         for (image = 1; image <= wim->hdr.image_count; image++) {
2753                 image_name = wimlib_get_image_name(wim, image);
2754                 if (image_name_ok_as_dir(image_name)) {
2755                         tstrcpy(buf + output_path_len + 1, image_name);
2756                 } else {
2757                         /* Image name is empty or contains forbidden characters.
2758                          * Use image number instead. */
2759                         tsprintf(buf + output_path_len + 1, T("%d"), image);
2760                 }
2761                 ret = extract_single_image(wim, image, buf, extract_flags,
2762                                            progress_func);
2763                 if (ret)
2764                         return ret;
2765         }
2766         return 0;
2767 }
2768
2769 static void
2770 clear_lte_extracted_file(WIMStruct *wim, int extract_flags)
2771 {
2772         if (unlikely(extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
2773                                       WIMLIB_EXTRACT_FLAG_HARDLINK)))
2774                 for_lookup_table_entry(wim->lookup_table,
2775                                        lte_free_extracted_file, NULL);
2776 }
2777
2778 static int
2779 do_wimlib_extract_image(WIMStruct *wim,
2780                         int image,
2781                         const tchar *target,
2782                         int extract_flags,
2783                         wimlib_progress_func_t progress_func)
2784 {
2785         int ret;
2786
2787         if (extract_flags & (WIMLIB_EXTRACT_FLAG_NO_PRESERVE_DIR_STRUCTURE |
2788                              WIMLIB_EXTRACT_FLAG_TO_STDOUT |
2789                              WIMLIB_EXTRACT_FLAG_GLOB_PATHS))
2790                 return WIMLIB_ERR_INVALID_PARAM;
2791
2792         if (image == WIMLIB_ALL_IMAGES)
2793                 ret = extract_all_images(wim, target, extract_flags,
2794                                          progress_func);
2795         else
2796                 ret = extract_single_image(wim, image, target, extract_flags,
2797                                            progress_func);
2798
2799         clear_lte_extracted_file(wim, extract_flags);
2800         return ret;
2801 }
2802
2803
2804 /****************************************************************************
2805  *                          Extraction API                                  *
2806  ****************************************************************************/
2807
2808 /* Note: new code should use wimlib_extract_paths() instead of
2809  * wimlib_extract_files() if possible.  */
2810 WIMLIBAPI int
2811 wimlib_extract_files(WIMStruct *wim,
2812                      int image,
2813                      const struct wimlib_extract_command *cmds,
2814                      size_t num_cmds,
2815                      int default_extract_flags,
2816                      wimlib_progress_func_t progress_func)
2817 {
2818         int all_flags = 0;
2819         int link_flags;
2820         int ret;
2821
2822         if (num_cmds == 0)
2823                 return 0;
2824
2825         default_extract_flags |= WIMLIB_EXTRACT_FLAG_NO_PRESERVE_DIR_STRUCTURE;
2826
2827         for (size_t i = 0; i < num_cmds; i++) {
2828                 int cmd_flags = (cmds[i].extract_flags |
2829                                  default_extract_flags);
2830
2831                 if (cmd_flags & ~WIMLIB_EXTRACT_MASK_PUBLIC)
2832                         return WIMLIB_ERR_INVALID_PARAM;
2833
2834                 int cmd_link_flags = (cmd_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
2835                                                    WIMLIB_EXTRACT_FLAG_HARDLINK));
2836                 if (i == 0) {
2837                         link_flags = cmd_link_flags;
2838                 } else {
2839                         if (cmd_link_flags != link_flags) {
2840                                 ERROR("The same symlink or hardlink extraction mode "
2841                                       "must be set on all extraction commands!");
2842                                 return WIMLIB_ERR_INVALID_PARAM;
2843                         }
2844                 }
2845                 all_flags |= cmd_flags;
2846         }
2847         if (all_flags & WIMLIB_EXTRACT_FLAG_GLOB_PATHS) {
2848                 ERROR("Glob paths not supported for wimlib_extract_files(). "
2849                       "Use wimlib_extract_paths() instead.");
2850                 return WIMLIB_ERR_INVALID_PARAM;
2851         }
2852
2853         for (size_t i = 0; i < num_cmds; i++) {
2854                 int extract_flags = (cmds[i].extract_flags |
2855                                      default_extract_flags);
2856                 const tchar *target = cmds[i].fs_dest_path;
2857                 const tchar *wim_source_path = cmds[i].wim_source_path;
2858
2859                 ret = do_wimlib_extract_paths(wim, image, target,
2860                                               &wim_source_path, 1,
2861                                               extract_flags | WIMLIB_EXTRACT_FLAG_FILEMODE,
2862                                               progress_func);
2863                 if (ret)
2864                         break;
2865         }
2866
2867         clear_lte_extracted_file(wim, all_flags);
2868         return ret;
2869 }
2870
2871 WIMLIBAPI int
2872 wimlib_extract_paths(WIMStruct *wim,
2873                      int image,
2874                      const tchar *target,
2875                      const tchar * const *paths,
2876                      size_t num_paths,
2877                      int extract_flags,
2878                      wimlib_progress_func_t progress_func)
2879 {
2880         int ret;
2881
2882         if (extract_flags & ~WIMLIB_EXTRACT_MASK_PUBLIC)
2883                 return WIMLIB_ERR_INVALID_PARAM;
2884
2885         ret = do_wimlib_extract_paths(wim, image, target, paths, num_paths,
2886                                       extract_flags, progress_func);
2887         clear_lte_extracted_file(wim, extract_flags);
2888         return ret;
2889 }
2890
2891 WIMLIBAPI int
2892 wimlib_extract_pathlist(WIMStruct *wim, int image,
2893                         const tchar *target,
2894                         const tchar *path_list_file,
2895                         int extract_flags,
2896                         wimlib_progress_func_t progress_func)
2897 {
2898         int ret;
2899         tchar **paths;
2900         size_t num_paths;
2901         void *mem;
2902
2903         ret = read_path_list_file(path_list_file, &paths, &num_paths, &mem);
2904         if (ret) {
2905                 ERROR("Failed to read path list file \"%"TS"\"",
2906                       path_list_file);
2907                 return ret;
2908         }
2909
2910         ret = wimlib_extract_paths(wim, image, target,
2911                                    (const tchar * const *)paths, num_paths,
2912                                    extract_flags, progress_func);
2913         FREE(paths);
2914         FREE(mem);
2915         return ret;
2916 }
2917
2918 WIMLIBAPI int
2919 wimlib_extract_image_from_pipe(int pipe_fd, const tchar *image_num_or_name,
2920                                const tchar *target, int extract_flags,
2921                                wimlib_progress_func_t progress_func)
2922 {
2923         int ret;
2924         WIMStruct *pwm;
2925         struct filedes *in_fd;
2926         int image;
2927         unsigned i;
2928
2929         if (extract_flags & ~WIMLIB_EXTRACT_MASK_PUBLIC)
2930                 return WIMLIB_ERR_INVALID_PARAM;
2931
2932         if (extract_flags & WIMLIB_EXTRACT_FLAG_FILE_ORDER)
2933                 return WIMLIB_ERR_INVALID_PARAM;
2934
2935         /* Read the WIM header from the pipe and get a WIMStruct to represent
2936          * the pipable WIM.  Caveats:  Unlike getting a WIMStruct with
2937          * wimlib_open_wim(), getting a WIMStruct in this way will result in
2938          * an empty lookup table, no XML data read, and no filename set.  */
2939         ret = open_wim_as_WIMStruct(&pipe_fd,
2940                                     WIMLIB_OPEN_FLAG_FROM_PIPE,
2941                                     &pwm, progress_func);
2942         if (ret)
2943                 return ret;
2944
2945         /* Sanity check to make sure this is a pipable WIM.  */
2946         if (pwm->hdr.magic != PWM_MAGIC) {
2947                 ERROR("The WIM being read from file descriptor %d "
2948                       "is not pipable!", pipe_fd);
2949                 ret = WIMLIB_ERR_NOT_PIPABLE;
2950                 goto out_wimlib_free;
2951         }
2952
2953         /* Sanity check to make sure the first part of a pipable split WIM is
2954          * sent over the pipe first.  */
2955         if (pwm->hdr.part_number != 1) {
2956                 ERROR("The first part of the split WIM must be "
2957                       "sent over the pipe first.");
2958                 ret = WIMLIB_ERR_INVALID_PIPABLE_WIM;
2959                 goto out_wimlib_free;
2960         }
2961
2962         in_fd = &pwm->in_fd;
2963         wimlib_assert(in_fd->offset == WIM_HEADER_DISK_SIZE);
2964
2965         /* As mentioned, the WIMStruct we created from the pipe does not have
2966          * XML data yet.  Fix this by reading the extra copy of the XML data
2967          * that directly follows the header in pipable WIMs.  (Note: see
2968          * write_pipable_wim() for more details about the format of pipable
2969          * WIMs.)  */
2970         {
2971                 struct wim_lookup_table_entry xml_lte;
2972                 struct wim_resource_spec xml_rspec;
2973                 ret = read_pwm_stream_header(pwm, &xml_lte, &xml_rspec, 0, NULL);
2974                 if (ret)
2975                         goto out_wimlib_free;
2976
2977                 if (!(xml_lte.flags & WIM_RESHDR_FLAG_METADATA))
2978                 {
2979                         ERROR("Expected XML data, but found non-metadata "
2980                               "stream.");
2981                         ret = WIMLIB_ERR_INVALID_PIPABLE_WIM;
2982                         goto out_wimlib_free;
2983                 }
2984
2985                 wim_res_spec_to_hdr(&xml_rspec, &pwm->hdr.xml_data_reshdr);
2986
2987                 ret = read_wim_xml_data(pwm);
2988                 if (ret)
2989                         goto out_wimlib_free;
2990
2991                 if (wim_info_get_num_images(pwm->wim_info) != pwm->hdr.image_count) {
2992                         ERROR("Image count in XML data is not the same as in WIM header.");
2993                         ret = WIMLIB_ERR_XML;
2994                         goto out_wimlib_free;
2995                 }
2996         }
2997
2998         /* Get image index (this may use the XML data that was just read to
2999          * resolve an image name).  */
3000         if (image_num_or_name) {
3001                 image = wimlib_resolve_image(pwm, image_num_or_name);
3002                 if (image == WIMLIB_NO_IMAGE) {
3003                         ERROR("\"%"TS"\" is not a valid image in the pipable WIM!",
3004                               image_num_or_name);
3005                         ret = WIMLIB_ERR_INVALID_IMAGE;
3006                         goto out_wimlib_free;
3007                 } else if (image == WIMLIB_ALL_IMAGES) {
3008                         ERROR("Applying all images from a pipe is not supported.");
3009                         ret = WIMLIB_ERR_INVALID_IMAGE;
3010                         goto out_wimlib_free;
3011                 }
3012         } else {
3013                 if (pwm->hdr.image_count != 1) {
3014                         ERROR("No image was specified, but the pipable WIM "
3015                               "did not contain exactly 1 image");
3016                         ret = WIMLIB_ERR_INVALID_IMAGE;
3017                         goto out_wimlib_free;
3018                 }
3019                 image = 1;
3020         }
3021
3022         /* Load the needed metadata resource.  */
3023         for (i = 1; i <= pwm->hdr.image_count; i++) {
3024                 struct wim_lookup_table_entry *metadata_lte;
3025                 struct wim_image_metadata *imd;
3026                 struct wim_resource_spec *metadata_rspec;
3027
3028                 metadata_lte = new_lookup_table_entry();
3029                 if (metadata_lte == NULL) {
3030                         ret = WIMLIB_ERR_NOMEM;
3031                         goto out_wimlib_free;
3032                 }
3033                 metadata_rspec = MALLOC(sizeof(struct wim_resource_spec));
3034                 if (metadata_rspec == NULL) {
3035                         ret = WIMLIB_ERR_NOMEM;
3036                         free_lookup_table_entry(metadata_lte);
3037                         goto out_wimlib_free;
3038                 }
3039
3040                 ret = read_pwm_stream_header(pwm, metadata_lte, metadata_rspec, 0, NULL);
3041                 imd = pwm->image_metadata[i - 1];
3042                 imd->metadata_lte = metadata_lte;
3043                 if (ret) {
3044                         FREE(metadata_rspec);
3045                         goto out_wimlib_free;
3046                 }
3047
3048                 if (!(metadata_lte->flags & WIM_RESHDR_FLAG_METADATA)) {
3049                         ERROR("Expected metadata resource, but found "
3050                               "non-metadata stream.");
3051                         ret = WIMLIB_ERR_INVALID_PIPABLE_WIM;
3052                         goto out_wimlib_free;
3053                 }
3054
3055                 if (i == image) {
3056                         /* Metadata resource is for the images being extracted.
3057                          * Parse it and save the metadata in memory.  */
3058                         ret = read_metadata_resource(pwm, imd);
3059                         if (ret)
3060                                 goto out_wimlib_free;
3061                         imd->modified = 1;
3062                 } else {
3063                         /* Metadata resource is not for the image being
3064                          * extracted.  Skip over it.  */
3065                         ret = skip_wim_stream(metadata_lte);
3066                         if (ret)
3067                                 goto out_wimlib_free;
3068                 }
3069         }
3070         /* Extract the image.  */
3071         extract_flags |= WIMLIB_EXTRACT_FLAG_FROM_PIPE;
3072         ret = do_wimlib_extract_image(pwm, image, target,
3073                                       extract_flags, progress_func);
3074         /* Clean up and return.  */
3075 out_wimlib_free:
3076         wimlib_free(pwm);
3077         return ret;
3078 }
3079
3080 WIMLIBAPI int
3081 wimlib_extract_image(WIMStruct *wim,
3082                      int image,
3083                      const tchar *target,
3084                      int extract_flags,
3085                      wimlib_progress_func_t progress_func)
3086 {
3087         if (extract_flags & ~WIMLIB_EXTRACT_MASK_PUBLIC)
3088                 return WIMLIB_ERR_INVALID_PARAM;
3089         return do_wimlib_extract_image(wim, image, target, extract_flags,
3090                                        progress_func);
3091 }