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