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