]> wimlib.net Git - wimlib/blob - src/extract.c
e62fa8a890cc27927f9fbe22290db85045d9cb8b
[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, 2014 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_image_from_pipe(), wimlib_extract_paths(), and
30  * wimlib_extract_pathlist().  Internally, all end up calling
31  * do_wimlib_extract_paths() and extract_trees().
32  *
33  * Although wimlib supports multiple extraction modes/backends (NTFS-3g, UNIX,
34  * Win32), this file does not itself have code to extract files or directories
35  * to any specific target; instead, it handles generic functionality and relies
36  * on lower-level callback functions declared in `struct apply_operations' to do
37  * the actual extraction.
38  */
39
40 #ifdef HAVE_CONFIG_H
41 #  include "config.h"
42 #endif
43
44 #include "wimlib/apply.h"
45 #include "wimlib/dentry.h"
46 #include "wimlib/encoding.h"
47 #include "wimlib/endianness.h"
48 #include "wimlib/error.h"
49 #include "wimlib/lookup_table.h"
50 #include "wimlib/metadata.h"
51 #include "wimlib/pathlist.h"
52 #include "wimlib/paths.h"
53 #include "wimlib/reparse.h"
54 #include "wimlib/resource.h"
55 #include "wimlib/security.h"
56 #include "wimlib/unix_data.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_FROM_PIPE   0x80000000
71 #define WIMLIB_EXTRACT_FLAG_IMAGEMODE   0x40000000
72
73 /* Keep in sync with wimlib.h  */
74 #define WIMLIB_EXTRACT_MASK_PUBLIC                              \
75         (WIMLIB_EXTRACT_FLAG_NTFS                       |       \
76          WIMLIB_EXTRACT_FLAG_UNIX_DATA                  |       \
77          WIMLIB_EXTRACT_FLAG_NO_ACLS                    |       \
78          WIMLIB_EXTRACT_FLAG_STRICT_ACLS                |       \
79          WIMLIB_EXTRACT_FLAG_RPFIX                      |       \
80          WIMLIB_EXTRACT_FLAG_NORPFIX                    |       \
81          WIMLIB_EXTRACT_FLAG_TO_STDOUT                  |       \
82          WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES  |       \
83          WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS         |       \
84          WIMLIB_EXTRACT_FLAG_STRICT_TIMESTAMPS          |       \
85          WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES         |       \
86          WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS            |       \
87          WIMLIB_EXTRACT_FLAG_GLOB_PATHS                 |       \
88          WIMLIB_EXTRACT_FLAG_STRICT_GLOB                |       \
89          WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES              |       \
90          WIMLIB_EXTRACT_FLAG_NO_PRESERVE_DIR_STRUCTURE  |       \
91          WIMLIB_EXTRACT_FLAG_WIMBOOT)
92
93 /* Check whether the extraction of a dentry should be skipped completely.  */
94 static bool
95 dentry_is_supported(struct wim_dentry *dentry,
96                     const struct wim_features *supported_features)
97 {
98         struct wim_inode *inode = dentry->d_inode;
99
100         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
101                 return supported_features->reparse_points ||
102                         (inode_is_symlink(inode) &&
103                          supported_features->symlink_reparse_points);
104         }
105         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
106                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
107                         return supported_features->encrypted_directories != 0;
108                 else
109                         return supported_features->encrypted_files != 0;
110         }
111         return true;
112 }
113
114
115 #define PWM_ALLOW_WIM_HDR 0x00001
116
117 /* Read the header from a stream in a pipable WIM.  */
118 static int
119 read_pwm_stream_header(WIMStruct *pwm, struct wim_lookup_table_entry *lte,
120                        struct wim_resource_spec *rspec,
121                        int flags, struct wim_header_disk *hdr_ret)
122 {
123         union {
124                 struct pwm_stream_hdr stream_hdr;
125                 struct wim_header_disk pwm_hdr;
126         } buf;
127         struct wim_reshdr reshdr;
128         int ret;
129
130         ret = full_read(&pwm->in_fd, &buf.stream_hdr, sizeof(buf.stream_hdr));
131         if (ret)
132                 goto read_error;
133
134         if ((flags & PWM_ALLOW_WIM_HDR) &&
135             le64_to_cpu(buf.stream_hdr.magic) == PWM_MAGIC)
136         {
137                 BUILD_BUG_ON(sizeof(buf.pwm_hdr) < sizeof(buf.stream_hdr));
138                 ret = full_read(&pwm->in_fd, &buf.stream_hdr + 1,
139                                 sizeof(buf.pwm_hdr) - sizeof(buf.stream_hdr));
140
141                 if (ret)
142                         goto read_error;
143                 lte->resource_location = RESOURCE_NONEXISTENT;
144                 memcpy(hdr_ret, &buf.pwm_hdr, sizeof(buf.pwm_hdr));
145                 return 0;
146         }
147
148         if (le64_to_cpu(buf.stream_hdr.magic) != PWM_STREAM_MAGIC) {
149                 ERROR("Data read on pipe is invalid (expected stream header).");
150                 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
151         }
152
153         copy_hash(lte->hash, buf.stream_hdr.hash);
154
155         reshdr.size_in_wim = 0;
156         reshdr.flags = le32_to_cpu(buf.stream_hdr.flags);
157         reshdr.offset_in_wim = pwm->in_fd.offset;
158         reshdr.uncompressed_size = le64_to_cpu(buf.stream_hdr.uncompressed_size);
159         wim_res_hdr_to_spec(&reshdr, pwm, rspec);
160         lte_bind_wim_resource_spec(lte, rspec);
161         lte->flags = rspec->flags;
162         lte->size = rspec->uncompressed_size;
163         lte->offset_in_res = 0;
164         return 0;
165
166 read_error:
167         ERROR_WITH_ERRNO("Error reading pipable WIM from pipe");
168         return ret;
169 }
170
171 static int
172 load_streams_from_pipe(struct apply_ctx *ctx,
173                        const struct read_stream_list_callbacks *cbs)
174 {
175         struct wim_lookup_table_entry *found_lte = NULL;
176         struct wim_resource_spec *rspec = NULL;
177         struct wim_lookup_table *lookup_table;
178         int ret;
179
180         ret = WIMLIB_ERR_NOMEM;
181         found_lte = new_lookup_table_entry();
182         if (!found_lte)
183                 goto out;
184
185         rspec = MALLOC(sizeof(struct wim_resource_spec));
186         if (!rspec)
187                 goto out;
188
189         lookup_table = ctx->wim->lookup_table;
190         memcpy(ctx->progress.extract.guid, ctx->wim->hdr.guid, WIM_GUID_LEN);
191         ctx->progress.extract.part_number = ctx->wim->hdr.part_number;
192         ctx->progress.extract.total_parts = ctx->wim->hdr.total_parts;
193         ret = extract_progress(ctx, WIMLIB_PROGRESS_MSG_EXTRACT_SPWM_PART_BEGIN);
194         if (ret)
195                 goto out;
196
197         while (ctx->num_streams_remaining) {
198                 struct wim_header_disk pwm_hdr;
199                 struct wim_lookup_table_entry *needed_lte;
200
201                 if (found_lte->resource_location != RESOURCE_NONEXISTENT)
202                         lte_unbind_wim_resource_spec(found_lte);
203                 ret = read_pwm_stream_header(ctx->wim, found_lte, rspec,
204                                              PWM_ALLOW_WIM_HDR, &pwm_hdr);
205                 if (ret)
206                         goto out;
207
208                 if ((found_lte->resource_location != RESOURCE_NONEXISTENT)
209                     && !(found_lte->flags & WIM_RESHDR_FLAG_METADATA)
210                     && (needed_lte = lookup_stream(lookup_table, found_lte->hash))
211                     && (needed_lte->out_refcnt))
212                 {
213                         needed_lte->offset_in_res = found_lte->offset_in_res;
214                         needed_lte->flags = found_lte->flags;
215                         needed_lte->size = found_lte->size;
216
217                         lte_unbind_wim_resource_spec(found_lte);
218                         lte_bind_wim_resource_spec(needed_lte, rspec);
219
220                         ret = (*cbs->begin_stream)(needed_lte, 0,
221                                                    cbs->begin_stream_ctx);
222                         if (ret) {
223                                 lte_unbind_wim_resource_spec(needed_lte);
224                                 goto out;
225                         }
226
227                         ret = extract_stream(needed_lte, needed_lte->size,
228                                              cbs->consume_chunk,
229                                              cbs->consume_chunk_ctx);
230
231                         ret = (*cbs->end_stream)(needed_lte, ret,
232                                                  cbs->end_stream_ctx);
233                         lte_unbind_wim_resource_spec(needed_lte);
234                         if (ret)
235                                 goto out;
236                         ctx->num_streams_remaining--;
237                 } else if (found_lte->resource_location != RESOURCE_NONEXISTENT) {
238                         ret = skip_wim_stream(found_lte);
239                         if (ret)
240                                 goto out;
241                 } else {
242                         u16 part_number = le16_to_cpu(pwm_hdr.part_number);
243                         u16 total_parts = le16_to_cpu(pwm_hdr.total_parts);
244
245                         if (part_number != ctx->progress.extract.part_number ||
246                             total_parts != ctx->progress.extract.total_parts ||
247                             memcmp(pwm_hdr.guid, ctx->progress.extract.guid,
248                                    WIM_GUID_LEN))
249                         {
250                                 ctx->progress.extract.part_number = part_number;
251                                 ctx->progress.extract.total_parts = total_parts;
252                                 memcpy(ctx->progress.extract.guid,
253                                        pwm_hdr.guid, WIM_GUID_LEN);
254                                 ret = extract_progress(ctx,
255                                                        WIMLIB_PROGRESS_MSG_EXTRACT_SPWM_PART_BEGIN);
256                                 if (ret)
257                                         goto out;
258                         }
259                 }
260         }
261         ret = 0;
262 out:
263         if (found_lte->resource_location != RESOURCE_IN_WIM)
264                 FREE(rspec);
265         free_lookup_table_entry(found_lte);
266         return ret;
267 }
268
269 /* Creates a temporary file opened for writing.  The open file descriptor is
270  * returned in @fd_ret and its name is returned in @name_ret (dynamically
271  * allocated).  */
272 static int
273 create_temporary_file(struct filedes *fd_ret, tchar **name_ret)
274 {
275         tchar *name;
276         int open_flags;
277         int raw_fd;
278
279 retry:
280         name = ttempnam(NULL, T("wimlib"));
281         if (!name) {
282                 ERROR_WITH_ERRNO("Failed to create temporary filename");
283                 return WIMLIB_ERR_NOMEM;
284         }
285
286         open_flags = O_WRONLY | O_CREAT | O_EXCL | O_BINARY;
287 #ifdef __WIN32__
288         open_flags |= _O_SHORT_LIVED;
289 #endif
290         raw_fd = topen(name, open_flags, 0600);
291
292         if (raw_fd < 0) {
293                 if (errno == EEXIST) {
294                         FREE(name);
295                         goto retry;
296                 }
297                 ERROR_WITH_ERRNO("Failed to create temporary file "
298                                  "\"%"TS"\"", name);
299                 FREE(name);
300                 return WIMLIB_ERR_OPEN;
301         }
302
303         filedes_init(fd_ret, raw_fd);
304         *name_ret = name;
305         return 0;
306 }
307
308 static int
309 begin_extract_stream_wrapper(struct wim_lookup_table_entry *lte,
310                              u32 flags, void *_ctx)
311 {
312         struct apply_ctx *ctx = _ctx;
313
314         ctx->cur_stream = lte;
315
316         if (unlikely(lte->out_refcnt > MAX_OPEN_STREAMS))
317                 return create_temporary_file(&ctx->tmpfile_fd, &ctx->tmpfile_name);
318         else
319                 return (*ctx->saved_cbs->begin_stream)(lte, flags,
320                                                        ctx->saved_cbs->begin_stream_ctx);
321 }
322
323 static int
324 extract_chunk_wrapper(const void *chunk, size_t size, void *_ctx)
325 {
326         struct apply_ctx *ctx = _ctx;
327         union wimlib_progress_info *progress = &ctx->progress;
328         int ret;
329
330         if (likely(ctx->supported_features.hard_links)) {
331                 progress->extract.completed_bytes +=
332                         (u64)size * ctx->cur_stream->out_refcnt;
333         } else {
334                 const struct stream_owner *owners = stream_owners(ctx->cur_stream);
335                 for (u32 i = 0; i < ctx->cur_stream->out_refcnt; i++) {
336                         const struct wim_inode *inode = owners[i].inode;
337                         const struct wim_dentry *dentry;
338
339                         list_for_each_entry(dentry,
340                                             &inode->i_extraction_aliases,
341                                             d_extraction_alias_node)
342                         {
343                                 progress->extract.completed_bytes += size;
344                         }
345                 }
346         }
347         if (progress->extract.completed_bytes >= ctx->next_progress) {
348
349                 ret = extract_progress(ctx, WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS);
350                 if (ret)
351                         return ret;
352
353                 if (progress->extract.completed_bytes >=
354                     progress->extract.total_bytes)
355                 {
356                         ctx->next_progress = UINT64_MAX;
357                 } else {
358                         /* Send new message as soon as another 1/128 of the
359                          * total has been extracted.  (Arbitrary number.)  */
360                         ctx->next_progress =
361                                 progress->extract.completed_bytes +
362                                         progress->extract.total_bytes / 128;
363
364                         /* ... Unless that would be more than 5000000 bytes, in
365                          * which case send the next after the next 5000000
366                          * bytes.  (Another arbitrary number.)  */
367                         if (progress->extract.completed_bytes + 5000000 <
368                             ctx->next_progress)
369                                 ctx->next_progress =
370                                         progress->extract.completed_bytes + 5000000;
371
372                         /* ... But always send a message as soon as we're
373                          * completely done.  */
374                         if (progress->extract.total_bytes < ctx->next_progress)
375                                 ctx->next_progress = progress->extract.total_bytes;
376                 }
377         }
378
379         if (unlikely(filedes_valid(&ctx->tmpfile_fd))) {
380                 /* Just extracting to temporary file for now.  */
381                 ret = full_write(&ctx->tmpfile_fd, chunk, size);
382                 if (ret) {
383                         ERROR_WITH_ERRNO("Error writing data to "
384                                          "temporary file \"%"TS"\"",
385                                          ctx->tmpfile_name);
386                 }
387                 return ret;
388         } else {
389                 return (*ctx->saved_cbs->consume_chunk)(chunk, size,
390                                                         ctx->saved_cbs->consume_chunk_ctx);
391         }
392 }
393
394 static int
395 extract_from_tmpfile(const tchar *tmpfile_name,
396                      struct wim_lookup_table_entry *orig_lte,
397                      struct apply_ctx *ctx)
398 {
399         struct wim_lookup_table_entry tmpfile_lte;
400         const struct stream_owner *owners = stream_owners(orig_lte);
401         int ret;
402
403         /* Copy the stream's data from the temporary file to each of its
404          * destinations.
405          *
406          * This is executed only in the very uncommon case that a
407          * single-instance stream is being extracted to more than
408          * MAX_OPEN_STREAMS locations!  */
409
410         memcpy(&tmpfile_lte, orig_lte, sizeof(struct wim_lookup_table_entry));
411         tmpfile_lte.resource_location = RESOURCE_IN_FILE_ON_DISK;
412         tmpfile_lte.file_on_disk = ctx->tmpfile_name;
413         tmpfile_lte.out_refcnt = 1;
414
415         for (u32 i = 0; i < orig_lte->out_refcnt; i++) {
416                 tmpfile_lte.inline_stream_owners[0] = owners[i];
417                 ret = read_full_stream_with_cbs(&tmpfile_lte, ctx->saved_cbs);
418                 if (ret)
419                         return ret;
420         }
421         return 0;
422 }
423
424 static int
425 end_extract_stream_wrapper(struct wim_lookup_table_entry *stream,
426                            int status, void *_ctx)
427 {
428         struct apply_ctx *ctx = _ctx;
429
430         if (unlikely(filedes_valid(&ctx->tmpfile_fd))) {
431                 filedes_close(&ctx->tmpfile_fd);
432                 if (!status)
433                         status = extract_from_tmpfile(ctx->tmpfile_name,
434                                                       stream, ctx);
435                 filedes_invalidate(&ctx->tmpfile_fd);
436                 tunlink(ctx->tmpfile_name);
437                 FREE(ctx->tmpfile_name);
438                 return status;
439         } else {
440                 return (*ctx->saved_cbs->end_stream)(stream, status,
441                                                      ctx->saved_cbs->end_stream_ctx);
442         }
443 }
444
445 /*
446  * Read the list of single-instance streams to extract and feed their data into
447  * the specified callback functions.
448  *
449  * This handles checksumming each stream.
450  *
451  * This also handles sending WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS.
452  *
453  * This also works if the WIM is being read from a pipe, whereas attempting to
454  * read streams directly (e.g. with read_full_stream_into_buf()) will not.
455  *
456  * This also will split up streams that will need to be extracted to more than
457  * MAX_OPEN_STREAMS locations, as measured by the 'out_refcnt' of each stream.
458  * Therefore, the apply_operations implementation need not worry about running
459  * out of file descriptors, unless it might open more than one file descriptor
460  * per nominal destination (e.g. Win32 currently might because the destination
461  * file system might not support hard links).
462  */
463 int
464 extract_stream_list(struct apply_ctx *ctx,
465                     const struct read_stream_list_callbacks *cbs)
466 {
467         struct read_stream_list_callbacks wrapper_cbs = {
468                 .begin_stream      = begin_extract_stream_wrapper,
469                 .begin_stream_ctx  = ctx,
470                 .consume_chunk     = extract_chunk_wrapper,
471                 .consume_chunk_ctx = ctx,
472                 .end_stream        = end_extract_stream_wrapper,
473                 .end_stream_ctx    = ctx,
474         };
475         ctx->saved_cbs = cbs;
476         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE) {
477                 return load_streams_from_pipe(ctx, &wrapper_cbs);
478         } else {
479                 return read_stream_list(&ctx->stream_list,
480                                         offsetof(struct wim_lookup_table_entry,
481                                                  extraction_list),
482                                         &wrapper_cbs, VERIFY_STREAM_HASHES);
483         }
484 }
485
486 /* Extract a WIM dentry to standard output.
487  *
488  * This obviously doesn't make sense in all cases.  We return an error if the
489  * dentry does not correspond to a regular file.  Otherwise we extract the
490  * unnamed data stream only.  */
491 static int
492 extract_dentry_to_stdout(struct wim_dentry *dentry,
493                          const struct wim_lookup_table *lookup_table)
494 {
495         struct wim_inode *inode = dentry->d_inode;
496         struct wim_lookup_table_entry *lte;
497         struct filedes _stdout;
498
499         if (inode->i_attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
500                                    FILE_ATTRIBUTE_DIRECTORY))
501         {
502                 ERROR("\"%"TS"\" is not a regular file and therefore cannot be "
503                       "extracted to standard output", dentry_full_path(dentry));
504                 return WIMLIB_ERR_NOT_A_REGULAR_FILE;
505         }
506
507         lte = inode_unnamed_lte(inode, lookup_table);
508         if (!lte) {
509                 const u8 *hash = inode_unnamed_stream_hash(inode);
510                 if (!is_zero_hash(hash))
511                         return stream_not_found_error(inode, hash);
512                 return 0;
513         }
514
515         filedes_init(&_stdout, STDOUT_FILENO);
516         return extract_full_stream_to_fd(lte, &_stdout);
517 }
518
519 static int
520 extract_dentries_to_stdout(struct wim_dentry **dentries, size_t num_dentries,
521                            const struct wim_lookup_table *lookup_table)
522 {
523         for (size_t i = 0; i < num_dentries; i++) {
524                 int ret = extract_dentry_to_stdout(dentries[i], lookup_table);
525                 if (ret)
526                         return ret;
527         }
528         return 0;
529 }
530
531 /**********************************************************************/
532
533 /*
534  * Removes duplicate dentries from the array.
535  *
536  * Returns the new number of dentries, packed at the front of the array.
537  */
538 static size_t
539 remove_duplicate_trees(struct wim_dentry **trees, size_t num_trees)
540 {
541         size_t i, j = 0;
542         for (i = 0; i < num_trees; i++) {
543                 if (!trees[i]->tmp_flag) {
544                         /* Found distinct dentry.  */
545                         trees[i]->tmp_flag = 1;
546                         trees[j++] = trees[i];
547                 }
548         }
549         for (i = 0; i < j; i++)
550                 trees[i]->tmp_flag = 0;
551         return j;
552 }
553
554 /*
555  * Remove dentries that are descendants of other dentries in the array.
556  *
557  * Returns the new number of dentries, packed at the front of the array.
558  */
559 static size_t
560 remove_contained_trees(struct wim_dentry **trees, size_t num_trees)
561 {
562         size_t i, j = 0;
563         for (i = 0; i < num_trees; i++)
564                 trees[i]->tmp_flag = 1;
565         for (i = 0; i < num_trees; i++) {
566                 struct wim_dentry *d = trees[i];
567                 while (!dentry_is_root(d)) {
568                         d = d->d_parent;
569                         if (d->tmp_flag)
570                                 goto tree_contained;
571                 }
572                 trees[j++] = trees[i];
573                 continue;
574
575         tree_contained:
576                 trees[i]->tmp_flag = 0;
577         }
578
579         for (i = 0; i < j; i++)
580                 trees[i]->tmp_flag = 0;
581         return j;
582 }
583
584 static int
585 dentry_append_to_list(struct wim_dentry *dentry, void *_dentry_list)
586 {
587         struct list_head *dentry_list = _dentry_list;
588         list_add_tail(&dentry->d_extraction_list_node, dentry_list);
589         return 0;
590 }
591
592 static void
593 dentry_reset_extraction_list_node(struct wim_dentry *dentry)
594 {
595         dentry->d_extraction_list_node = (struct list_head){NULL, NULL};
596 }
597
598 static int
599 dentry_delete_from_list(struct wim_dentry *dentry, void *_ignore)
600 {
601         list_del(&dentry->d_extraction_list_node);
602         dentry_reset_extraction_list_node(dentry);
603         return 0;
604 }
605
606 /*
607  * Build the preliminary list of dentries to be extracted.
608  *
609  * The list maintains the invariant that if d1 and d2 are in the list and d1 is
610  * an ancestor of d2, then d1 appears before d2 in the list.
611  */
612 static void
613 build_dentry_list(struct list_head *dentry_list, struct wim_dentry **trees,
614                   size_t num_trees, bool add_ancestors)
615 {
616         INIT_LIST_HEAD(dentry_list);
617
618         /* Add the trees recursively.  */
619         for (size_t i = 0; i < num_trees; i++)
620                 for_dentry_in_tree(trees[i], dentry_append_to_list, dentry_list);
621
622         /* If requested, add ancestors of the trees.  */
623         if (add_ancestors) {
624                 for (size_t i = 0; i < num_trees; i++) {
625                         struct wim_dentry *dentry = trees[i];
626                         struct wim_dentry *ancestor;
627                         struct list_head *place_after;
628
629                         if (dentry_is_root(dentry))
630                                 continue;
631
632                         place_after = dentry_list;
633                         ancestor = dentry;
634                         do {
635                                 ancestor = ancestor->d_parent;
636                                 if (will_extract_dentry(ancestor)) {
637                                         place_after = &ancestor->d_extraction_list_node;
638                                         break;
639                                 }
640                         } while (!dentry_is_root(ancestor));
641
642                         ancestor = dentry;
643                         do {
644                                 ancestor = ancestor->d_parent;
645                                 if (will_extract_dentry(ancestor))
646                                         break;
647                                 list_add(&ancestor->d_extraction_list_node, place_after);
648                         } while (!dentry_is_root(ancestor));
649                 }
650         }
651 }
652
653 static void
654 destroy_dentry_list(struct list_head *dentry_list)
655 {
656         struct wim_dentry *dentry, *tmp;
657         struct wim_inode *inode;
658
659         list_for_each_entry_safe(dentry, tmp, dentry_list, d_extraction_list_node) {
660                 inode = dentry->d_inode;
661                 dentry_reset_extraction_list_node(dentry);
662                 inode->i_visited = 0;
663                 if ((void *)dentry->d_extraction_name != (void *)dentry->file_name)
664                         FREE(dentry->d_extraction_name);
665                 dentry->d_extraction_name = NULL;
666                 dentry->d_extraction_name_nchars = 0;
667         }
668 }
669
670 static void
671 destroy_stream_list(struct list_head *stream_list)
672 {
673         struct wim_lookup_table_entry *lte;
674
675         list_for_each_entry(lte, stream_list, extraction_list)
676                 if (lte->out_refcnt > ARRAY_LEN(lte->inline_stream_owners))
677                         FREE(lte->stream_owners);
678 }
679
680 #ifdef __WIN32__
681 static const utf16lechar replacement_char = cpu_to_le16(0xfffd);
682 #else
683 static const utf16lechar replacement_char = cpu_to_le16('?');
684 #endif
685
686 static bool
687 file_name_valid(utf16lechar *name, size_t num_chars, bool fix)
688 {
689         size_t i;
690
691         if (num_chars == 0)
692                 return true;
693         for (i = 0; i < num_chars; i++) {
694                 switch (name[i]) {
695         #ifdef __WIN32__
696                 case cpu_to_le16('\\'):
697                 case cpu_to_le16(':'):
698                 case cpu_to_le16('*'):
699                 case cpu_to_le16('?'):
700                 case cpu_to_le16('"'):
701                 case cpu_to_le16('<'):
702                 case cpu_to_le16('>'):
703                 case cpu_to_le16('|'):
704         #endif
705                 case cpu_to_le16('/'):
706                 case cpu_to_le16('\0'):
707                         if (fix)
708                                 name[i] = replacement_char;
709                         else
710                                 return false;
711                 }
712         }
713
714 #ifdef __WIN32__
715         if (name[num_chars - 1] == cpu_to_le16(' ') ||
716             name[num_chars - 1] == cpu_to_le16('.'))
717         {
718                 if (fix)
719                         name[num_chars - 1] = replacement_char;
720                 else
721                         return false;
722         }
723 #endif
724         return true;
725 }
726
727 static int
728 dentry_calculate_extraction_name(struct wim_dentry *dentry,
729                                  struct apply_ctx *ctx)
730 {
731         int ret;
732
733         if (!dentry_is_supported(dentry, &ctx->supported_features))
734                 goto skip_dentry;
735
736         if (dentry_is_root(dentry))
737                 return 0;
738
739 #ifdef WITH_NTFS_3G
740         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
741                 dentry->d_extraction_name = dentry->file_name;
742                 dentry->d_extraction_name_nchars = dentry->file_name_nbytes /
743                                                    sizeof(utf16lechar);
744                 return 0;
745         }
746 #endif
747
748         if (!ctx->supported_features.case_sensitive_filenames) {
749                 struct wim_dentry *other;
750                 list_for_each_entry(other, &dentry->d_ci_conflict_list,
751                                     d_ci_conflict_list)
752                 {
753                         if (will_extract_dentry(other)) {
754                                 if (ctx->extract_flags &
755                                     WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS) {
756                                         WARNING("\"%"TS"\" has the same "
757                                                 "case-insensitive name as "
758                                                 "\"%"TS"\"; extracting "
759                                                 "dummy name instead",
760                                                 dentry_full_path(dentry),
761                                                 dentry_full_path(other));
762                                         goto out_replace;
763                                 } else {
764                                         WARNING("Not extracting \"%"TS"\": "
765                                                 "has same case-insensitive "
766                                                 "name as \"%"TS"\"",
767                                                 dentry_full_path(dentry),
768                                                 dentry_full_path(other));
769                                         goto skip_dentry;
770                                 }
771                         }
772                 }
773         }
774
775         if (file_name_valid(dentry->file_name, dentry->file_name_nbytes / 2, false)) {
776                 ret = utf16le_get_tstr(dentry->file_name,
777                                        dentry->file_name_nbytes,
778                                        (const tchar **)&dentry->d_extraction_name,
779                                        &dentry->d_extraction_name_nchars);
780                 dentry->d_extraction_name_nchars /= sizeof(tchar);
781                 return ret;
782         } else {
783                 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES)
784                 {
785                         WARNING("\"%"TS"\" has an invalid filename "
786                                 "that is not supported on this platform; "
787                                 "extracting dummy name instead",
788                                 dentry_full_path(dentry));
789                         goto out_replace;
790                 } else {
791                         WARNING("Not extracting \"%"TS"\": has an invalid filename "
792                                 "that is not supported on this platform",
793                                 dentry_full_path(dentry));
794                         goto skip_dentry;
795                 }
796         }
797
798 out_replace:
799         {
800                 utf16lechar utf16_name_copy[dentry->file_name_nbytes / 2];
801
802                 memcpy(utf16_name_copy, dentry->file_name, dentry->file_name_nbytes);
803                 file_name_valid(utf16_name_copy, dentry->file_name_nbytes / 2, true);
804
805                 const tchar *tchar_name;
806                 size_t tchar_nchars;
807
808                 ret = utf16le_get_tstr(utf16_name_copy,
809                                        dentry->file_name_nbytes,
810                                        &tchar_name, &tchar_nchars);
811                 if (ret)
812                         return ret;
813
814                 tchar_nchars /= sizeof(tchar);
815
816                 size_t fixed_name_num_chars = tchar_nchars;
817                 tchar fixed_name[tchar_nchars + 50];
818
819                 tmemcpy(fixed_name, tchar_name, tchar_nchars);
820                 fixed_name_num_chars += tsprintf(fixed_name + tchar_nchars,
821                                                  T(" (invalid filename #%lu)"),
822                                                  ++ctx->invalid_sequence);
823
824                 utf16le_put_tstr(tchar_name);
825
826                 dentry->d_extraction_name = memdup(fixed_name,
827                                                    2 * fixed_name_num_chars + 2);
828                 if (!dentry->d_extraction_name)
829                         return WIMLIB_ERR_NOMEM;
830                 dentry->d_extraction_name_nchars = fixed_name_num_chars;
831         }
832         return 0;
833
834 skip_dentry:
835         for_dentry_in_tree(dentry, dentry_delete_from_list, NULL);
836         return 0;
837 }
838
839 /*
840  * Calculate the actual filename component at which each WIM dentry will be
841  * extracted, with special handling for dentries that are unsupported by the
842  * extraction backend or have invalid names.
843  *
844  * ctx->supported_features must be filled in.
845  *
846  * Possible error codes: WIMLIB_ERR_NOMEM, WIMLIB_ERR_INVALID_UTF16_STRING
847  */
848 static int
849 dentry_list_calculate_extraction_names(struct list_head *dentry_list,
850                                        struct apply_ctx *ctx)
851 {
852         struct list_head *prev, *cur;
853
854         /* Can't use list_for_each_entry() because a call to
855          * dentry_calculate_extraction_name() may delete the current dentry and
856          * its children from the list.  */
857
858         prev = dentry_list;
859         for (;;) {
860                 struct wim_dentry *dentry;
861                 int ret;
862
863                 cur = prev->next;
864                 if (cur == dentry_list)
865                         break;
866
867                 dentry = list_entry(cur, struct wim_dentry, d_extraction_list_node);
868
869                 ret = dentry_calculate_extraction_name(dentry, ctx);
870                 if (ret)
871                         return ret;
872
873                 if (prev->next == cur)
874                         prev = cur;
875                 else
876                         ; /* Current dentry and its children (which follow in
877                              the list) were deleted.  prev stays the same.  */
878         }
879         return 0;
880 }
881
882 static int
883 dentry_resolve_streams(struct wim_dentry *dentry, int extract_flags,
884                        struct wim_lookup_table *lookup_table)
885 {
886         struct wim_inode *inode = dentry->d_inode;
887         struct wim_lookup_table_entry *lte;
888         int ret;
889         bool force = false;
890
891         /* Special case:  when extracting from a pipe, the WIM lookup table is
892          * initially empty, so "resolving" an inode's streams is initially not
893          * possible.  However, we still need to keep track of which streams,
894          * identified by SHA1 message digests, need to be extracted, so we
895          * "resolve" the inode's streams anyway by allocating new entries.  */
896         if (extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE)
897                 force = true;
898         ret = inode_resolve_streams(inode, lookup_table, force);
899         if (ret)
900                 return ret;
901         for (u32 i = 0; i <= inode->i_num_ads; i++) {
902                 lte = inode_stream_lte_resolved(inode, i);
903                 if (lte)
904                         lte->out_refcnt = 0;
905         }
906         return 0;
907 }
908
909 /*
910  * For each dentry to be extracted, resolve all streams in the corresponding
911  * inode and set 'out_refcnt' in each to 0.
912  *
913  * Possible error codes: WIMLIB_ERR_RESOURCE_NOT_FOUND, WIMLIB_ERR_NOMEM.
914  */
915 static int
916 dentry_list_resolve_streams(struct list_head *dentry_list,
917                             struct apply_ctx *ctx)
918 {
919         struct wim_dentry *dentry;
920         int ret;
921
922         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
923                 ret = dentry_resolve_streams(dentry,
924                                              ctx->extract_flags,
925                                              ctx->wim->lookup_table);
926                 if (ret)
927                         return ret;
928         }
929         return 0;
930 }
931
932 static int
933 ref_stream(struct wim_lookup_table_entry *lte, u32 stream_idx,
934            struct wim_dentry *dentry, struct apply_ctx *ctx)
935 {
936         struct wim_inode *inode = dentry->d_inode;
937         struct stream_owner *stream_owners;
938
939         if (!lte)
940                 return 0;
941
942         /* Tally the size only for each extraction of the stream (not hard
943          * links).  */
944         if (inode->i_visited && ctx->supported_features.hard_links)
945                 return 0;
946
947         ctx->progress.extract.total_bytes += lte->size;
948         ctx->progress.extract.num_streams++;
949
950         if (inode->i_visited)
951                 return 0;
952
953         /* Add stream to the dentry_list only one time, even if it's going
954          * to be extracted to multiple inodes.  */
955         if (lte->out_refcnt == 0) {
956                 list_add_tail(&lte->extraction_list, &ctx->stream_list);
957                 ctx->num_streams_remaining++;
958         }
959
960         /* If inode not yet been visited, append it to the stream_owners array.  */
961         if (lte->out_refcnt < ARRAY_LEN(lte->inline_stream_owners)) {
962                 stream_owners = lte->inline_stream_owners;
963         } else {
964                 struct stream_owner *prev_stream_owners;
965                 size_t alloc_stream_owners;
966
967                 if (lte->out_refcnt == ARRAY_LEN(lte->inline_stream_owners)) {
968                         prev_stream_owners = NULL;
969                         alloc_stream_owners = ARRAY_LEN(lte->inline_stream_owners);
970                 } else {
971                         prev_stream_owners = lte->stream_owners;
972                         alloc_stream_owners = lte->alloc_stream_owners;
973                 }
974
975                 if (lte->out_refcnt == alloc_stream_owners) {
976                         alloc_stream_owners *= 2;
977                         stream_owners = REALLOC(prev_stream_owners,
978                                                alloc_stream_owners *
979                                                 sizeof(stream_owners[0]));
980                         if (!stream_owners)
981                                 return WIMLIB_ERR_NOMEM;
982                         if (!prev_stream_owners) {
983                                 memcpy(stream_owners,
984                                        lte->inline_stream_owners,
985                                        sizeof(lte->inline_stream_owners));
986                         }
987                         lte->stream_owners = stream_owners;
988                         lte->alloc_stream_owners = alloc_stream_owners;
989                 }
990                 stream_owners = lte->stream_owners;
991         }
992         stream_owners[lte->out_refcnt].inode = inode;
993         if (stream_idx == 0) {
994                 stream_owners[lte->out_refcnt].stream_name = NULL;
995         } else {
996                 stream_owners[lte->out_refcnt].stream_name =
997                         inode->i_ads_entries[stream_idx - 1].stream_name;
998         }
999         lte->out_refcnt++;
1000         return 0;
1001 }
1002
1003 static int
1004 dentry_ref_streams(struct wim_dentry *dentry, struct apply_ctx *ctx)
1005 {
1006         struct wim_inode *inode = dentry->d_inode;
1007         int ret;
1008
1009         /* The unnamed data stream will always be extracted, except in an
1010          * unlikely case.  */
1011         if (!inode_is_encrypted_directory(inode)) {
1012                 u16 stream_idx;
1013                 struct wim_lookup_table_entry *stream;
1014
1015                 stream = inode_unnamed_stream_resolved(inode, &stream_idx);
1016                 ret = ref_stream(stream, stream_idx, dentry, ctx);
1017                 if (ret)
1018                         return ret;
1019         }
1020
1021         /* Named data streams will be extracted only if supported in the current
1022          * extraction mode and volume, and to avoid complications, if not doing
1023          * a linked extraction.  */
1024         if (ctx->supported_features.named_data_streams) {
1025                 for (u16 i = 0; i < inode->i_num_ads; i++) {
1026                         if (!ads_entry_is_named_stream(&inode->i_ads_entries[i]))
1027                                 continue;
1028                         ret = ref_stream(inode->i_ads_entries[i].lte, i + 1,
1029                                          dentry, ctx);
1030                         if (ret)
1031                                 return ret;
1032                 }
1033         }
1034         inode->i_visited = 1;
1035         return 0;
1036 }
1037
1038 /*
1039  * For each dentry to be extracted, iterate through the data streams of the
1040  * corresponding inode.  For each such stream that is not to be ignored due to
1041  * the supported features or extraction flags, add it to the list of streams to
1042  * be extracted (ctx->stream_list) if not already done so.
1043  *
1044  * Also builds a mapping from each stream to the inodes referencing it.
1045  *
1046  * This also initializes the extract progress info with byte and stream
1047  * information.
1048  *
1049  * ctx->supported_features must be filled in.
1050  *
1051  * Possible error codes: WIMLIB_ERR_NOMEM.
1052  */
1053 static int
1054 dentry_list_ref_streams(struct list_head *dentry_list, struct apply_ctx *ctx)
1055 {
1056         struct wim_dentry *dentry;
1057         int ret;
1058
1059         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1060                 ret = dentry_ref_streams(dentry, ctx);
1061                 if (ret)
1062                         return ret;
1063         }
1064         list_for_each_entry(dentry, dentry_list, d_extraction_list_node)
1065                 dentry->d_inode->i_visited = 0;
1066         return 0;
1067 }
1068
1069 static void
1070 dentry_list_build_inode_alias_lists(struct list_head *dentry_list)
1071 {
1072         struct wim_dentry *dentry;
1073         struct wim_inode *inode;
1074
1075         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1076                 inode = dentry->d_inode;
1077                 if (!inode->i_visited)
1078                         INIT_LIST_HEAD(&inode->i_extraction_aliases);
1079                 list_add_tail(&dentry->d_extraction_alias_node,
1080                               &inode->i_extraction_aliases);
1081                 inode->i_visited = 1;
1082         }
1083         list_for_each_entry(dentry, dentry_list, d_extraction_list_node)
1084                 dentry->d_inode->i_visited = 0;
1085 }
1086
1087 static void
1088 inode_tally_features(const struct wim_inode *inode,
1089                      struct wim_features *features)
1090 {
1091         if (inode->i_attributes & FILE_ATTRIBUTE_ARCHIVE)
1092                 features->archive_files++;
1093         if (inode->i_attributes & FILE_ATTRIBUTE_HIDDEN)
1094                 features->hidden_files++;
1095         if (inode->i_attributes & FILE_ATTRIBUTE_SYSTEM)
1096                 features->system_files++;
1097         if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED)
1098                 features->compressed_files++;
1099         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1100                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1101                         features->encrypted_directories++;
1102                 else
1103                         features->encrypted_files++;
1104         }
1105         if (inode->i_attributes & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED)
1106                 features->not_context_indexed_files++;
1107         if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE)
1108                 features->sparse_files++;
1109         if (inode_has_named_stream(inode))
1110                 features->named_data_streams++;
1111         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1112                 features->reparse_points++;
1113                 if (inode_is_symlink(inode))
1114                         features->symlink_reparse_points++;
1115                 else
1116                         features->other_reparse_points++;
1117         }
1118         if (inode->i_security_id != -1)
1119                 features->security_descriptors++;
1120         if (inode_has_unix_data(inode))
1121                 features->unix_data++;
1122 }
1123
1124 /* Tally features necessary to extract a dentry and the corresponding inode.  */
1125 static void
1126 dentry_tally_features(struct wim_dentry *dentry, struct wim_features *features)
1127 {
1128         struct wim_inode *inode = dentry->d_inode;
1129
1130         if (dentry_has_short_name(dentry))
1131                 features->short_names++;
1132
1133         if (inode->i_visited) {
1134                 features->hard_links++;
1135         } else {
1136                 inode_tally_features(inode, features);
1137                 inode->i_visited = 1;
1138         }
1139 }
1140
1141 /* Tally the features necessary to extract the specified dentries.  */
1142 static void
1143 dentry_list_get_features(struct list_head *dentry_list,
1144                          struct wim_features *features)
1145 {
1146         struct wim_dentry *dentry;
1147
1148         list_for_each_entry(dentry, dentry_list, d_extraction_list_node)
1149                 dentry_tally_features(dentry, features);
1150
1151         list_for_each_entry(dentry, dentry_list, d_extraction_list_node)
1152                 dentry->d_inode->i_visited = 0;
1153 }
1154
1155 static int
1156 do_feature_check(const struct wim_features *required_features,
1157                  const struct wim_features *supported_features,
1158                  int extract_flags)
1159 {
1160         /* File attributes.  */
1161         if (!(extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)) {
1162                 /* Note: Don't bother the user about FILE_ATTRIBUTE_ARCHIVE.
1163                  * We're an archive program, so theoretically we can do what we
1164                  * want with it.  */
1165
1166                 if (required_features->hidden_files &&
1167                     !supported_features->hidden_files)
1168                         WARNING("Ignoring FILE_ATTRIBUTE_HIDDEN of %lu files",
1169                                 required_features->hidden_files);
1170
1171                 if (required_features->system_files &&
1172                     !supported_features->system_files)
1173                         WARNING("Ignoring FILE_ATTRIBUTE_SYSTEM of %lu files",
1174                                 required_features->system_files);
1175
1176                 if (required_features->compressed_files &&
1177                     !supported_features->compressed_files)
1178                         WARNING("Ignoring FILE_ATTRIBUTE_COMPRESSED of %lu files",
1179                                 required_features->compressed_files);
1180
1181                 if (required_features->not_context_indexed_files &&
1182                     !supported_features->not_context_indexed_files)
1183                         WARNING("Ignoring FILE_ATTRIBUTE_NOT_CONTENT_INDEXED of %lu files",
1184                                 required_features->not_context_indexed_files);
1185
1186                 if (required_features->sparse_files &&
1187                     !supported_features->sparse_files)
1188                         WARNING("Ignoring FILE_ATTRIBUTE_SPARSE_FILE of %lu files",
1189                                 required_features->sparse_files);
1190
1191                 if (required_features->encrypted_directories &&
1192                     !supported_features->encrypted_directories)
1193                         WARNING("Ignoring FILE_ATTRIBUTE_ENCRYPTED of %lu directories",
1194                                 required_features->encrypted_directories);
1195         }
1196
1197         /* Encrypted files.  */
1198         if (required_features->encrypted_files &&
1199             !supported_features->encrypted_files)
1200                 WARNING("Ignoring %lu encrypted files",
1201                         required_features->encrypted_files);
1202
1203         /* Named data streams.  */
1204         if (required_features->named_data_streams &&
1205             (!supported_features->named_data_streams))
1206                 WARNING("Ignoring named data streams of %lu files",
1207                         required_features->named_data_streams);
1208
1209         /* Hard links.  */
1210         if (required_features->hard_links && !supported_features->hard_links)
1211                 WARNING("Extracting %lu hard links as independent files",
1212                         required_features->hard_links);
1213
1214         /* Symbolic links and reparse points.  */
1215         if ((extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS) &&
1216             required_features->symlink_reparse_points &&
1217             !supported_features->symlink_reparse_points &&
1218             !supported_features->reparse_points)
1219         {
1220                 ERROR("Extraction backend does not support symbolic links!");
1221                 return WIMLIB_ERR_UNSUPPORTED;
1222         }
1223         if (required_features->reparse_points &&
1224             !supported_features->reparse_points)
1225         {
1226                 if (supported_features->symlink_reparse_points) {
1227                         if (required_features->other_reparse_points) {
1228                                 WARNING("Ignoring %lu non-symlink/junction "
1229                                         "reparse point files",
1230                                         required_features->other_reparse_points);
1231                         }
1232                 } else {
1233                         WARNING("Ignoring %lu reparse point files",
1234                                 required_features->reparse_points);
1235                 }
1236         }
1237
1238         /* Security descriptors.  */
1239         if (((extract_flags & (WIMLIB_EXTRACT_FLAG_STRICT_ACLS |
1240                                WIMLIB_EXTRACT_FLAG_UNIX_DATA))
1241              == WIMLIB_EXTRACT_FLAG_STRICT_ACLS) &&
1242             required_features->security_descriptors &&
1243             !supported_features->security_descriptors)
1244         {
1245                 ERROR("Extraction backend does not support security descriptors!");
1246                 return WIMLIB_ERR_UNSUPPORTED;
1247         }
1248         if (!(extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS) &&
1249             required_features->security_descriptors &&
1250             !supported_features->security_descriptors)
1251                 WARNING("Ignoring Windows NT security descriptors of %lu files",
1252                         required_features->security_descriptors);
1253
1254         /* UNIX data.  */
1255         if ((extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) &&
1256             required_features->unix_data && !supported_features->unix_data)
1257         {
1258                 ERROR("Extraction backend does not support UNIX data!");
1259                 return WIMLIB_ERR_UNSUPPORTED;
1260         }
1261
1262         if (required_features->unix_data &&
1263             !(extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA))
1264         {
1265                 WARNING("Ignoring UNIX metadata of %lu files",
1266                         required_features->unix_data);
1267         }
1268
1269         /* DOS Names.  */
1270         if (required_features->short_names &&
1271             !supported_features->short_names)
1272         {
1273                 if (extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES) {
1274                         ERROR("Extraction backend does not support DOS names!");
1275                         return WIMLIB_ERR_UNSUPPORTED;
1276                 }
1277                 WARNING("Ignoring DOS names of %lu files",
1278                         required_features->short_names);
1279         }
1280
1281         /* Timestamps.  */
1282         if ((extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_TIMESTAMPS) &&
1283             !supported_features->timestamps)
1284         {
1285                 ERROR("Extraction backend does not support timestamps!");
1286                 return WIMLIB_ERR_UNSUPPORTED;
1287         }
1288
1289         return 0;
1290 }
1291
1292 static const struct apply_operations *
1293 select_apply_operations(int extract_flags)
1294 {
1295 #ifdef WITH_NTFS_3G
1296         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS)
1297                 return &ntfs_3g_apply_ops;
1298 #endif
1299 #ifdef __WIN32__
1300         return &win32_apply_ops;
1301 #else
1302         return &unix_apply_ops;
1303 #endif
1304 }
1305
1306 static int
1307 extract_trees(WIMStruct *wim, struct wim_dentry **trees, size_t num_trees,
1308               const tchar *target, int extract_flags)
1309 {
1310         const struct apply_operations *ops;
1311         struct apply_ctx *ctx;
1312         int ret;
1313         LIST_HEAD(dentry_list);
1314
1315         if (extract_flags & WIMLIB_EXTRACT_FLAG_TO_STDOUT) {
1316                 ret = extract_dentries_to_stdout(trees, num_trees,
1317                                                  wim->lookup_table);
1318                 goto out;
1319         }
1320
1321         num_trees = remove_duplicate_trees(trees, num_trees);
1322         num_trees = remove_contained_trees(trees, num_trees);
1323
1324         ops = select_apply_operations(extract_flags);
1325
1326         if (num_trees > 1 && ops->single_tree_only) {
1327                 ERROR("Extracting multiple directory trees "
1328                       "at once is not supported in %s extraction mode!",
1329                       ops->name);
1330                 ret = WIMLIB_ERR_UNSUPPORTED;
1331                 goto out;
1332         }
1333
1334         ctx = CALLOC(1, ops->context_size);
1335         if (!ctx) {
1336                 ret = WIMLIB_ERR_NOMEM;
1337                 goto out;
1338         }
1339
1340         ctx->wim = wim;
1341         ctx->target = target;
1342         ctx->target_nchars = tstrlen(target);
1343         ctx->extract_flags = extract_flags;
1344         if (ctx->wim->progfunc) {
1345                 ctx->progfunc = ctx->wim->progfunc;
1346                 ctx->progctx = ctx->wim->progctx;
1347                 ctx->progress.extract.image = wim->current_image;
1348                 ctx->progress.extract.extract_flags = (extract_flags &
1349                                                        WIMLIB_EXTRACT_MASK_PUBLIC);
1350                 ctx->progress.extract.wimfile_name = wim->filename;
1351                 ctx->progress.extract.image_name = wimlib_get_image_name(wim,
1352                                                                          wim->current_image);
1353                 ctx->progress.extract.target = target;
1354         }
1355         INIT_LIST_HEAD(&ctx->stream_list);
1356         filedes_invalidate(&ctx->tmpfile_fd);
1357
1358         ret = (*ops->get_supported_features)(target, &ctx->supported_features);
1359         if (ret)
1360                 goto out_cleanup;
1361
1362         build_dentry_list(&dentry_list, trees, num_trees,
1363                           !(extract_flags &
1364                             WIMLIB_EXTRACT_FLAG_NO_PRESERVE_DIR_STRUCTURE));
1365
1366         dentry_list_get_features(&dentry_list, &ctx->required_features);
1367
1368         ret = do_feature_check(&ctx->required_features, &ctx->supported_features,
1369                                ctx->extract_flags);
1370         if (ret)
1371                 goto out_cleanup;
1372
1373         ret = dentry_list_calculate_extraction_names(&dentry_list, ctx);
1374         if (ret)
1375                 goto out_cleanup;
1376
1377         ret = dentry_list_resolve_streams(&dentry_list, ctx);
1378         if (ret)
1379                 goto out_cleanup;
1380
1381         ret = dentry_list_ref_streams(&dentry_list, ctx);
1382         if (ret)
1383                 goto out_cleanup;
1384
1385         dentry_list_build_inode_alias_lists(&dentry_list);
1386
1387         if (extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE) {
1388                 /* When extracting from a pipe, the number of bytes of data to
1389                  * extract can't be determined in the normal way (examining the
1390                  * lookup table), since at this point all we have is a set of
1391                  * SHA1 message digests of streams that need to be extracted.
1392                  * However, we can get a reasonably accurate estimate by taking
1393                  * <TOTALBYTES> from the corresponding <IMAGE> in the WIM XML
1394                  * data.  This does assume that a full image is being extracted,
1395                  * but currently there is no API for doing otherwise.  (Also,
1396                  * subtract <HARDLINKBYTES> from this if hard links are
1397                  * supported by the extraction mode.)  */
1398                 ctx->progress.extract.total_bytes =
1399                         wim_info_get_image_total_bytes(wim->wim_info,
1400                                                        wim->current_image);
1401                 if (ctx->supported_features.hard_links) {
1402                         ctx->progress.extract.total_bytes -=
1403                                 wim_info_get_image_hard_link_bytes(wim->wim_info,
1404                                                                    wim->current_image);
1405                 }
1406         }
1407
1408         ret = extract_progress(ctx,
1409                                ((extract_flags & WIMLIB_EXTRACT_FLAG_IMAGEMODE) ?
1410                                        WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN :
1411                                        WIMLIB_PROGRESS_MSG_EXTRACT_TREE_BEGIN));
1412         if (ret)
1413                 goto out_cleanup;
1414
1415         ret = (*ops->extract)(&dentry_list, ctx);
1416         if (ret)
1417                 goto out_cleanup;
1418
1419         if (ctx->progress.extract.completed_bytes <
1420             ctx->progress.extract.total_bytes)
1421         {
1422                 ctx->progress.extract.completed_bytes =
1423                         ctx->progress.extract.total_bytes;
1424                 ret = extract_progress(ctx, WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS);
1425                 if (ret)
1426                         goto out_cleanup;
1427         }
1428
1429         ret = extract_progress(ctx,
1430                                ((extract_flags & WIMLIB_EXTRACT_FLAG_IMAGEMODE) ?
1431                                        WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END :
1432                                        WIMLIB_PROGRESS_MSG_EXTRACT_TREE_END));
1433 out_cleanup:
1434         destroy_stream_list(&ctx->stream_list);
1435         destroy_dentry_list(&dentry_list);
1436         FREE(ctx);
1437 out:
1438         return ret;
1439 }
1440
1441 static int
1442 mkdir_if_needed(const tchar *target)
1443 {
1444         struct stat stbuf;
1445         if (tstat(target, &stbuf)) {
1446                 if (errno == ENOENT) {
1447                         if (tmkdir(target, 0755)) {
1448                                 ERROR_WITH_ERRNO("Failed to create directory "
1449                                                  "\"%"TS"\"", target);
1450                                 return WIMLIB_ERR_MKDIR;
1451                         }
1452                 } else {
1453                         ERROR_WITH_ERRNO("Failed to stat \"%"TS"\"", target);
1454                         return WIMLIB_ERR_STAT;
1455                 }
1456         } else if (!S_ISDIR(stbuf.st_mode)) {
1457                 ERROR("\"%"TS"\" is not a directory", target);
1458                 return WIMLIB_ERR_NOTDIR;
1459         }
1460         return 0;
1461 }
1462
1463 /* Make sure the extraction flags make sense, and update them if needed.  */
1464 static int
1465 check_extract_flags(const WIMStruct *wim, int *extract_flags_p)
1466 {
1467         int extract_flags = *extract_flags_p;
1468
1469         /* Check for invalid flag combinations  */
1470
1471         if ((extract_flags &
1472              (WIMLIB_EXTRACT_FLAG_NO_ACLS |
1473               WIMLIB_EXTRACT_FLAG_STRICT_ACLS)) == (WIMLIB_EXTRACT_FLAG_NO_ACLS |
1474                                                     WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
1475                 return WIMLIB_ERR_INVALID_PARAM;
1476
1477         if ((extract_flags &
1478              (WIMLIB_EXTRACT_FLAG_RPFIX |
1479               WIMLIB_EXTRACT_FLAG_NORPFIX)) == (WIMLIB_EXTRACT_FLAG_RPFIX |
1480                                                 WIMLIB_EXTRACT_FLAG_NORPFIX))
1481                 return WIMLIB_ERR_INVALID_PARAM;
1482
1483 #ifndef WITH_NTFS_3G
1484         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1485                 ERROR("wimlib was compiled without support for NTFS-3g, so\n"
1486                       "        it cannot apply a WIM image directly to an NTFS volume.");
1487                 return WIMLIB_ERR_UNSUPPORTED;
1488         }
1489 #endif
1490
1491 #ifndef __WIN32__
1492         if (extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT) {
1493                 ERROR("WIMBoot extraction is only supported on Windows!");
1494                 return WIMLIB_ERR_UNSUPPORTED;
1495         }
1496 #endif
1497
1498         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_RPFIX |
1499                               WIMLIB_EXTRACT_FLAG_NORPFIX |
1500                               WIMLIB_EXTRACT_FLAG_IMAGEMODE)) ==
1501                                         WIMLIB_EXTRACT_FLAG_IMAGEMODE)
1502         {
1503                 /* For full-image extraction, do reparse point fixups by default
1504                  * if the WIM header says they are enabled.  */
1505                 if (wim->hdr.flags & WIM_HDR_FLAG_RP_FIX)
1506                         extract_flags |= WIMLIB_EXTRACT_FLAG_RPFIX;
1507         }
1508
1509         *extract_flags_p = extract_flags;
1510         return 0;
1511 }
1512
1513 static u32
1514 get_wildcard_flags(int extract_flags)
1515 {
1516         u32 wildcard_flags = 0;
1517
1518         if (extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_GLOB)
1519                 wildcard_flags |= WILDCARD_FLAG_ERROR_IF_NO_MATCH;
1520         else
1521                 wildcard_flags |= WILDCARD_FLAG_WARN_IF_NO_MATCH;
1522
1523         if (default_ignore_case)
1524                 wildcard_flags |= WILDCARD_FLAG_CASE_INSENSITIVE;
1525
1526         return wildcard_flags;
1527 }
1528
1529 struct append_dentry_ctx {
1530         struct wim_dentry **dentries;
1531         size_t num_dentries;
1532         size_t num_alloc_dentries;
1533 };
1534
1535 static int
1536 append_dentry_cb(struct wim_dentry *dentry, void *_ctx)
1537 {
1538         struct append_dentry_ctx *ctx = _ctx;
1539
1540         if (ctx->num_dentries == ctx->num_alloc_dentries) {
1541                 struct wim_dentry **new_dentries;
1542                 size_t new_length;
1543
1544                 new_length = max(ctx->num_alloc_dentries + 8,
1545                                  ctx->num_alloc_dentries * 3 / 2);
1546                 new_dentries = REALLOC(ctx->dentries,
1547                                        new_length * sizeof(ctx->dentries[0]));
1548                 if (new_dentries == NULL)
1549                         return WIMLIB_ERR_NOMEM;
1550                 ctx->dentries = new_dentries;
1551                 ctx->num_alloc_dentries = new_length;
1552         }
1553         ctx->dentries[ctx->num_dentries++] = dentry;
1554         return 0;
1555 }
1556
1557 static int
1558 do_wimlib_extract_paths(WIMStruct *wim, int image, const tchar *target,
1559                         const tchar * const *paths, size_t num_paths,
1560                         int extract_flags)
1561 {
1562         int ret;
1563         struct wim_dentry **trees;
1564         size_t num_trees;
1565
1566         if (wim == NULL || target == NULL || target[0] == T('\0') ||
1567             (num_paths != 0 && paths == NULL))
1568                 return WIMLIB_ERR_INVALID_PARAM;
1569
1570         ret = check_extract_flags(wim, &extract_flags);
1571         if (ret)
1572                 return ret;
1573
1574         ret = select_wim_image(wim, image);
1575         if (ret)
1576                 return ret;
1577
1578         ret = wim_checksum_unhashed_streams(wim);
1579         if (ret)
1580                 return ret;
1581
1582         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_NTFS |
1583                               WIMLIB_EXTRACT_FLAG_NO_PRESERVE_DIR_STRUCTURE)) ==
1584             (WIMLIB_EXTRACT_FLAG_NO_PRESERVE_DIR_STRUCTURE))
1585         {
1586                 ret = mkdir_if_needed(target);
1587                 if (ret)
1588                         return ret;
1589         }
1590
1591         if (extract_flags & WIMLIB_EXTRACT_FLAG_GLOB_PATHS) {
1592
1593                 struct append_dentry_ctx append_dentry_ctx = {
1594                         .dentries = NULL,
1595                         .num_dentries = 0,
1596                         .num_alloc_dentries = 0,
1597                 };
1598
1599                 u32 wildcard_flags = get_wildcard_flags(extract_flags);
1600
1601                 for (size_t i = 0; i < num_paths; i++) {
1602                         tchar *path = canonicalize_wim_path(paths[i]);
1603                         if (path == NULL) {
1604                                 ret = WIMLIB_ERR_NOMEM;
1605                                 trees = append_dentry_ctx.dentries;
1606                                 goto out_free_trees;
1607                         }
1608                         ret = expand_wildcard(wim, path,
1609                                               append_dentry_cb,
1610                                               &append_dentry_ctx,
1611                                               wildcard_flags);
1612                         FREE(path);
1613                         if (ret) {
1614                                 trees = append_dentry_ctx.dentries;
1615                                 goto out_free_trees;
1616                         }
1617                 }
1618                 trees = append_dentry_ctx.dentries;
1619                 num_trees = append_dentry_ctx.num_dentries;
1620         } else {
1621                 trees = MALLOC(num_paths * sizeof(trees[0]));
1622                 if (trees == NULL)
1623                         return WIMLIB_ERR_NOMEM;
1624
1625                 for (size_t i = 0; i < num_paths; i++) {
1626
1627                         tchar *path = canonicalize_wim_path(paths[i]);
1628                         if (path == NULL) {
1629                                 ret = WIMLIB_ERR_NOMEM;
1630                                 goto out_free_trees;
1631                         }
1632
1633                         trees[i] = get_dentry(wim, path,
1634                                               WIMLIB_CASE_PLATFORM_DEFAULT);
1635                         FREE(path);
1636                         if (trees[i] == NULL) {
1637                                   ERROR("Path \"%"TS"\" does not exist "
1638                                         "in WIM image %d",
1639                                         paths[i], wim->current_image);
1640                                   ret = WIMLIB_ERR_PATH_DOES_NOT_EXIST;
1641                                   goto out_free_trees;
1642                         }
1643                 }
1644                 num_trees = num_paths;
1645         }
1646
1647         if (num_trees == 0) {
1648                 ret = 0;
1649                 goto out_free_trees;
1650         }
1651
1652         ret = extract_trees(wim, trees, num_trees, target, extract_flags);
1653 out_free_trees:
1654         FREE(trees);
1655         return ret;
1656 }
1657
1658 static int
1659 extract_single_image(WIMStruct *wim, int image,
1660                      const tchar *target, int extract_flags)
1661 {
1662         const tchar *path = WIMLIB_WIM_ROOT_PATH;
1663         extract_flags |= WIMLIB_EXTRACT_FLAG_IMAGEMODE;
1664         return do_wimlib_extract_paths(wim, image, target, &path, 1, extract_flags);
1665 }
1666
1667 static const tchar * const filename_forbidden_chars =
1668 T(
1669 #ifdef __WIN32__
1670 "<>:\"/\\|?*"
1671 #else
1672 "/"
1673 #endif
1674 );
1675
1676 /* This function checks if it is okay to use a WIM image's name as a directory
1677  * name.  */
1678 static bool
1679 image_name_ok_as_dir(const tchar *image_name)
1680 {
1681         return image_name && *image_name &&
1682                 !tstrpbrk(image_name, filename_forbidden_chars) &&
1683                 tstrcmp(image_name, T(".")) &&
1684                 tstrcmp(image_name, T(".."));
1685 }
1686
1687 /* Extracts all images from the WIM to the directory @target, with the images
1688  * placed in subdirectories named by their image names. */
1689 static int
1690 extract_all_images(WIMStruct *wim, const tchar *target, int extract_flags)
1691 {
1692         size_t image_name_max_len = max(xml_get_max_image_name_len(wim), 20);
1693         size_t output_path_len = tstrlen(target);
1694         tchar buf[output_path_len + 1 + image_name_max_len + 1];
1695         int ret;
1696         int image;
1697         const tchar *image_name;
1698
1699         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1700                 ERROR("Cannot extract multiple images in NTFS extraction mode.");
1701                 return WIMLIB_ERR_INVALID_PARAM;
1702         }
1703
1704         ret = mkdir_if_needed(target);
1705         if (ret)
1706                 return ret;
1707         tmemcpy(buf, target, output_path_len);
1708         buf[output_path_len] = OS_PREFERRED_PATH_SEPARATOR;
1709         for (image = 1; image <= wim->hdr.image_count; image++) {
1710                 image_name = wimlib_get_image_name(wim, image);
1711                 if (image_name_ok_as_dir(image_name)) {
1712                         tstrcpy(buf + output_path_len + 1, image_name);
1713                 } else {
1714                         /* Image name is empty or contains forbidden characters.
1715                          * Use image number instead. */
1716                         tsprintf(buf + output_path_len + 1, T("%d"), image);
1717                 }
1718                 ret = extract_single_image(wim, image, buf, extract_flags);
1719                 if (ret)
1720                         return ret;
1721         }
1722         return 0;
1723 }
1724
1725 static int
1726 do_wimlib_extract_image(WIMStruct *wim, int image, const tchar *target,
1727                         int extract_flags)
1728 {
1729         if (extract_flags & (WIMLIB_EXTRACT_FLAG_NO_PRESERVE_DIR_STRUCTURE |
1730                              WIMLIB_EXTRACT_FLAG_TO_STDOUT |
1731                              WIMLIB_EXTRACT_FLAG_GLOB_PATHS))
1732                 return WIMLIB_ERR_INVALID_PARAM;
1733
1734         if (image == WIMLIB_ALL_IMAGES)
1735                 return extract_all_images(wim, target, extract_flags);
1736         else
1737                 return extract_single_image(wim, image, target, extract_flags);
1738 }
1739
1740
1741 /****************************************************************************
1742  *                          Extraction API                                  *
1743  ****************************************************************************/
1744
1745 WIMLIBAPI int
1746 wimlib_extract_paths(WIMStruct *wim, int image, const tchar *target,
1747                      const tchar * const *paths, size_t num_paths,
1748                      int extract_flags)
1749 {
1750         if (extract_flags & ~WIMLIB_EXTRACT_MASK_PUBLIC)
1751                 return WIMLIB_ERR_INVALID_PARAM;
1752
1753         return do_wimlib_extract_paths(wim, image, target, paths, num_paths,
1754                                        extract_flags);
1755 }
1756
1757 WIMLIBAPI int
1758 wimlib_extract_pathlist(WIMStruct *wim, int image, const tchar *target,
1759                         const tchar *path_list_file, int extract_flags)
1760 {
1761         int ret;
1762         tchar **paths;
1763         size_t num_paths;
1764         void *mem;
1765
1766         ret = read_path_list_file(path_list_file, &paths, &num_paths, &mem);
1767         if (ret) {
1768                 ERROR("Failed to read path list file \"%"TS"\"",
1769                       path_list_file);
1770                 return ret;
1771         }
1772
1773         ret = wimlib_extract_paths(wim, image, target,
1774                                    (const tchar * const *)paths, num_paths,
1775                                    extract_flags);
1776         FREE(paths);
1777         FREE(mem);
1778         return ret;
1779 }
1780
1781 WIMLIBAPI int
1782 wimlib_extract_image_from_pipe_with_progress(int pipe_fd,
1783                                              const tchar *image_num_or_name,
1784                                              const tchar *target,
1785                                              int extract_flags,
1786                                              wimlib_progress_func_t progfunc,
1787                                              void *progctx)
1788 {
1789         int ret;
1790         WIMStruct *pwm;
1791         struct filedes *in_fd;
1792         int image;
1793         unsigned i;
1794
1795         if (extract_flags & ~WIMLIB_EXTRACT_MASK_PUBLIC)
1796                 return WIMLIB_ERR_INVALID_PARAM;
1797
1798         /* Read the WIM header from the pipe and get a WIMStruct to represent
1799          * the pipable WIM.  Caveats:  Unlike getting a WIMStruct with
1800          * wimlib_open_wim(), getting a WIMStruct in this way will result in
1801          * an empty lookup table, no XML data read, and no filename set.  */
1802         ret = open_wim_as_WIMStruct(&pipe_fd, WIMLIB_OPEN_FLAG_FROM_PIPE, &pwm,
1803                                     progfunc, progctx);
1804         if (ret)
1805                 return ret;
1806
1807         /* Sanity check to make sure this is a pipable WIM.  */
1808         if (pwm->hdr.magic != PWM_MAGIC) {
1809                 ERROR("The WIM being read from file descriptor %d "
1810                       "is not pipable!", pipe_fd);
1811                 ret = WIMLIB_ERR_NOT_PIPABLE;
1812                 goto out_wimlib_free;
1813         }
1814
1815         /* Sanity check to make sure the first part of a pipable split WIM is
1816          * sent over the pipe first.  */
1817         if (pwm->hdr.part_number != 1) {
1818                 ERROR("The first part of the split WIM must be "
1819                       "sent over the pipe first.");
1820                 ret = WIMLIB_ERR_INVALID_PIPABLE_WIM;
1821                 goto out_wimlib_free;
1822         }
1823
1824         in_fd = &pwm->in_fd;
1825         wimlib_assert(in_fd->offset == WIM_HEADER_DISK_SIZE);
1826
1827         /* As mentioned, the WIMStruct we created from the pipe does not have
1828          * XML data yet.  Fix this by reading the extra copy of the XML data
1829          * that directly follows the header in pipable WIMs.  (Note: see
1830          * write_pipable_wim() for more details about the format of pipable
1831          * WIMs.)  */
1832         {
1833                 struct wim_lookup_table_entry xml_lte;
1834                 struct wim_resource_spec xml_rspec;
1835                 ret = read_pwm_stream_header(pwm, &xml_lte, &xml_rspec, 0, NULL);
1836                 if (ret)
1837                         goto out_wimlib_free;
1838
1839                 if (!(xml_lte.flags & WIM_RESHDR_FLAG_METADATA))
1840                 {
1841                         ERROR("Expected XML data, but found non-metadata "
1842                               "stream.");
1843                         ret = WIMLIB_ERR_INVALID_PIPABLE_WIM;
1844                         goto out_wimlib_free;
1845                 }
1846
1847                 wim_res_spec_to_hdr(&xml_rspec, &pwm->hdr.xml_data_reshdr);
1848
1849                 ret = read_wim_xml_data(pwm);
1850                 if (ret)
1851                         goto out_wimlib_free;
1852
1853                 if (wim_info_get_num_images(pwm->wim_info) != pwm->hdr.image_count) {
1854                         ERROR("Image count in XML data is not the same as in WIM header.");
1855                         ret = WIMLIB_ERR_IMAGE_COUNT;
1856                         goto out_wimlib_free;
1857                 }
1858         }
1859
1860         /* Get image index (this may use the XML data that was just read to
1861          * resolve an image name).  */
1862         if (image_num_or_name) {
1863                 image = wimlib_resolve_image(pwm, image_num_or_name);
1864                 if (image == WIMLIB_NO_IMAGE) {
1865                         ERROR("\"%"TS"\" is not a valid image in the pipable WIM!",
1866                               image_num_or_name);
1867                         ret = WIMLIB_ERR_INVALID_IMAGE;
1868                         goto out_wimlib_free;
1869                 } else if (image == WIMLIB_ALL_IMAGES) {
1870                         ERROR("Applying all images from a pipe is not supported!");
1871                         ret = WIMLIB_ERR_INVALID_IMAGE;
1872                         goto out_wimlib_free;
1873                 }
1874         } else {
1875                 if (pwm->hdr.image_count != 1) {
1876                         ERROR("No image was specified, but the pipable WIM "
1877                               "did not contain exactly 1 image");
1878                         ret = WIMLIB_ERR_INVALID_IMAGE;
1879                         goto out_wimlib_free;
1880                 }
1881                 image = 1;
1882         }
1883
1884         /* Load the needed metadata resource.  */
1885         for (i = 1; i <= pwm->hdr.image_count; i++) {
1886                 struct wim_lookup_table_entry *metadata_lte;
1887                 struct wim_image_metadata *imd;
1888                 struct wim_resource_spec *metadata_rspec;
1889
1890                 metadata_lte = new_lookup_table_entry();
1891                 if (metadata_lte == NULL) {
1892                         ret = WIMLIB_ERR_NOMEM;
1893                         goto out_wimlib_free;
1894                 }
1895                 metadata_rspec = MALLOC(sizeof(struct wim_resource_spec));
1896                 if (metadata_rspec == NULL) {
1897                         ret = WIMLIB_ERR_NOMEM;
1898                         free_lookup_table_entry(metadata_lte);
1899                         goto out_wimlib_free;
1900                 }
1901
1902                 ret = read_pwm_stream_header(pwm, metadata_lte, metadata_rspec, 0, NULL);
1903                 imd = pwm->image_metadata[i - 1];
1904                 imd->metadata_lte = metadata_lte;
1905                 if (ret) {
1906                         FREE(metadata_rspec);
1907                         goto out_wimlib_free;
1908                 }
1909
1910                 if (!(metadata_lte->flags & WIM_RESHDR_FLAG_METADATA)) {
1911                         ERROR("Expected metadata resource, but found "
1912                               "non-metadata stream.");
1913                         ret = WIMLIB_ERR_INVALID_PIPABLE_WIM;
1914                         goto out_wimlib_free;
1915                 }
1916
1917                 if (i == image) {
1918                         /* Metadata resource is for the image being extracted.
1919                          * Parse it and save the metadata in memory.  */
1920                         ret = read_metadata_resource(pwm, imd);
1921                         if (ret)
1922                                 goto out_wimlib_free;
1923                         imd->modified = 1;
1924                 } else {
1925                         /* Metadata resource is not for the image being
1926                          * extracted.  Skip over it.  */
1927                         ret = skip_wim_stream(metadata_lte);
1928                         if (ret)
1929                                 goto out_wimlib_free;
1930                 }
1931         }
1932         /* Extract the image.  */
1933         extract_flags |= WIMLIB_EXTRACT_FLAG_FROM_PIPE;
1934         ret = do_wimlib_extract_image(pwm, image, target, extract_flags);
1935         /* Clean up and return.  */
1936 out_wimlib_free:
1937         wimlib_free(pwm);
1938         return ret;
1939 }
1940
1941
1942 WIMLIBAPI int
1943 wimlib_extract_image_from_pipe(int pipe_fd, const tchar *image_num_or_name,
1944                                const tchar *target, int extract_flags)
1945 {
1946         return wimlib_extract_image_from_pipe_with_progress(pipe_fd,
1947                                                             image_num_or_name,
1948                                                             target,
1949                                                             extract_flags,
1950                                                             NULL,
1951                                                             NULL);
1952 }
1953
1954 WIMLIBAPI int
1955 wimlib_extract_image(WIMStruct *wim, int image, const tchar *target,
1956                      int extract_flags)
1957 {
1958         if (extract_flags & ~WIMLIB_EXTRACT_MASK_PUBLIC)
1959                 return WIMLIB_ERR_INVALID_PARAM;
1960         return do_wimlib_extract_image(wim, image, target, extract_flags);
1961 }