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