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