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