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