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