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