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