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