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