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