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