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