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