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