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