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