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