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