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