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