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