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