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