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