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