]> wimlib.net Git - wimlib/blob - src/extract.c
b40d708d6c6e8b5fc4f64ef8e61e31514e4b2edf
[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 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_files(), and wimlib_extract_image_from_pipe().  Internally,
30  * all end up calling extract_tree() zero or more times to extract a tree of
31  * files from the currently selected WIM image to the specified target directory
32  * or NTFS volume.
33  *
34  * Although wimlib supports multiple extraction modes/backends (NTFS-3g, UNIX,
35  * Win32), this file does not itself have code to extract files or directories
36  * to any specific target; instead, it handles generic functionality and relies
37  * on lower-level callback functions declared in `struct apply_operations' to do
38  * the actual extraction.
39  */
40
41 #ifdef HAVE_CONFIG_H
42 #  include "config.h"
43 #endif
44
45 #include "wimlib/apply.h"
46 #include "wimlib/dentry.h"
47 #include "wimlib/encoding.h"
48 #include "wimlib/endianness.h"
49 #include "wimlib/error.h"
50 #include "wimlib/lookup_table.h"
51 #include "wimlib/metadata.h"
52 #include "wimlib/paths.h"
53 #include "wimlib/reparse.h"
54 #include "wimlib/resource.h"
55 #include "wimlib/security.h"
56 #include "wimlib/swm.h"
57 #ifdef __WIN32__
58 #  include "wimlib/win32.h" /* for realpath() equivalent */
59 #endif
60 #include "wimlib/xml.h"
61 #include "wimlib/wim.h"
62
63 #include <errno.h>
64 #include <fcntl.h>
65 #include <stdlib.h>
66 #include <sys/stat.h>
67 #include <unistd.h>
68
69 #define WIMLIB_EXTRACT_FLAG_MULTI_IMAGE 0x80000000
70 #define WIMLIB_EXTRACT_FLAG_FROM_PIPE   0x40000000
71 #define WIMLIB_EXTRACT_MASK_PUBLIC      0x3fffffff
72
73 /* Given a WIM dentry in the tree to be extracted, resolve all streams in the
74  * corresponding inode and set 'out_refcnt' in each to 0.  */
75 static int
76 dentry_resolve_and_zero_lte_refcnt(struct wim_dentry *dentry, void *_ctx)
77 {
78         struct apply_ctx *ctx = _ctx;
79         struct wim_inode *inode = dentry->d_inode;
80         struct wim_lookup_table_entry *lte;
81         int ret;
82         bool force = false;
83
84         if (dentry->extraction_skipped)
85                 return 0;
86
87         /* Special case:  when extracting from a pipe, the WIM lookup table is
88          * initially empty, so "resolving" an inode's streams is initially not
89          * possible.  However, we still need to keep track of which streams,
90          * identified by SHA1 message digests, need to be extracted, so we
91          * "resolve" the inode's streams anyway by allocating new entries.  */
92         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE)
93                 force = true;
94         ret = inode_resolve_ltes(inode, ctx->wim->lookup_table, force);
95         if (ret)
96                 return ret;
97         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
98                 lte = inode_stream_lte_resolved(inode, i);
99                 if (lte)
100                         lte->out_refcnt = 0;
101         }
102         return 0;
103 }
104
105 static inline bool
106 is_linked_extraction(const struct apply_ctx *ctx)
107 {
108         return 0 != (ctx->extract_flags & (WIMLIB_EXTRACT_FLAG_HARDLINK |
109                                            WIMLIB_EXTRACT_FLAG_SYMLINK));
110 }
111
112 static inline bool
113 can_extract_named_data_streams(const struct apply_ctx *ctx)
114 {
115         return ctx->supported_features.named_data_streams &&
116                 !is_linked_extraction(ctx);
117 }
118
119 static int
120 ref_stream_to_extract(struct wim_lookup_table_entry *lte,
121                       struct wim_dentry *dentry, struct apply_ctx *ctx)
122 {
123         if (!lte)
124                 return 0;
125
126         if (likely(!is_linked_extraction(ctx)) || (lte->out_refcnt == 0 &&
127                                                    lte->extracted_file == NULL))
128         {
129                 ctx->progress.extract.total_bytes += wim_resource_size(lte);
130                 ctx->progress.extract.num_streams++;
131         }
132
133         if (lte->out_refcnt == 0) {
134                 list_add_tail(&lte->extraction_list, &ctx->stream_list);
135                 ctx->num_streams_remaining++;
136         }
137
138         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_SEQUENTIAL) {
139                 struct wim_dentry **lte_dentries;
140
141                 /* Append dentry to this stream's array of dentries referencing
142                  * it.  Use inline array to avoid memory allocation until the
143                  * number of dentries becomes too large.  */
144                 if (lte->out_refcnt < ARRAY_LEN(lte->inline_lte_dentries)) {
145                         lte_dentries = lte->inline_lte_dentries;
146                 } else {
147                         struct wim_dentry **prev_lte_dentries;
148                         size_t alloc_lte_dentries;
149
150                         if (lte->out_refcnt == ARRAY_LEN(lte->inline_lte_dentries)) {
151                                 prev_lte_dentries = NULL;
152                                 alloc_lte_dentries = ARRAY_LEN(lte->inline_lte_dentries);
153                         } else {
154                                 prev_lte_dentries = lte->lte_dentries;
155                                 alloc_lte_dentries = lte->alloc_lte_dentries;
156                         }
157
158                         if (lte->out_refcnt == alloc_lte_dentries) {
159                                 alloc_lte_dentries *= 2;
160                                 lte_dentries = REALLOC(prev_lte_dentries,
161                                                        alloc_lte_dentries *
162                                                         sizeof(lte_dentries[0]));
163                                 if (!lte_dentries)
164                                         return WIMLIB_ERR_NOMEM;
165                                 if (prev_lte_dentries == NULL) {
166                                         memcpy(lte_dentries,
167                                                lte->inline_lte_dentries,
168                                                sizeof(lte->inline_lte_dentries));
169                                 }
170                                 lte->lte_dentries = lte_dentries;
171                                 lte->alloc_lte_dentries = alloc_lte_dentries;
172                         }
173                         lte_dentries = lte->lte_dentries;
174                 }
175                 lte_dentries[lte->out_refcnt] = dentry;
176         }
177         lte->out_refcnt++;
178         return 0;
179 }
180
181 /* Given a WIM dentry in the tree to be extracted, iterate through streams that
182  * need to be extracted.  For each one, add it to the list of streams to be
183  * extracted (ctx->stream_list) if not already done so, and also update the
184  * progress information (ctx->progress) with the stream.  Furthermore, if doing
185  * a sequential extraction, build a mapping from each the stream to the dentries
186  * referencing it.  */
187 static int
188 dentry_add_streams_to_extract(struct wim_dentry *dentry, void *_ctx)
189 {
190         struct apply_ctx *ctx = _ctx;
191         struct wim_inode *inode = dentry->d_inode;
192         int ret;
193
194         /* Don't process dentries marked as skipped.  */
195         if (dentry->extraction_skipped)
196                 return 0;
197
198         /* Don't process additional hard links.  */
199         if (inode->i_visited && ctx->supported_features.hard_links)
200                 return 0;
201
202         /* The unnamed data stream will always be extracted, except in an
203          * unlikely case.  */
204         if (!inode_is_encrypted_directory(inode)) {
205                 ret = ref_stream_to_extract(inode_unnamed_lte_resolved(inode),
206                                             dentry, ctx);
207                 if (ret)
208                         return ret;
209         }
210
211         /* Named data streams will be extracted only if supported in the current
212          * extraction mode and volume, and to avoid complications, if not doing
213          * a linked extraction.  */
214         if (can_extract_named_data_streams(ctx)) {
215                 for (u16 i = 0; i < inode->i_num_ads; i++) {
216                         if (!ads_entry_is_named_stream(&inode->i_ads_entries[i]))
217                                 continue;
218                         ret = ref_stream_to_extract(inode->i_ads_entries[i].lte,
219                                                     dentry, ctx);
220                         if (ret)
221                                 return ret;
222                 }
223         }
224         inode->i_visited = 1;
225         return 0;
226 }
227
228 /* Inform library user of progress of stream extraction following the successful
229  * extraction of a copy of the stream specified by @lte.  */
230 static void
231 update_extract_progress(struct apply_ctx *ctx,
232                         const struct wim_lookup_table_entry *lte)
233 {
234         wimlib_progress_func_t progress_func = ctx->progress_func;
235         union wimlib_progress_info *progress = &ctx->progress;
236
237         progress->extract.completed_bytes += wim_resource_size(lte);
238         if (progress_func &&
239             progress->extract.completed_bytes >= ctx->next_progress)
240         {
241                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS, progress);
242                 if (progress->extract.completed_bytes >=
243                     progress->extract.total_bytes)
244                 {
245                         ctx->next_progress = ~0ULL;
246                 } else {
247                         ctx->next_progress += progress->extract.total_bytes / 128;
248                         if (ctx->next_progress > progress->extract.total_bytes)
249                                 ctx->next_progress = progress->extract.total_bytes;
250                 }
251         }
252 }
253
254 #ifndef __WIN32__
255 /* Extract a symbolic link (not directly as reparse data), handling fixing up
256  * the target of absolute symbolic links and updating the extract progress.
257  *
258  * @inode must specify the WIM inode for a symbolic link or junction reparse
259  * point.
260  *
261  * @lte_override overrides the resource used as the reparse data for the
262  * symbolic link.  */
263 static int
264 extract_symlink(const tchar *path, struct apply_ctx *ctx,
265                 struct wim_inode *inode,
266                 struct wim_lookup_table_entry *lte_override)
267 {
268         ssize_t bufsize = ctx->ops->path_max;
269         tchar target[bufsize];
270         tchar *buf = target;
271         tchar *fixed_target;
272         ssize_t sret;
273         int ret;
274
275         /* If absolute symbolic link fixups requested, reserve space in the link
276          * target buffer for the absolute path of the target directory.  */
277         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
278         {
279                 buf += ctx->realtarget_nchars;
280                 bufsize -= ctx->realtarget_nchars;
281         }
282
283         /* Translate the WIM inode's reparse data into the link target.  */
284         sret = wim_inode_readlink(inode, buf, bufsize - 1, lte_override);
285         if (sret < 0) {
286                 errno = -sret;
287                 return WIMLIB_ERR_READLINK;
288         }
289         buf[sret] = '\0';
290
291         if ((ctx->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX) &&
292             buf[0] == '/')
293         {
294                 /* Fix absolute symbolic link target to point into the
295                  * actual extraction destination.  */
296                 tmemcpy(target, ctx->realtarget, ctx->realtarget_nchars);
297                 fixed_target = target;
298         } else {
299                 /* Keep same link target.  */
300                 fixed_target = buf;
301         }
302
303         /* Call into the apply_operations to create the symbolic link.  */
304         DEBUG("Creating symlink \"%"TS"\" => \"%"TS"\"",
305               path, fixed_target);
306         ret = ctx->ops->create_symlink(fixed_target, path, ctx);
307         if (ret) {
308                 ERROR_WITH_ERRNO("Failed to create symlink "
309                                  "\"%"TS"\" => \"%"TS"\"", path, fixed_target);
310                 return ret;
311         }
312
313         /* Account for reparse data consumed.  */
314         update_extract_progress(ctx,
315                                 (lte_override ? lte_override :
316                                       inode_unnamed_lte_resolved(inode)));
317         return 0;
318 }
319 #endif /* !__WIN32__ */
320
321 /* Create a file, directory, or symbolic link.  */
322 static int
323 extract_inode(const tchar *path, struct apply_ctx *ctx, struct wim_inode *inode)
324 {
325         int ret;
326
327 #ifndef __WIN32__
328         if (ctx->supported_features.symlink_reparse_points &&
329             !ctx->supported_features.reparse_points &&
330             inode_is_symlink(inode))
331         {
332                 ret = extract_symlink(path, ctx, inode, NULL);
333         } else
334 #endif /* !__WIN32__ */
335         if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
336                 ret = ctx->ops->create_directory(path, ctx, &inode->extract_cookie);
337                 if (ret) {
338                         ERROR_WITH_ERRNO("Failed to create the directory "
339                                          "\"%"TS"\"", path);
340                 }
341         } else if ((inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) &&
342                     ctx->ops->extract_encrypted_stream_creates_file &&
343                     ctx->supported_features.encrypted_files) {
344                 ret = ctx->ops->extract_encrypted_stream(
345                                 path, inode_unnamed_lte_resolved(inode), ctx);
346                 if (ret) {
347                         ERROR_WITH_ERRNO("Failed to create and extract "
348                                          "encrypted file \"%"TS"\"", path);
349                 }
350         } else {
351                 ret = ctx->ops->create_file(path, ctx, &inode->extract_cookie);
352                 if (ret) {
353                         ERROR_WITH_ERRNO("Failed to create the file "
354                                          "\"%"TS"\"", path);
355                 }
356         }
357         return ret;
358 }
359
360 static int
361 extract_hardlink(const tchar *oldpath, const tchar *newpath,
362                  struct apply_ctx *ctx)
363 {
364         int ret;
365
366         DEBUG("Creating hardlink \"%"TS"\" => \"%"TS"\"", newpath, oldpath);
367         ret = ctx->ops->create_hardlink(oldpath, newpath, ctx);
368         if (ret) {
369                 ERROR_WITH_ERRNO("Failed to create hardlink "
370                                  "\"%"TS"\" => \"%"TS"\"",
371                                  newpath, oldpath);
372         }
373         return ret;
374 }
375
376 #ifdef __WIN32__
377 static int
378 try_extract_rpfix(u8 *rpbuf,
379                   u16 *rpbuflen_p,
380                   const wchar_t *extract_root_realpath,
381                   unsigned extract_root_realpath_nchars)
382 {
383         struct reparse_data rpdata;
384         wchar_t *target;
385         size_t target_nchars;
386         size_t stripped_nchars;
387         wchar_t *stripped_target;
388         wchar_t stripped_target_nchars;
389         int ret;
390
391         utf16lechar *new_target;
392         utf16lechar *new_print_name;
393         size_t new_target_nchars;
394         size_t new_print_name_nchars;
395         utf16lechar *p;
396
397         ret = parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata);
398         if (ret)
399                 return ret;
400
401         if (extract_root_realpath[0] == L'\0' ||
402             extract_root_realpath[1] != L':' ||
403             extract_root_realpath[2] != L'\\')
404                 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
405
406         ret = parse_substitute_name(rpdata.substitute_name,
407                                     rpdata.substitute_name_nbytes,
408                                     rpdata.rptag);
409         if (ret < 0)
410                 return 0;
411         stripped_nchars = ret;
412         target = rpdata.substitute_name;
413         target_nchars = rpdata.substitute_name_nbytes / sizeof(utf16lechar);
414         stripped_target = target + stripped_nchars;
415         stripped_target_nchars = target_nchars - stripped_nchars;
416
417         new_target = alloca((6 + extract_root_realpath_nchars +
418                              stripped_target_nchars) * sizeof(utf16lechar));
419
420         p = new_target;
421         if (stripped_nchars == 6) {
422                 /* Include \??\ prefix if it was present before */
423                 p = wmempcpy(p, L"\\??\\", 4);
424         }
425
426         /* Print name excludes the \??\ if present. */
427         new_print_name = p;
428         if (stripped_nchars != 0) {
429                 /* Get drive letter from real path to extract root, if a drive
430                  * letter was present before. */
431                 *p++ = extract_root_realpath[0];
432                 *p++ = extract_root_realpath[1];
433         }
434         /* Copy the rest of the extract root */
435         p = wmempcpy(p, extract_root_realpath + 2, extract_root_realpath_nchars - 2);
436
437         /* Append the stripped target */
438         p = wmempcpy(p, stripped_target, stripped_target_nchars);
439         new_target_nchars = p - new_target;
440         new_print_name_nchars = p - new_print_name;
441
442         if (new_target_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE ||
443             new_print_name_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE)
444                 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
445
446         rpdata.substitute_name = new_target;
447         rpdata.substitute_name_nbytes = new_target_nchars * sizeof(utf16lechar);
448         rpdata.print_name = new_print_name;
449         rpdata.print_name_nbytes = new_print_name_nchars * sizeof(utf16lechar);
450         return make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
451 }
452 #endif /* __WIN32__ */
453
454 /* Set reparse data on extracted file or directory that has
455  * FILE_ATTRIBUTE_REPARSE_POINT set.  */
456 static int
457 extract_reparse_data(const tchar *path, struct apply_ctx *ctx,
458                      struct wim_inode *inode,
459                      struct wim_lookup_table_entry *lte_override)
460 {
461         int ret;
462         u8 rpbuf[REPARSE_POINT_MAX_SIZE];
463         u16 rpbuflen;
464
465         ret = wim_inode_get_reparse_data(inode, rpbuf, &rpbuflen, lte_override);
466         if (ret)
467                 goto error;
468
469 #ifdef __WIN32__
470         /* Fix up target of absolute symbolic link or junction points so
471          * that they point into the actual extraction target.  */
472         if ((ctx->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX) &&
473             (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
474              inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT) &&
475             !inode->i_not_rpfixed)
476         {
477                 ret = try_extract_rpfix(rpbuf, &rpbuflen, ctx->realtarget,
478                                         ctx->realtarget_nchars);
479                 if (ret && !(ctx->extract_flags &
480                              WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS))
481                 {
482                         WARNING("Reparse point fixup of \"%"TS"\" "
483                                 "failed", path);
484                         ret = 0;
485                 }
486                 if (ret)
487                         goto error;
488         }
489 #endif
490
491         ret = ctx->ops->set_reparse_data(path, rpbuf, rpbuflen, ctx);
492
493         /* On Windows, the SeCreateSymbolicLink privilege is required to create
494          * symbolic links.  To be more friendly towards non-Administrator users,
495          * we merely warn the user if symbolic links cannot be created due to
496          * insufficient permissions or privileges, unless
497          * WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS was provided.  */
498 #ifdef __WIN32__
499         if (ret && inode_is_symlink(inode) &&
500             (errno == EACCES || errno == EPERM) &&
501             !(ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS))
502         {
503                 WARNING("Can't set reparse data on \"%"TS"\": "
504                         "Access denied!\n"
505                         "          You may be trying to "
506                         "extract a symbolic link without the\n"
507                         "          SeCreateSymbolicLink privilege, "
508                         "which by default non-Administrator\n"
509                         "          accounts do not have.",
510                         path);
511                 ret = 0;
512         }
513 #endif
514         if (ret)
515                 goto error;
516
517         /* Account for reparse data consumed.  */
518         update_extract_progress(ctx,
519                                 (lte_override ? lte_override :
520                                       inode_unnamed_lte_resolved(inode)));
521         return 0;
522
523 error:
524         ERROR_WITH_ERRNO("Failed to set reparse data on \"%"TS"\"", path);
525         return ret;
526 }
527
528 /*
529  * Extract zero or more streams to a file.
530  *
531  * This function operates slightly differently depending on whether @lte_spec is
532  * NULL or not.  When @lte_spec is NULL, the behavior is to extract the default
533  * file contents (unnamed stream), and, if named data streams are supported in
534  * the extract mode and volume, any named data streams.  When @lte_spec is NULL,
535  * the behavior is to extract only all copies of the stream @lte_spec, and in
536  * addition use @lte_spec to set the reparse data or create the symbolic link if
537  * appropriate.
538  *
539  * @path
540  *      Path to file to extract (as can be passed to apply_operations
541  *      functions).
542  * @ctx
543  *      Apply context.
544  * @dentry
545  *      WIM dentry that corresponds to the file being extracted.
546  * @lte_spec
547  *      If non-NULL, specifies the lookup table entry for a stream to extract,
548  *      and only that stream will be extracted (although there may be more than
549  *      one instance of it).
550  * @lte_override
551  *      Used only if @lte_spec != NULL; it is passed to the extraction functions
552  *      rather than @lte_spec, allowing the location of the stream to be
553  *      overridden.  (This is used when the WIM is being read from a nonseekable
554  *      file, such as a pipe, when streams need to be used more than once; each
555  *      such stream is extracted to a temporary file.)
556  */
557 static int
558 extract_streams(const tchar *path, struct apply_ctx *ctx,
559                 struct wim_dentry *dentry,
560                 struct wim_lookup_table_entry *lte_spec,
561                 struct wim_lookup_table_entry *lte_override)
562 {
563         struct wim_inode *inode = dentry->d_inode;
564         struct wim_lookup_table_entry *lte;
565         file_spec_t file_spec;
566         int ret;
567
568         if (dentry->was_hardlinked)
569                 return 0;
570
571 #ifdef ENABLE_DEBUG
572         if (lte_spec) {
573                 char sha1_str[100];
574                 char *p = sha1_str;
575                 for (unsigned i = 0; i < SHA1_HASH_SIZE; i++)
576                         p += sprintf(p, "%02x", lte_override->hash[i]);
577                 DEBUG("Extracting stream SHA1=%s to \"%"TS"\"",
578                       sha1_str, path, inode->i_ino);
579         } else {
580                 DEBUG("Extracting streams to \"%"TS"\"", path, inode->i_ino);
581         }
582 #endif
583
584         if (ctx->ops->uses_cookies)
585                 file_spec.cookie = inode->extract_cookie;
586         else
587                 file_spec.path = path;
588
589         /* Unnamed data stream.  */
590         lte = inode_unnamed_lte_resolved(inode);
591         if (lte && (!lte_spec || lte == lte_spec)) {
592                 if (lte_spec)
593                         lte = lte_override;
594                 if (!(inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
595                                              FILE_ATTRIBUTE_REPARSE_POINT)))
596                 {
597                         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED &&
598                             ctx->supported_features.encrypted_files) {
599                                 if (!ctx->ops->extract_encrypted_stream_creates_file) {
600                                         ret = ctx->ops->extract_encrypted_stream(
601                                                                 path, lte, ctx);
602                                         if (ret)
603                                                 goto error;
604                                 }
605                         } else {
606                                 ret = ctx->ops->extract_unnamed_stream(
607                                                         file_spec, lte, ctx);
608                                 if (ret)
609                                         goto error;
610                         }
611                         update_extract_progress(ctx, lte);
612                 }
613                 else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
614                 {
615                         ret = 0;
616                         if (ctx->supported_features.reparse_points)
617                                 ret = extract_reparse_data(path, ctx, inode, lte);
618                 #ifndef __WIN32__
619                         else if ((inode_is_symlink(inode) &&
620                                   ctx->supported_features.symlink_reparse_points))
621                                 ret = extract_symlink(path, ctx, inode, lte);
622                 #endif
623                         if (ret)
624                                 return ret;
625                 }
626         }
627
628         /* Named data streams.  */
629         if (can_extract_named_data_streams(ctx)) {
630                 for (u16 i = 0; i < inode->i_num_ads; i++) {
631                         struct wim_ads_entry *entry = &inode->i_ads_entries[i];
632
633                         if (!ads_entry_is_named_stream(entry))
634                                 continue;
635                         lte = entry->lte;
636                         if (!lte)
637                                 continue;
638                         if (lte_spec && lte_spec != lte)
639                                 continue;
640                         if (lte_spec)
641                                 lte = lte_override;
642                         ret = ctx->ops->extract_named_stream(file_spec, entry->stream_name,
643                                                              entry->stream_name_nbytes / 2,
644                                                              lte, ctx);
645                         if (ret)
646                                 goto error;
647                         update_extract_progress(ctx, lte);
648                 }
649         }
650         return 0;
651
652 error:
653         ERROR_WITH_ERRNO("Failed to extract data of \"%"TS"\"", path);
654         return ret;
655 }
656
657 /* Set attributes on an extracted file or directory if supported by the
658  * extraction mode.  */
659 static int
660 extract_file_attributes(const tchar *path, struct apply_ctx *ctx,
661                         struct wim_dentry *dentry, unsigned pass)
662 {
663         int ret;
664
665         if (ctx->ops->set_file_attributes &&
666             !(dentry == ctx->extract_root && ctx->root_dentry_is_special)) {
667                 u32 attributes = dentry->d_inode->i_attributes;
668
669                 /* Clear unsupported attributes.  */
670                 attributes &= ctx->supported_attributes_mask;
671
672                 if ((attributes & FILE_ATTRIBUTE_DIRECTORY &&
673                      !ctx->supported_features.encrypted_directories) ||
674                     (!(attributes & FILE_ATTRIBUTE_DIRECTORY) &&
675                      !ctx->supported_features.encrypted_files))
676                 {
677                         attributes &= ~FILE_ATTRIBUTE_ENCRYPTED;
678                 }
679
680                 if (attributes == 0)
681                         attributes = FILE_ATTRIBUTE_NORMAL;
682
683                 ret = ctx->ops->set_file_attributes(path, attributes, ctx, pass);
684                 if (ret) {
685                         ERROR_WITH_ERRNO("Failed to set attributes on "
686                                          "\"%"TS"\"", path);
687                         return ret;
688                 }
689         }
690         return 0;
691 }
692
693
694 /* Set or remove the short (DOS) name on an extracted file or directory if
695  * supported by the extraction mode.  Since DOS names are unimportant and it's
696  * easy to run into problems setting them on Windows (SetFileShortName()
697  * requires SE_RESTORE privilege, which only the Administrator can request, and
698  * also requires DELETE access to the file), failure is ignored unless
699  * WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES is set.  */
700 static int
701 extract_short_name(const tchar *path, struct apply_ctx *ctx,
702                    struct wim_dentry *dentry)
703 {
704         int ret;
705
706         /* The root of the dentry tree being extracted may not be extracted to
707          * its original name, so its short name should be ignored.  */
708         if (dentry == ctx->extract_root)
709                 return 0;
710
711         if (ctx->supported_features.short_names) {
712                 ret = ctx->ops->set_short_name(path,
713                                                dentry->short_name,
714                                                dentry->short_name_nbytes / 2,
715                                                ctx);
716                 if (ret && (ctx->extract_flags &
717                             WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES))
718                 {
719                         ERROR_WITH_ERRNO("Failed to set short name of "
720                                          "\"%"TS"\"", path);
721                         return ret;
722                 }
723         }
724         return 0;
725 }
726
727 /* Set security descriptor, UNIX data, or neither on an extracted file, taking
728  * into account the current extraction mode and flags.  */
729 static int
730 extract_security(const tchar *path, struct apply_ctx *ctx,
731                  struct wim_dentry *dentry)
732 {
733         int ret;
734         struct wim_inode *inode = dentry->d_inode;
735
736         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
737                 return 0;
738
739         if ((ctx->extract_root == dentry) && ctx->root_dentry_is_special)
740                 return 0;
741
742 #ifndef __WIN32__
743         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
744                 struct wimlib_unix_data data;
745
746                 ret = inode_get_unix_data(inode, &data, NULL);
747                 if (ret < 0)
748                         ret = 0;
749                 else if (ret == 0)
750                         ret = ctx->ops->set_unix_data(path, &data, ctx);
751                 if (ret) {
752                         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
753                                 ERROR_WITH_ERRNO("Failed to set UNIX owner, "
754                                                  "group, and/or mode on "
755                                                  "\"%"TS"\"", path);
756                                 return ret;
757                         } else {
758                                 WARNING_WITH_ERRNO("Failed to set UNIX owner, "
759                                                    "group, and/or/mode on "
760                                                    "\"%"TS"\"", path);
761                         }
762                 }
763         }
764         else
765 #endif /* __WIN32__ */
766         if (ctx->supported_features.security_descriptors &&
767             inode->i_security_id != -1)
768         {
769                 const struct wim_security_data *sd;
770                 const u8 *desc;
771                 size_t desc_size;
772
773                 sd = wim_const_security_data(ctx->wim);
774                 desc = sd->descriptors[inode->i_security_id];
775                 desc_size = sd->sizes[inode->i_security_id];
776
777                 ret = ctx->ops->set_security_descriptor(path, desc,
778                                                         desc_size, ctx);
779                 if (ret) {
780                         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
781                                 ERROR_WITH_ERRNO("Failed to set security "
782                                                  "descriptor on \"%"TS"\"", path);
783                                 return ret;
784                         } else {
785                         #if 0
786                                 if (errno != EACCES) {
787                                         WARNING_WITH_ERRNO("Failed to set "
788                                                            "security descriptor "
789                                                            "on \"%"TS"\"", path);
790                                 }
791                         #endif
792                                 ctx->no_security_descriptors++;
793                         }
794                 }
795         }
796         return 0;
797 }
798
799 /* Set timestamps on an extracted file.  Failure is warning-only unless
800  * WIMLIB_EXTRACT_FLAG_STRICT_TIMESTAMPS is set.  */
801 static int
802 extract_timestamps(const tchar *path, struct apply_ctx *ctx,
803                    struct wim_dentry *dentry)
804 {
805         struct wim_inode *inode = dentry->d_inode;
806         int ret;
807
808         if ((ctx->extract_root == dentry) && ctx->root_dentry_is_special)
809                 return 0;
810
811         if (ctx->ops->set_timestamps) {
812                 ret = ctx->ops->set_timestamps(path,
813                                                inode->i_creation_time,
814                                                inode->i_last_write_time,
815                                                inode->i_last_access_time,
816                                                ctx);
817                 if (ret) {
818                         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_TIMESTAMPS) {
819                                 ERROR_WITH_ERRNO("Failed to set timestamps "
820                                                  "on \"%"TS"\"", path);
821                                 return ret;
822                         } else {
823                                 WARNING_WITH_ERRNO("Failed to set timestamps "
824                                                    "on \"%"TS"\"", path);
825                         }
826                 }
827         }
828         return 0;
829 }
830
831 /* Check whether the extraction of a dentry should be skipped completely.  */
832 static bool
833 dentry_is_supported(struct wim_dentry *dentry,
834                     const struct wim_features *supported_features)
835 {
836         struct wim_inode *inode = dentry->d_inode;
837
838         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
839                 return supported_features->reparse_points ||
840                         (inode_is_symlink(inode) &&
841                          supported_features->symlink_reparse_points);
842         }
843         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
844                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
845                         return supported_features->encrypted_directories != 0;
846                 else
847                         return supported_features->encrypted_files != 0;
848         }
849         return true;
850 }
851
852 /* Given a WIM dentry to extract, build the path to which to extract it, in the
853  * format understood by the callbacks in the apply_operations being used.
854  *
855  * Write the resulting path into @path, which must have room for at least
856  * ctx->ops->max_path characters including the null-terminator.
857  *
858  * Return %true if successful; %false if this WIM dentry doesn't actually need
859  * to be extracted or if the calculated path exceeds ctx->ops->max_path
860  * characters.
861  *
862  * This function clobbers the tmp_list member of @dentry and its ancestors up
863  * until the extraction root.  */
864 static bool
865 build_extraction_path(tchar path[], struct wim_dentry *dentry,
866                       struct apply_ctx *ctx)
867 {
868         size_t path_nchars;
869         LIST_HEAD(ancestor_list);
870         tchar *p = path;
871         const tchar *target_prefix;
872         size_t target_prefix_nchars;
873         struct wim_dentry *d;
874
875         if (dentry->extraction_skipped)
876                 return false;
877
878         path_nchars = ctx->ops->path_prefix_nchars;
879
880         if (ctx->ops->requires_realtarget_in_paths) {
881                 target_prefix        = ctx->realtarget;
882                 target_prefix_nchars = ctx->realtarget_nchars;
883         } else if (ctx->ops->requires_target_in_paths) {
884                 target_prefix        = ctx->target;
885                 target_prefix_nchars = ctx->target_nchars;
886         } else {
887                 target_prefix        = NULL;
888                 target_prefix_nchars = 0;
889         }
890         path_nchars += target_prefix_nchars;
891
892         for (d = dentry; d != ctx->extract_root; d = d->parent) {
893                 path_nchars += d->extraction_name_nchars + 1;
894                 list_add(&d->tmp_list, &ancestor_list);
895         }
896
897         path_nchars++; /* null terminator */
898
899         if (path_nchars > ctx->ops->path_max) {
900                 WARNING("\"%"TS"\": Path too long to extract",
901                         dentry_full_path(dentry));
902                 return false;
903         }
904
905         p = tmempcpy(p, ctx->ops->path_prefix, ctx->ops->path_prefix_nchars);
906         p = tmempcpy(p, target_prefix, target_prefix_nchars);
907         list_for_each_entry(d, &ancestor_list, tmp_list) {
908                 *p++ = ctx->ops->path_separator;
909                 p = tmempcpy(p, d->extraction_name, d->extraction_name_nchars);
910         }
911         *p++ = T('\0');
912         wimlib_assert(p - path == path_nchars);
913         return true;
914 }
915
916 static unsigned
917 get_num_path_components(const tchar *path, tchar path_separator)
918 {
919         unsigned num_components = 0;
920 #ifdef __WIN32__
921         /* Ignore drive letter.  */
922         if (path[0] != L'\0' && path[1] == L':')
923                 path += 2;
924 #endif
925
926         while (*path) {
927                 while (*path == path_separator)
928                         path++;
929                 if (*path)
930                         num_components++;
931                 while (*path && *path != path_separator)
932                         path++;
933         }
934         return num_components;
935 }
936
937 static int
938 extract_multiimage_symlink(const tchar *oldpath, const tchar *newpath,
939                            struct apply_ctx *ctx, struct wim_dentry *dentry)
940 {
941         size_t num_raw_path_components;
942         const struct wim_dentry *d;
943         size_t num_target_path_components;
944         tchar *p;
945         const tchar *p_old;
946         int ret;
947
948         num_raw_path_components = 0;
949         for (d = dentry; d != ctx->extract_root; d = d->parent)
950                 num_raw_path_components++;
951
952         if (ctx->ops->requires_realtarget_in_paths)
953                 num_target_path_components = get_num_path_components(ctx->realtarget,
954                                                                      ctx->ops->path_separator);
955         else if (ctx->ops->requires_target_in_paths)
956                 num_target_path_components = get_num_path_components(ctx->target,
957                                                                      ctx->ops->path_separator);
958         else
959                 num_target_path_components = 0;
960
961         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_MULTI_IMAGE) {
962                 wimlib_assert(num_target_path_components > 0);
963                 num_raw_path_components++;
964                 num_target_path_components--;
965         }
966
967         p_old = oldpath + ctx->ops->path_prefix_nchars;
968 #ifdef __WIN32__
969         if (p_old[0] != L'\0' && p_old[1] == ':')
970                 p_old += 2;
971 #endif
972         while (*p_old == ctx->ops->path_separator)
973                 p_old++;
974         while (--num_target_path_components) {
975                 while (*p_old != ctx->ops->path_separator)
976                         p_old++;
977                 while (*p_old == ctx->ops->path_separator)
978                         p_old++;
979         }
980
981         tchar symlink_target[tstrlen(p_old) + 3 * num_raw_path_components + 1];
982
983         p = &symlink_target[0];
984         while (num_raw_path_components--) {
985                 *p++ = '.';
986                 *p++ = '.';
987                 *p++ = ctx->ops->path_separator;
988         }
989         tstrcpy(p, p_old);
990         DEBUG("Creating symlink \"%"TS"\" => \"%"TS"\"",
991               newpath, symlink_target);
992         ret = ctx->ops->create_symlink(symlink_target, newpath, ctx);
993         if (ret) {
994                 ERROR_WITH_ERRNO("Failed to create symlink "
995                                  "\"%"TS"\" => \"%"TS"\"",
996                                  newpath, symlink_target);
997         }
998         return ret;
999 }
1000
1001 /* Create the "skeleton" of an extracted file or directory.  Don't yet extract
1002  * data streams, reparse data (including symbolic links), timestamps, and
1003  * security descriptors.  Basically, everything that doesn't require reading
1004  * non-metadata resources from the WIM file and isn't delayed until the final
1005  * pass.  */
1006 static int
1007 do_dentry_extract_skeleton(tchar path[], struct wim_dentry *dentry,
1008                            struct apply_ctx *ctx)
1009 {
1010         struct wim_inode *inode = dentry->d_inode;
1011         int ret;
1012         const tchar *oldpath;
1013
1014         if (unlikely(is_linked_extraction(ctx))) {
1015                 struct wim_lookup_table_entry *unnamed_lte;
1016
1017                 unnamed_lte = inode_unnamed_lte_resolved(dentry->d_inode);
1018                 if (unnamed_lte && unnamed_lte->extracted_file) {
1019                         oldpath = unnamed_lte->extracted_file;
1020                         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_HARDLINK)
1021                                 goto hardlink;
1022                         else
1023                                 goto symlink;
1024                 }
1025         }
1026
1027         /* Create hard link if this dentry corresponds to an already-extracted
1028          * inode.  */
1029         if (inode->i_extracted_file) {
1030                 oldpath = inode->i_extracted_file;
1031                 goto hardlink;
1032         }
1033
1034         /* Skip symlinks unless they can be extracted as reparse points rather
1035          * than created directly.  */
1036         if (inode_is_symlink(inode) && !ctx->supported_features.reparse_points)
1037                 return 0;
1038
1039         /* Create this file or directory unless it's the extraction root, which
1040          * was already created if necessary.  */
1041         if (dentry != ctx->extract_root) {
1042                 ret = extract_inode(path, ctx, inode);
1043                 if (ret)
1044                         return ret;
1045         }
1046
1047         /* Create empty named data streams.  */
1048         if (can_extract_named_data_streams(ctx)) {
1049                 for (u16 i = 0; i < inode->i_num_ads; i++) {
1050                         file_spec_t file_spec;
1051                         struct wim_ads_entry *entry = &inode->i_ads_entries[i];
1052
1053                         if (!ads_entry_is_named_stream(entry))
1054                                 continue;
1055                         if (entry->lte)
1056                                 continue;
1057                         if (ctx->ops->uses_cookies)
1058                                 file_spec.cookie = inode->extract_cookie;
1059                         else
1060                                 file_spec.path = path;
1061                         ret = ctx->ops->extract_named_stream(file_spec,
1062                                                              entry->stream_name,
1063                                                              entry->stream_name_nbytes / 2,
1064                                                              entry->lte, ctx);
1065                         if (ret) {
1066                                 ERROR_WITH_ERRNO("\"%"TS"\": failed to create "
1067                                                  "empty named data stream",
1068                                                  path);
1069                                 return ret;
1070                         }
1071                 }
1072         }
1073
1074         /* Set file attributes (if supported).  */
1075         ret = extract_file_attributes(path, ctx, dentry, 0);
1076         if (ret)
1077                 return ret;
1078
1079         /* Set or remove file short name (if supported).  */
1080         ret = extract_short_name(path, ctx, dentry);
1081         if (ret)
1082                 return ret;
1083
1084         /* If inode has multiple links and hard links are supported in this
1085          * extraction mode and volume, save the path to the extracted file in
1086          * case it's needed to create a hard link.  */
1087         if (unlikely(is_linked_extraction(ctx))) {
1088                 struct wim_lookup_table_entry *unnamed_lte;
1089
1090                 unnamed_lte = inode_unnamed_lte_resolved(dentry->d_inode);
1091                 if (unnamed_lte) {
1092                         unnamed_lte->extracted_file = TSTRDUP(path);
1093                         if (!unnamed_lte->extracted_file)
1094                                 return WIMLIB_ERR_NOMEM;
1095                 }
1096         } else if (inode->i_nlink > 1 && ctx->supported_features.hard_links) {
1097                 inode->i_extracted_file = TSTRDUP(path);
1098                 if (!inode->i_extracted_file)
1099                         return WIMLIB_ERR_NOMEM;
1100         }
1101         return 0;
1102
1103 symlink:
1104         ret = extract_multiimage_symlink(oldpath, path, ctx, dentry);
1105         if (ret)
1106                 return ret;
1107         dentry->was_hardlinked = 1;
1108         return 0;
1109
1110 hardlink:
1111         ret = extract_hardlink(oldpath, path, ctx);
1112         if (ret)
1113                 return ret;
1114         dentry->was_hardlinked = 1;
1115         return 0;
1116 }
1117
1118 static int
1119 dentry_extract_skeleton(struct wim_dentry *dentry, void *_ctx)
1120 {
1121         struct apply_ctx *ctx = _ctx;
1122         tchar path[ctx->ops->path_max];
1123         struct wim_dentry *orig_dentry;
1124         struct wim_dentry *other_dentry;
1125         int ret;
1126
1127         /* Here we may re-order the extraction of multiple names (hard links)
1128          * for the same file in the same directory in order to ensure the short
1129          * (DOS) name is set correctly.  A short name is always associated with
1130          * exactly one long name, and at least on NTFS, only one long name for a
1131          * file can have a short name associated with it.  (More specifically,
1132          * there can be unlimited names in the POSIX namespace, but only one
1133          * name can be in the Win32+DOS namespace, or one name in the Win32
1134          * namespace with a corresponding name in the DOS namespace.) To ensure
1135          * the short name of a file is associated with the correct long name in
1136          * a directory, we extract the long name with a corresponding short name
1137          * before any additional names.  This can affect NTFS-3g extraction
1138          * (which uses ntfs_set_ntfs_dos_name(), which doesn't allow specifying
1139          * the long name to associate with a short name) and may affect Win32
1140          * extraction as well (which uses SetFileShortName()).  */
1141
1142         if (dentry->skeleton_extracted)
1143                 return 0;
1144         orig_dentry = NULL;
1145         if (ctx->supported_features.short_names
1146             && !dentry_has_short_name(dentry)
1147             && !dentry->d_inode->i_dos_name_extracted)
1148         {
1149                 inode_for_each_dentry(other_dentry, dentry->d_inode) {
1150                         if (dentry_has_short_name(other_dentry)
1151                             && !other_dentry->skeleton_extracted
1152                             && other_dentry->parent == dentry->parent)
1153                         {
1154                                 DEBUG("Creating %"TS" before %"TS" "
1155                                       "to guarantee correct DOS name extraction",
1156                                       dentry_full_path(other_dentry),
1157                                       dentry_full_path(dentry));
1158                                 orig_dentry = dentry;
1159                                 dentry = other_dentry;
1160                                 break;
1161                         }
1162                 }
1163         }
1164 again:
1165         if (!build_extraction_path(path, dentry, ctx))
1166                 return 0;
1167         ret = do_dentry_extract_skeleton(path, dentry, ctx);
1168         if (ret)
1169                 return ret;
1170
1171         dentry->skeleton_extracted = 1;
1172
1173         if (orig_dentry) {
1174                 dentry = orig_dentry;
1175                 orig_dentry = NULL;
1176                 goto again;
1177         }
1178         dentry->d_inode->i_dos_name_extracted = 1;
1179         return 0;
1180 }
1181
1182 /* Create a file or directory, then immediately extract all streams.  This
1183  * assumes that WIMLIB_EXTRACT_FLAG_SEQUENTIAL is not specified, since the WIM
1184  * may not be read sequentially by this function.  */
1185 static int
1186 dentry_extract(struct wim_dentry *dentry, void *_ctx)
1187 {
1188         struct apply_ctx *ctx = _ctx;
1189         tchar path[ctx->ops->path_max];
1190         int ret;
1191
1192         ret = dentry_extract_skeleton(dentry, ctx);
1193         if (ret)
1194                 return ret;
1195
1196         if (!build_extraction_path(path, dentry, ctx))
1197                 return 0;
1198
1199         return extract_streams(path, ctx, dentry, NULL, NULL);
1200 }
1201
1202 /* Extract all instances of the stream @lte that are being extracted in this
1203  * call of extract_tree().  @can_seek specifies whether the WIM file descriptor
1204  * is seekable or not (e.g. is a pipe).  If not and the stream needs to be
1205  * extracted multiple times, it is extracted to a temporary file first.
1206  *
1207  * This is intended for use with sequential extraction of a WIM image
1208  * (WIMLIB_EXTRACT_FLAG_SEQUENTIAL specified).  */
1209 static int
1210 extract_stream_instances(struct wim_lookup_table_entry *lte,
1211                          struct apply_ctx *ctx, bool can_seek)
1212 {
1213         struct wim_dentry **lte_dentries;
1214         struct wim_lookup_table_entry *lte_tmp = NULL;
1215         struct wim_lookup_table_entry *lte_override;
1216         tchar *stream_tmp_filename = NULL;
1217         tchar path[ctx->ops->path_max];
1218         unsigned i;
1219         int ret;
1220
1221         if (lte->out_refcnt <= ARRAY_LEN(lte->inline_lte_dentries))
1222                 lte_dentries = lte->inline_lte_dentries;
1223         else
1224                 lte_dentries = lte->lte_dentries;
1225
1226         if (likely(can_seek || lte->out_refcnt < 2)) {
1227                 lte_override = lte;
1228         } else {
1229                 /* Need to extract stream to temporary file.  */
1230                 struct filedes fd;
1231                 int raw_fd;
1232
1233                 stream_tmp_filename = ttempnam(NULL, T("wimlib"));
1234                 if (!stream_tmp_filename) {
1235                         ERROR_WITH_ERRNO("Failed to create temporary filename");
1236                         ret = WIMLIB_ERR_OPEN;
1237                         goto out;
1238                 }
1239
1240                 lte_tmp = memdup(lte, sizeof(struct wim_lookup_table_entry));
1241                 if (!lte_tmp) {
1242                         ret = WIMLIB_ERR_NOMEM;
1243                         goto out_free_stream_tmp_filename;
1244                 }
1245                 lte_tmp->resource_location = RESOURCE_IN_FILE_ON_DISK;
1246                 lte_tmp->file_on_disk = stream_tmp_filename;
1247                 lte_override = lte_tmp;
1248
1249                 raw_fd = topen(stream_tmp_filename,
1250                                O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0600);
1251                 if (raw_fd < 0) {
1252                         ERROR_WITH_ERRNO("Failed to open temporary file");
1253                         ret = WIMLIB_ERR_OPEN;
1254                         goto out_free_lte_tmp;
1255                 }
1256                 filedes_init(&fd, raw_fd);
1257                 ret = extract_wim_resource_to_fd(lte, &fd,
1258                                                  wim_resource_size(lte));
1259                 if (filedes_close(&fd) && !ret)
1260                         ret = WIMLIB_ERR_WRITE;
1261                 if (ret)
1262                         goto out_unlink_stream_tmp_file;
1263         }
1264
1265         /* Extract all instances of the stream, reading either from the stream
1266          * in the WIM file or from the temporary file containing the stream.
1267          * dentry->tmp_flag is used to ensure that each dentry is processed only
1268          * once regardless of how many times this stream appears in the streams
1269          * of the corresponding inode.  */
1270         for (i = 0; i < lte->out_refcnt; i++) {
1271                 struct wim_dentry *dentry = lte_dentries[i];
1272
1273                 if (dentry->tmp_flag)
1274                         continue;
1275                 if (!build_extraction_path(path, dentry, ctx))
1276                         continue;
1277                 ret = extract_streams(path, ctx, dentry,
1278                                       lte, lte_override);
1279                 if (ret)
1280                         goto out_clear_tmp_flags;
1281                 dentry->tmp_flag = 1;
1282         }
1283         ret = 0;
1284 out_clear_tmp_flags:
1285         for (i = 0; i < lte->out_refcnt; i++)
1286                 lte_dentries[i]->tmp_flag = 0;
1287 out_unlink_stream_tmp_file:
1288         if (stream_tmp_filename)
1289                 tunlink(stream_tmp_filename);
1290 out_free_lte_tmp:
1291         FREE(lte_tmp);
1292 out_free_stream_tmp_filename:
1293         FREE(stream_tmp_filename);
1294 out:
1295         return ret;
1296 }
1297
1298 /* Extracts a list of streams (ctx.stream_list), assuming that the directory
1299  * structure and empty files were already created.  This relies on the
1300  * per-`struct wim_lookup_table_entry' list of dentries that reference each
1301  * stream that was constructed earlier.  Streams are extracted exactly in the
1302  * order of the stream list; however, unless the WIM's file descriptor is
1303  * detected to be non-seekable, streams may be read from the WIM file more than
1304  * one time if multiple copies need to be extracted.  */
1305 static int
1306 extract_stream_list(struct apply_ctx *ctx)
1307 {
1308         struct wim_lookup_table_entry *lte;
1309         bool can_seek;
1310         int ret;
1311
1312         can_seek = (lseek(ctx->wim->in_fd.fd, 0, SEEK_CUR) != -1);
1313         list_for_each_entry(lte, &ctx->stream_list, extraction_list) {
1314                 ret = extract_stream_instances(lte, ctx, can_seek);
1315                 if (ret)
1316                         return ret;
1317         }
1318         return 0;
1319 }
1320
1321 #define PWM_ALLOW_WIM_HDR 0x00001
1322 #define PWM_SILENT_EOF    0x00002
1323
1324 /* Read the header from a stream in a pipable WIM.  */
1325 static int
1326 read_pwm_stream_header(WIMStruct *pwm, struct wim_lookup_table_entry *lte,
1327                        int flags, struct wim_header_disk *hdr_ret)
1328 {
1329         union {
1330                 struct pwm_stream_hdr stream_hdr;
1331                 struct wim_header_disk pwm_hdr;
1332         } buf;
1333         int ret;
1334
1335         ret = full_read(&pwm->in_fd, &buf.stream_hdr, sizeof(buf.stream_hdr));
1336         if (ret)
1337                 goto read_error;
1338
1339         if ((flags & PWM_ALLOW_WIM_HDR) && buf.stream_hdr.magic == PWM_MAGIC) {
1340                 BUILD_BUG_ON(sizeof(buf.pwm_hdr) < sizeof(buf.stream_hdr));
1341                 ret = full_read(&pwm->in_fd, &buf.stream_hdr + 1,
1342                                 sizeof(buf.pwm_hdr) - sizeof(buf.stream_hdr));
1343
1344                 if (ret)
1345                         goto read_error;
1346                 lte->resource_location = RESOURCE_NONEXISTENT;
1347                 memcpy(hdr_ret, &buf.pwm_hdr, sizeof(buf.pwm_hdr));
1348                 return 0;
1349         }
1350
1351         if (buf.stream_hdr.magic != PWM_STREAM_MAGIC) {
1352                 ERROR("Data read on pipe is invalid (expected stream header).");
1353                 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1354         }
1355
1356         lte->resource_entry.original_size = le64_to_cpu(buf.stream_hdr.uncompressed_size);
1357         copy_hash(lte->hash, buf.stream_hdr.hash);
1358         lte->resource_entry.flags = le32_to_cpu(buf.stream_hdr.flags);
1359         lte->resource_entry.offset = pwm->in_fd.offset;
1360         lte->resource_location = RESOURCE_IN_WIM;
1361         lte->wim = pwm;
1362         if (lte->resource_entry.flags & WIM_RESHDR_FLAG_COMPRESSED) {
1363                 lte->compression_type = pwm->compression_type;
1364                 lte->resource_entry.size = 0;
1365         } else {
1366                 lte->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1367                 lte->resource_entry.size = lte->resource_entry.original_size;
1368         }
1369         lte->is_pipable = 1;
1370         return 0;
1371
1372 read_error:
1373         if (ret != WIMLIB_ERR_UNEXPECTED_END_OF_FILE || !(flags & PWM_SILENT_EOF))
1374                 ERROR_WITH_ERRNO("Error reading pipable WIM from pipe");
1375         return ret;
1376 }
1377
1378 /* Skip over an unneeded stream in a pipable WIM being read from a pipe.  */
1379 static int
1380 skip_pwm_stream(struct wim_lookup_table_entry *lte)
1381 {
1382         return read_partial_wim_resource(lte, wim_resource_size(lte),
1383                                          NULL, NULL,
1384                                          WIMLIB_READ_RESOURCE_FLAG_SEEK_ONLY,
1385                                          0);
1386 }
1387
1388 static int
1389 extract_streams_from_pipe(struct apply_ctx *ctx)
1390 {
1391         struct wim_lookup_table_entry *found_lte;
1392         struct wim_lookup_table_entry *needed_lte;
1393         struct wim_lookup_table *lookup_table;
1394         struct wim_header_disk pwm_hdr;
1395         int ret;
1396         int pwm_flags;
1397
1398         ret = WIMLIB_ERR_NOMEM;
1399         found_lte = new_lookup_table_entry();
1400         if (!found_lte)
1401                 goto out;
1402
1403         lookup_table = ctx->wim->lookup_table;
1404         pwm_flags = PWM_ALLOW_WIM_HDR;
1405         if ((ctx->extract_flags & WIMLIB_EXTRACT_FLAG_RESUME))
1406                 pwm_flags |= PWM_SILENT_EOF;
1407         memcpy(ctx->progress.extract.guid, ctx->wim->hdr.guid, WIM_GID_LEN);
1408         ctx->progress.extract.part_number = ctx->wim->hdr.part_number;
1409         ctx->progress.extract.total_parts = ctx->wim->hdr.total_parts;
1410         if (ctx->progress_func)
1411                 ctx->progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_SPWM_PART_BEGIN,
1412                                    &ctx->progress);
1413         while (ctx->num_streams_remaining) {
1414                 ret = read_pwm_stream_header(ctx->wim, found_lte, pwm_flags,
1415                                              &pwm_hdr);
1416                 if (ret) {
1417                         if (ret == WIMLIB_ERR_UNEXPECTED_END_OF_FILE &&
1418                             (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_RESUME))
1419                         {
1420                                 goto resume_done;
1421                         }
1422                         goto out_free_found_lte;
1423                 }
1424
1425                 if ((found_lte->resource_location != RESOURCE_NONEXISTENT)
1426                     && !(found_lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA)
1427                     && (needed_lte = __lookup_resource(lookup_table, found_lte->hash))
1428                     && (needed_lte->out_refcnt))
1429                 {
1430                         copy_resource_entry(&needed_lte->resource_entry,
1431                                             &found_lte->resource_entry);
1432                         needed_lte->resource_location = found_lte->resource_location;
1433                         needed_lte->wim               = found_lte->wim;
1434                         needed_lte->compression_type  = found_lte->compression_type;
1435                         needed_lte->is_pipable        = found_lte->is_pipable;
1436
1437                         ret = extract_stream_instances(needed_lte, ctx, false);
1438                         if (ret)
1439                                 goto out_free_found_lte;
1440                         ctx->num_streams_remaining--;
1441                 } else if (found_lte->resource_location != RESOURCE_NONEXISTENT) {
1442                         ret = skip_pwm_stream(found_lte);
1443                         if (ret)
1444                                 goto out_free_found_lte;
1445                 } else {
1446                         u16 part_number = le16_to_cpu(pwm_hdr.part_number);
1447                         u16 total_parts = le16_to_cpu(pwm_hdr.total_parts);
1448
1449                         if (part_number != ctx->progress.extract.part_number ||
1450                             total_parts != ctx->progress.extract.total_parts ||
1451                             memcmp(pwm_hdr.guid, ctx->progress.extract.guid,
1452                                    WIM_GID_LEN))
1453                         {
1454                                 ctx->progress.extract.part_number = part_number;
1455                                 ctx->progress.extract.total_parts = total_parts;
1456                                 memcpy(ctx->progress.extract.guid,
1457                                        pwm_hdr.guid, WIM_GID_LEN);
1458                                 if (ctx->progress_func) {
1459                                         ctx->progress_func(
1460                                                 WIMLIB_PROGRESS_MSG_EXTRACT_SPWM_PART_BEGIN,
1461                                                            &ctx->progress);
1462                                 }
1463
1464                         }
1465                 }
1466         }
1467         ret = 0;
1468 out_free_found_lte:
1469         free_lookup_table_entry(found_lte);
1470 out:
1471         return ret;
1472
1473 resume_done:
1474         /* TODO */
1475         return 0;
1476 }
1477
1478 /* Finish extracting a file, directory, or symbolic link by setting file
1479  * security and timestamps.  */
1480 static int
1481 dentry_extract_final(struct wim_dentry *dentry, void *_ctx)
1482 {
1483         struct apply_ctx *ctx = _ctx;
1484         int ret;
1485         tchar path[ctx->ops->path_max];
1486
1487         if (!build_extraction_path(path, dentry, ctx))
1488                 return 0;
1489
1490         ret = extract_security(path, ctx, dentry);
1491         if (ret)
1492                 return ret;
1493
1494         if (ctx->ops->requires_final_set_attributes_pass) {
1495                 /* Set file attributes (if supported).  */
1496                 ret = extract_file_attributes(path, ctx, dentry, 1);
1497                 if (ret)
1498                         return ret;
1499         }
1500
1501         return extract_timestamps(path, ctx, dentry);
1502 }
1503
1504 /*
1505  * Extract a WIM dentry to standard output.
1506  *
1507  * This obviously doesn't make sense in all cases.  We return an error if the
1508  * dentry does not correspond to a regular file.  Otherwise we extract the
1509  * unnamed data stream only.
1510  */
1511 static int
1512 extract_dentry_to_stdout(struct wim_dentry *dentry)
1513 {
1514         int ret = 0;
1515         if (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
1516                                              FILE_ATTRIBUTE_DIRECTORY))
1517         {
1518                 ERROR("\"%"TS"\" is not a regular file and therefore cannot be "
1519                       "extracted to standard output", dentry_full_path(dentry));
1520                 ret = WIMLIB_ERR_NOT_A_REGULAR_FILE;
1521         } else {
1522                 struct wim_lookup_table_entry *lte;
1523
1524                 lte = inode_unnamed_lte_resolved(dentry->d_inode);
1525                 if (lte) {
1526                         struct filedes _stdout;
1527                         filedes_init(&_stdout, STDOUT_FILENO);
1528                         ret = extract_wim_resource_to_fd(lte, &_stdout,
1529                                                          wim_resource_size(lte));
1530                 }
1531         }
1532         return ret;
1533 }
1534
1535 #ifdef __WIN32__
1536 static const utf16lechar replacement_char = cpu_to_le16(0xfffd);
1537 #else
1538 static const utf16lechar replacement_char = cpu_to_le16('?');
1539 #endif
1540
1541 static bool
1542 file_name_valid(utf16lechar *name, size_t num_chars, bool fix)
1543 {
1544         size_t i;
1545
1546         if (num_chars == 0)
1547                 return true;
1548         for (i = 0; i < num_chars; i++) {
1549                 switch (name[i]) {
1550         #ifdef __WIN32__
1551                 case cpu_to_le16('\\'):
1552                 case cpu_to_le16(':'):
1553                 case cpu_to_le16('*'):
1554                 case cpu_to_le16('?'):
1555                 case cpu_to_le16('"'):
1556                 case cpu_to_le16('<'):
1557                 case cpu_to_le16('>'):
1558                 case cpu_to_le16('|'):
1559         #endif
1560                 case cpu_to_le16('/'):
1561                 case cpu_to_le16('\0'):
1562                         if (fix)
1563                                 name[i] = replacement_char;
1564                         else
1565                                 return false;
1566                 }
1567         }
1568
1569 #ifdef __WIN32__
1570         if (name[num_chars - 1] == cpu_to_le16(' ') ||
1571             name[num_chars - 1] == cpu_to_le16('.'))
1572         {
1573                 if (fix)
1574                         name[num_chars - 1] = replacement_char;
1575                 else
1576                         return false;
1577         }
1578 #endif
1579         return true;
1580 }
1581
1582 static bool
1583 dentry_is_dot_or_dotdot(const struct wim_dentry *dentry)
1584 {
1585         const utf16lechar *file_name = dentry->file_name;
1586         return file_name != NULL &&
1587                 file_name[0] == cpu_to_le16('.') &&
1588                 (file_name[1] == cpu_to_le16('\0') ||
1589                  (file_name[1] == cpu_to_le16('.') &&
1590                   file_name[2] == cpu_to_le16('\0')));
1591 }
1592
1593 static int
1594 dentry_mark_skipped(struct wim_dentry *dentry, void *_ignore)
1595 {
1596         dentry->extraction_skipped = 1;
1597         return 0;
1598 }
1599
1600 /*
1601  * dentry_calculate_extraction_path-
1602  *
1603  * Calculate the actual filename component at which a WIM dentry will be
1604  * extracted, handling invalid filenames "properly".
1605  *
1606  * dentry->extraction_name usually will be set the same as dentry->file_name (on
1607  * UNIX, converted into the platform's multibyte encoding).  However, if the
1608  * file name contains characters that are not valid on the current platform or
1609  * has some other format that is not valid, leave dentry->extraction_name as
1610  * NULL and set dentry->extraction_skipped to indicate that this dentry should
1611  * not be extracted, unless the appropriate flag
1612  * WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES is set in the extract flags, in
1613  * which case a substitute filename will be created and set instead.
1614  *
1615  * Conflicts with case-insensitive names on Windows are handled similarly; see
1616  * below.
1617  */
1618 static int
1619 dentry_calculate_extraction_path(struct wim_dentry *dentry, void *_args)
1620 {
1621         struct apply_ctx *ctx = _args;
1622         int ret;
1623
1624         if (dentry == ctx->extract_root || dentry->extraction_skipped)
1625                 return 0;
1626
1627         if (!dentry_is_supported(dentry, &ctx->supported_features))
1628                 goto skip_dentry;
1629
1630         if (dentry_is_dot_or_dotdot(dentry)) {
1631                 /* WIM files shouldn't contain . or .. entries.  But if they are
1632                  * there, don't attempt to extract them. */
1633                 WARNING("Skipping extraction of unexpected . or .. file "
1634                         "\"%"TS"\"", dentry_full_path(dentry));
1635                 goto skip_dentry;
1636         }
1637
1638 #ifdef __WIN32__
1639         if (!ctx->ops->supports_case_sensitive_filenames)
1640         {
1641                 struct wim_dentry *other;
1642                 list_for_each_entry(other, &dentry->case_insensitive_conflict_list,
1643                                     case_insensitive_conflict_list)
1644                 {
1645                         if (ctx->extract_flags &
1646                             WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS) {
1647                                 WARNING("\"%"TS"\" has the same "
1648                                         "case-insensitive name as "
1649                                         "\"%"TS"\"; extracting "
1650                                         "dummy name instead",
1651                                         dentry_full_path(dentry),
1652                                         dentry_full_path(other));
1653                                 goto out_replace;
1654                         } else {
1655                                 WARNING("Not extracting \"%"TS"\": "
1656                                         "has same case-insensitive "
1657                                         "name as \"%"TS"\"",
1658                                         dentry_full_path(dentry),
1659                                         dentry_full_path(other));
1660                                 goto skip_dentry;
1661                         }
1662                 }
1663         }
1664 #else   /* __WIN32__ */
1665         wimlib_assert(ctx->ops->supports_case_sensitive_filenames);
1666 #endif  /* !__WIN32__ */
1667
1668         if (file_name_valid(dentry->file_name, dentry->file_name_nbytes / 2, false)) {
1669 #ifdef __WIN32__
1670                 dentry->extraction_name = dentry->file_name;
1671                 dentry->extraction_name_nchars = dentry->file_name_nbytes / 2;
1672                 return 0;
1673 #else
1674                 return utf16le_to_tstr(dentry->file_name,
1675                                        dentry->file_name_nbytes,
1676                                        &dentry->extraction_name,
1677                                        &dentry->extraction_name_nchars);
1678 #endif
1679         } else {
1680                 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES)
1681                 {
1682                         WARNING("\"%"TS"\" has an invalid filename "
1683                                 "that is not supported on this platform; "
1684                                 "extracting dummy name instead",
1685                                 dentry_full_path(dentry));
1686                         goto out_replace;
1687                 } else {
1688                         WARNING("Not extracting \"%"TS"\": has an invalid filename "
1689                                 "that is not supported on this platform",
1690                                 dentry_full_path(dentry));
1691                         goto skip_dentry;
1692                 }
1693         }
1694
1695 out_replace:
1696         {
1697                 utf16lechar utf16_name_copy[dentry->file_name_nbytes / 2];
1698
1699                 memcpy(utf16_name_copy, dentry->file_name, dentry->file_name_nbytes);
1700                 file_name_valid(utf16_name_copy, dentry->file_name_nbytes / 2, true);
1701
1702                 tchar *tchar_name;
1703                 size_t tchar_nchars;
1704         #ifdef __WIN32__
1705                 tchar_name = utf16_name_copy;
1706                 tchar_nchars = dentry->file_name_nbytes / 2;
1707         #else
1708                 ret = utf16le_to_tstr(utf16_name_copy,
1709                                       dentry->file_name_nbytes,
1710                                       &tchar_name, &tchar_nchars);
1711                 if (ret)
1712                         return ret;
1713         #endif
1714                 size_t fixed_name_num_chars = tchar_nchars;
1715                 tchar fixed_name[tchar_nchars + 50];
1716
1717                 tmemcpy(fixed_name, tchar_name, tchar_nchars);
1718                 fixed_name_num_chars += tsprintf(fixed_name + tchar_nchars,
1719                                                  T(" (invalid filename #%lu)"),
1720                                                  ++ctx->invalid_sequence);
1721         #ifndef __WIN32__
1722                 FREE(tchar_name);
1723         #endif
1724                 dentry->extraction_name = memdup(fixed_name,
1725                                                  2 * fixed_name_num_chars + 2);
1726                 if (!dentry->extraction_name)
1727                         return WIMLIB_ERR_NOMEM;
1728                 dentry->extraction_name_nchars = fixed_name_num_chars;
1729         }
1730         return 0;
1731
1732 skip_dentry:
1733         for_dentry_in_tree(dentry, dentry_mark_skipped, NULL);
1734         return 0;
1735 }
1736
1737 /* Clean up dentry and inode structure after extraction.  */
1738 static int
1739 dentry_reset_needs_extraction(struct wim_dentry *dentry, void *_ignore)
1740 {
1741         struct wim_inode *inode = dentry->d_inode;
1742
1743         dentry->extraction_skipped = 0;
1744         dentry->was_hardlinked = 0;
1745         dentry->skeleton_extracted = 0;
1746         inode->i_visited = 0;
1747         FREE(inode->i_extracted_file);
1748         inode->i_extracted_file = NULL;
1749         inode->i_dos_name_extracted = 0;
1750         if ((void*)dentry->extraction_name != (void*)dentry->file_name)
1751                 FREE(dentry->extraction_name);
1752         dentry->extraction_name = NULL;
1753         return 0;
1754 }
1755
1756 /* Tally features necessary to extract a dentry and the corresponding inode.  */
1757 static int
1758 dentry_tally_features(struct wim_dentry *dentry, void *_features)
1759 {
1760         struct wim_features *features = _features;
1761         struct wim_inode *inode = dentry->d_inode;
1762
1763         if (inode->i_attributes & FILE_ATTRIBUTE_ARCHIVE)
1764                 features->archive_files++;
1765         if (inode->i_attributes & FILE_ATTRIBUTE_HIDDEN)
1766                 features->hidden_files++;
1767         if (inode->i_attributes & FILE_ATTRIBUTE_SYSTEM)
1768                 features->system_files++;
1769         if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED)
1770                 features->compressed_files++;
1771         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1772                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1773                         features->encrypted_directories++;
1774                 else
1775                         features->encrypted_files++;
1776         }
1777         if (inode->i_attributes & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED)
1778                 features->not_context_indexed_files++;
1779         if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE)
1780                 features->sparse_files++;
1781         if (inode_has_named_stream(inode))
1782                 features->named_data_streams++;
1783         if (inode->i_visited)
1784                 features->hard_links++;
1785         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1786                 features->reparse_points++;
1787                 if (inode_is_symlink(inode))
1788                         features->symlink_reparse_points++;
1789                 else
1790                         features->other_reparse_points++;
1791         }
1792         if (inode->i_security_id != -1)
1793                 features->security_descriptors++;
1794         if (dentry->short_name_nbytes)
1795                 features->short_names++;
1796         if (inode_has_unix_data(inode))
1797                 features->unix_data++;
1798         inode->i_visited = 1;
1799         return 0;
1800 }
1801
1802 static int
1803 dentry_clear_inode_visited(struct wim_dentry *dentry, void *_ignore)
1804 {
1805         dentry->d_inode->i_visited = 0;
1806         return 0;
1807 }
1808
1809 /* Tally the features necessary to extract a dentry tree.  */
1810 static void
1811 dentry_tree_get_features(struct wim_dentry *root, struct wim_features *features)
1812 {
1813         memset(features, 0, sizeof(struct wim_features));
1814         for_dentry_in_tree(root, dentry_tally_features, features);
1815         for_dentry_in_tree(root, dentry_clear_inode_visited, NULL);
1816 }
1817
1818 static u32
1819 compute_supported_attributes_mask(const struct wim_features *supported_features)
1820 {
1821         u32 mask = ~(u32)0;
1822
1823         if (!supported_features->archive_files)
1824                 mask &= ~FILE_ATTRIBUTE_ARCHIVE;
1825
1826         if (!supported_features->hidden_files)
1827                 mask &= ~FILE_ATTRIBUTE_HIDDEN;
1828
1829         if (!supported_features->system_files)
1830                 mask &= ~FILE_ATTRIBUTE_SYSTEM;
1831
1832         if (!supported_features->not_context_indexed_files)
1833                 mask &= ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
1834
1835         if (!supported_features->compressed_files)
1836                 mask &= ~FILE_ATTRIBUTE_COMPRESSED;
1837
1838         if (!supported_features->sparse_files)
1839                 mask &= ~FILE_ATTRIBUTE_SPARSE_FILE;
1840
1841         if (!supported_features->reparse_points)
1842                 mask &= ~FILE_ATTRIBUTE_REPARSE_POINT;
1843
1844         return mask;
1845 }
1846
1847 static int
1848 do_feature_check(const struct wim_features *required_features,
1849                  const struct wim_features *supported_features,
1850                  int extract_flags,
1851                  const struct apply_operations *ops,
1852                  const tchar *wim_source_path)
1853 {
1854         const tchar *loc;
1855         const tchar *mode = T("this extraction mode");
1856
1857         if (wim_source_path[0] == '\0')
1858                 loc = T("the WIM image");
1859         else
1860                 loc = wim_source_path;
1861
1862         /* We're an archive program, so theoretically we can do what we want
1863          * with FILE_ATTRIBUTE_ARCHIVE (which is a dumb flag anyway).  Don't
1864          * bother the user about it.  */
1865 #if 0
1866         if (required_features->archive_files && !supported_features->archive_files)
1867         {
1868                 WARNING(
1869           "%lu files in %"TS" are marked as archived, but this attribute\n"
1870 "          is not supported in %"TS".",
1871                         required_features->archive_files, loc, mode);
1872         }
1873 #endif
1874
1875         if (required_features->hidden_files && !supported_features->hidden_files)
1876         {
1877                 WARNING(
1878           "%lu files in %"TS" are marked as hidden, but this\n"
1879 "          attribute is not supported in %"TS".",
1880                         required_features->hidden_files, loc, mode);
1881         }
1882
1883         if (required_features->system_files && !supported_features->system_files)
1884         {
1885                 WARNING(
1886           "%lu files in %"TS" are marked as system files,\n"
1887 "          but this attribute is not supported in %"TS".",
1888                         required_features->system_files, loc, mode);
1889         }
1890
1891         if (required_features->compressed_files && !supported_features->compressed_files)
1892         {
1893                 WARNING(
1894           "%lu files in %"TS" are marked as being transparently\n"
1895 "          compressed, but transparent compression is not supported in\n"
1896 "          %"TS".  These files will be extracted as uncompressed.",
1897                         required_features->compressed_files, loc, mode);
1898         }
1899
1900         if (required_features->encrypted_files && !supported_features->encrypted_files)
1901         {
1902                 WARNING(
1903           "%lu files in %"TS" are marked as being encrypted,\n"
1904 "           but encryption is not supported in %"TS".  These files\n"
1905 "           will not be extracted.",
1906                         required_features->encrypted_files, loc, mode);
1907         }
1908
1909         if (required_features->encrypted_directories &&
1910             !supported_features->encrypted_directories)
1911         {
1912                 WARNING(
1913           "%lu directories in %"TS" are marked as being encrypted,\n"
1914 "           but encryption is not supported in %"TS".\n"
1915 "           These directories will be extracted as unencrypted.",
1916                         required_features->encrypted_directories, loc, mode);
1917         }
1918
1919         if (required_features->not_context_indexed_files &&
1920             !supported_features->not_context_indexed_files)
1921         {
1922                 WARNING(
1923           "%lu files in %"TS" are marked as not content indexed,\n"
1924 "          but this attribute is not supported in %"TS".",
1925                         required_features->not_context_indexed_files, loc, mode);
1926         }
1927
1928         if (required_features->sparse_files && !supported_features->sparse_files)
1929         {
1930                 WARNING(
1931           "%lu files in %"TS" are marked as sparse, but creating\n"
1932 "           sparse files is not supported in %"TS".  These files\n"
1933 "           will be extracted as non-sparse.",
1934                         required_features->sparse_files, loc, mode);
1935         }
1936
1937         if (required_features->named_data_streams &&
1938             !supported_features->named_data_streams)
1939         {
1940                 WARNING(
1941           "%lu files in %"TS" contain one or more alternate (named)\n"
1942 "          data streams, which are not supported in %"TS".\n"
1943 "          Alternate data streams will NOT be extracted.",
1944                         required_features->named_data_streams, loc, mode);
1945         }
1946
1947         if (unlikely(extract_flags & (WIMLIB_EXTRACT_FLAG_HARDLINK |
1948                                       WIMLIB_EXTRACT_FLAG_SYMLINK)) &&
1949             required_features->named_data_streams &&
1950             supported_features->named_data_streams)
1951         {
1952                 WARNING(
1953           "%lu files in %"TS" contain one or more alternate (named)\n"
1954 "          data streams, which are not supported in linked extraction mode.\n"
1955 "          Alternate data streams will NOT be extracted.",
1956                         required_features->named_data_streams, loc);
1957         }
1958
1959         if (required_features->hard_links && !supported_features->hard_links)
1960         {
1961                 WARNING(
1962           "%lu files in %"TS" are hard links, but hard links are\n"
1963 "          not supported in %"TS".  Hard links will be extracted as\n"
1964 "          duplicate copies of the linked files.",
1965                         required_features->hard_links, loc, mode);
1966         }
1967
1968         if (required_features->reparse_points && !supported_features->reparse_points)
1969         {
1970                 if (supported_features->symlink_reparse_points) {
1971                         if (required_features->other_reparse_points) {
1972                                 WARNING(
1973           "%lu files in %"TS" are reparse points that are neither\n"
1974 "          symbolic links nor junction points and are not supported in\n"
1975 "          %"TS".  These reparse points will not be extracted.",
1976                                         required_features->other_reparse_points, loc,
1977                                         mode);
1978                         }
1979                 } else {
1980                         WARNING(
1981           "%lu files in %"TS" are reparse points, which are\n"
1982 "          not supported in %"TS" and will not be extracted.",
1983                                 required_features->reparse_points, loc, mode);
1984                 }
1985         }
1986
1987         if (required_features->security_descriptors &&
1988             !supported_features->security_descriptors)
1989         {
1990                 WARNING(
1991           "%lu files in %"TS" have Windows NT security descriptors,\n"
1992 "          but extracting security descriptors is not supported in\n"
1993 "          %"TS".  No security descriptors will be extracted.",
1994                         required_features->security_descriptors, loc, mode);
1995         }
1996
1997         if (required_features->short_names && !supported_features->short_names)
1998         {
1999                 WARNING(
2000           "%lu files in %"TS" have short (DOS) names, but\n"
2001 "          extracting short names is not supported in %"TS".\n"
2002 "          Short names will not be extracted.\n",
2003                         required_features->short_names, loc, mode);
2004         }
2005
2006         if ((extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) &&
2007             required_features->unix_data && !supported_features->unix_data)
2008         {
2009                 ERROR("Extracting UNIX data is not supported in %"TS, mode);
2010                 return WIMLIB_ERR_UNSUPPORTED;
2011         }
2012         if ((extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES) &&
2013             required_features->short_names && !supported_features->short_names)
2014         {
2015                 ERROR("Extracting short names is not supported in %"TS"", mode);
2016                 return WIMLIB_ERR_UNSUPPORTED;
2017         }
2018         if ((extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_TIMESTAMPS) &&
2019             !ops->set_timestamps)
2020         {
2021                 ERROR("Extracting timestamps is not supported in %"TS"", mode);
2022                 return WIMLIB_ERR_UNSUPPORTED;
2023         }
2024         if (((extract_flags & (WIMLIB_EXTRACT_FLAG_STRICT_ACLS |
2025                                WIMLIB_EXTRACT_FLAG_UNIX_DATA))
2026              == WIMLIB_EXTRACT_FLAG_STRICT_ACLS) &&
2027             required_features->security_descriptors &&
2028             !supported_features->security_descriptors)
2029         {
2030                 ERROR("Extracting security descriptors is not supported in %"TS, mode);
2031                 return WIMLIB_ERR_UNSUPPORTED;
2032         }
2033
2034         if ((extract_flags & WIMLIB_EXTRACT_FLAG_HARDLINK) &&
2035             !supported_features->hard_links)
2036         {
2037                 ERROR("Hard link extraction mode requested, but "
2038                       "%"TS" does not support hard links!", mode);
2039                 return WIMLIB_ERR_UNSUPPORTED;
2040         }
2041
2042         if ((extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS) &&
2043             required_features->symlink_reparse_points &&
2044             !(supported_features->symlink_reparse_points ||
2045               supported_features->reparse_points))
2046         {
2047                 ERROR("Extracting symbolic links is not supported in %"TS, mode);
2048                 return WIMLIB_ERR_UNSUPPORTED;
2049         }
2050
2051         if ((extract_flags & WIMLIB_EXTRACT_FLAG_SYMLINK) &&
2052             !supported_features->symlink_reparse_points)
2053         {
2054                 ERROR("Symbolic link extraction mode requested, but "
2055                       "%"TS" does not support symbolic "
2056                       "links!", mode);
2057                 return WIMLIB_ERR_UNSUPPORTED;
2058         }
2059         return 0;
2060 }
2061
2062 static void
2063 do_extract_warnings(struct apply_ctx *ctx)
2064 {
2065         if (ctx->partial_security_descriptors == 0 &&
2066             ctx->no_security_descriptors == 0)
2067                 return;
2068
2069         WARNING("Extraction of \"%"TS"\" complete, but with one or more warnings:",
2070                 ctx->target);
2071         if (ctx->partial_security_descriptors != 0) {
2072                 WARNING("- Could only partially set the security descriptor\n"
2073                         "            on %lu files or directories.",
2074                         ctx->partial_security_descriptors);
2075         }
2076         if (ctx->no_security_descriptors != 0) {
2077                 WARNING("- Could not set security descriptor at all\n"
2078                         "            on %lu files or directories.",
2079                         ctx->no_security_descriptors);
2080         }
2081 #ifdef __WIN32__
2082         WARNING("To fully restore all security descriptors, run the program\n"
2083                 "          with Administrator rights.");
2084 #endif
2085 }
2086
2087 /*
2088  * extract_tree - Extract a file or directory tree from the currently selected
2089  *                WIM image.
2090  *
2091  * @wim:        WIMStruct for the WIM file, with the desired image selected
2092  *              (as wim->current_image).
2093  *
2094  * @wim_source_path:
2095  *              "Canonical" (i.e. no leading or trailing slashes, path
2096  *              separators WIM_PATH_SEPARATOR) path inside the WIM image to
2097  *              extract.  An empty string means the full image.
2098  *
2099  * @target:
2100  *              Filesystem path to extract the file or directory tree to.
2101  *              (Or, with WIMLIB_EXTRACT_FLAG_NTFS: the name of a NTFS volume.)
2102  *
2103  * @extract_flags:
2104  *              WIMLIB_EXTRACT_FLAG_*.  Also, the private flag
2105  *              WIMLIB_EXTRACT_FLAG_MULTI_IMAGE will be set if this is being
2106  *              called through wimlib_extract_image() with WIMLIB_ALL_IMAGES as
2107  *              the image.
2108  *
2109  * @progress_func:
2110  *              If non-NULL, progress function for the extraction.  The messages
2111  *              that may be sent in this function are:
2112  *
2113  *              WIMLIB_PROGRESS_MSG_EXTRACT_TREE_BEGIN or
2114  *                      WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN;
2115  *              WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN;
2116  *              WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_END;
2117  *              WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY;
2118  *              WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS;
2119  *              WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS;
2120  *              WIMLIB_PROGRESS_MSG_EXTRACT_TREE_END or
2121  *                      WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END.
2122  *
2123  * Returns 0 on success; a positive WIMLIB_ERR_* code on failure.
2124  */
2125 static int
2126 extract_tree(WIMStruct *wim, const tchar *wim_source_path, const tchar *target,
2127              int extract_flags, wimlib_progress_func_t progress_func)
2128 {
2129         struct wim_dentry *root;
2130         struct wim_features required_features;
2131         struct apply_ctx ctx;
2132         int ret;
2133         struct wim_lookup_table_entry *lte;
2134
2135         /* Start initializing the apply_ctx.  */
2136         memset(&ctx, 0, sizeof(struct apply_ctx));
2137         ctx.wim = wim;
2138         ctx.extract_flags = extract_flags;
2139         ctx.target = target;
2140         ctx.target_nchars = tstrlen(target);
2141         ctx.progress_func = progress_func;
2142         if (progress_func) {
2143                 ctx.progress.extract.wimfile_name = wim->filename;
2144                 ctx.progress.extract.image = wim->current_image;
2145                 ctx.progress.extract.extract_flags = (extract_flags &
2146                                                       WIMLIB_EXTRACT_MASK_PUBLIC);
2147                 ctx.progress.extract.image_name = wimlib_get_image_name(wim,
2148                                                                         wim->current_image);
2149                 ctx.progress.extract.extract_root_wim_source_path = wim_source_path;
2150                 ctx.progress.extract.target = target;
2151         }
2152         INIT_LIST_HEAD(&ctx.stream_list);
2153
2154         /* Translate the path to extract into the corresponding
2155          * `struct wim_dentry', which will be the root of the
2156          * "dentry tree" to extract.  */
2157         root = get_dentry(wim, wim_source_path);
2158         if (!root) {
2159                 ERROR("Path \"%"TS"\" does not exist in WIM image %d",
2160                       wim_source_path, wim->current_image);
2161                 ret = WIMLIB_ERR_PATH_DOES_NOT_EXIST;
2162                 goto out;
2163         }
2164
2165         ctx.extract_root = root;
2166
2167         /* Select the appropriate apply_operations based on the
2168          * platform and extract_flags.  */
2169 #ifdef __WIN32__
2170         ctx.ops = &win32_apply_ops;
2171 #else
2172         ctx.ops = &unix_apply_ops;
2173 #endif
2174
2175 #ifdef WITH_NTFS_3G
2176         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS)
2177                 ctx.ops = &ntfs_3g_apply_ops;
2178 #endif
2179
2180         /* Call the start_extract() callback.  This gives the apply_operations
2181          * implementation a chance to do any setup needed to access the volume.
2182          * Furthermore, it's expected to set the supported features of this
2183          * extraction mode (ctx.supported_features), which are determined at
2184          * runtime as they may vary depending on the actual volume.  These
2185          * features are then compared with the actual features extracting this
2186          * dentry tree requires.  Some mismatches will merely produce warnings
2187          * and the unsupported data will be ignored; others will produce errors.
2188          */
2189         ret = ctx.ops->start_extract(target, &ctx);
2190         if (ret)
2191                 goto out;
2192
2193         dentry_tree_get_features(root, &required_features);
2194         ret = do_feature_check(&required_features, &ctx.supported_features,
2195                                extract_flags, ctx.ops, wim_source_path);
2196         if (ret)
2197                 goto out_finish_or_abort_extract;
2198
2199         ctx.supported_attributes_mask =
2200                 compute_supported_attributes_mask(&ctx.supported_features);
2201
2202         /* Figure out whether the root dentry is being extracted to the root of
2203          * a volume and therefore needs to be treated "specially", for example
2204          * not being explicitly created and not having attributes set.  */
2205         if (ctx.ops->target_is_root && ctx.ops->root_directory_is_special)
2206                 ctx.root_dentry_is_special = ctx.ops->target_is_root(target);
2207
2208         /* Calculate the actual filename component of each extracted dentry.  In
2209          * the process, set the dentry->extraction_skipped flag on dentries that
2210          * are being skipped for some reason (e.g. invalid filename).  */
2211         ret = for_dentry_in_tree(root, dentry_calculate_extraction_path, &ctx);
2212         if (ret)
2213                 goto out_dentry_reset_needs_extraction;
2214
2215         /* Build the list of the streams that need to be extracted and
2216          * initialize ctx.progress.extract with stream information.  */
2217         ret = for_dentry_in_tree(ctx.extract_root,
2218                                  dentry_resolve_and_zero_lte_refcnt, &ctx);
2219         if (ret)
2220                 goto out_dentry_reset_needs_extraction;
2221
2222         ret = for_dentry_in_tree(ctx.extract_root,
2223                                  dentry_add_streams_to_extract, &ctx);
2224         if (ret)
2225                 goto out_teardown_stream_list;
2226
2227         if (extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE) {
2228                 /* When extracting from a pipe, the number of bytes of data to
2229                  * extract can't be determined in the normal way (examining the
2230                  * lookup table), since at this point all we have is a set of
2231                  * SHA1 message digests of streams that need to be extracted.
2232                  * However, we can get a reasonably accurate estimate by taking
2233                  * <TOTALBYTES> from the corresponding <IMAGE> in the WIM XML
2234                  * data.  This does assume that a full image is being extracted,
2235                  * but currently there is no API for doing otherwise.  (Also,
2236                  * subtract <HARDLINKBYTES> from this if hard links are
2237                  * supported by the extraction mode.)  */
2238                 ctx.progress.extract.total_bytes =
2239                         wim_info_get_image_total_bytes(wim->wim_info,
2240                                                        wim->current_image);
2241                 if (ctx.supported_features.hard_links) {
2242                         ctx.progress.extract.total_bytes -=
2243                                 wim_info_get_image_hard_link_bytes(wim->wim_info,
2244                                                                    wim->current_image);
2245                 }
2246         }
2247
2248         /* Handle the special case of extracting a file to standard
2249          * output.  In that case, "root" should be a single file, not a
2250          * directory tree.  (If not, extract_dentry_to_stdout() will
2251          * return an error.)  */
2252         if (extract_flags & WIMLIB_EXTRACT_FLAG_TO_STDOUT) {
2253                 ret = extract_dentry_to_stdout(root);
2254                 goto out_teardown_stream_list;
2255         }
2256
2257         /* If a sequential extraction was specified, sort the streams to be
2258          * extracted by their position in the WIM file so that the WIM file can
2259          * be read sequentially.  */
2260         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SEQUENTIAL |
2261                               WIMLIB_EXTRACT_FLAG_FROM_PIPE))
2262                                         == WIMLIB_EXTRACT_FLAG_SEQUENTIAL)
2263         {
2264                 ret = sort_stream_list_by_sequential_order(
2265                                 &ctx.stream_list,
2266                                 offsetof(struct wim_lookup_table_entry,
2267                                          extraction_list));
2268                 if (ret)
2269                         goto out_teardown_stream_list;
2270         }
2271
2272         if (ctx.ops->realpath_works_on_nonexisting_files &&
2273             ((extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX) ||
2274              ctx.ops->requires_realtarget_in_paths))
2275         {
2276                 ctx.realtarget = realpath(target, NULL);
2277                 if (!ctx.realtarget) {
2278                         ret = WIMLIB_ERR_NOMEM;
2279                         goto out_teardown_stream_list;
2280                 }
2281                 ctx.realtarget_nchars = tstrlen(ctx.realtarget);
2282         }
2283
2284         if (progress_func) {
2285                 progress_func(*wim_source_path ? WIMLIB_PROGRESS_MSG_EXTRACT_TREE_BEGIN :
2286                                                  WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN,
2287                               &ctx.progress);
2288         }
2289
2290         if (!ctx.root_dentry_is_special)
2291         {
2292                 tchar path[ctx.ops->path_max];
2293                 if (build_extraction_path(path, root, &ctx))
2294                 {
2295                         ret = extract_inode(path, &ctx, root->d_inode);
2296                         if (ret)
2297                                 goto out_free_realtarget;
2298                 }
2299         }
2300
2301         /* If we need to fix up the targets of absolute symbolic links
2302          * (WIMLIB_EXTRACT_FLAG_RPFIX) or the extraction mode requires paths to
2303          * be absolute, use realpath() (or its replacement on Windows) to get
2304          * the absolute path to the extraction target.  Note that this requires
2305          * the target directory to exist, unless
2306          * realpath_works_on_nonexisting_files is set in the apply_operations.
2307          * */
2308         if (!ctx.realtarget &&
2309             (((extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX) &&
2310               required_features.symlink_reparse_points) ||
2311              ctx.ops->requires_realtarget_in_paths))
2312         {
2313                 ctx.realtarget = realpath(target, NULL);
2314                 if (!ctx.realtarget) {
2315                         ret = WIMLIB_ERR_NOMEM;
2316                         goto out_free_realtarget;
2317                 }
2318                 ctx.realtarget_nchars = tstrlen(ctx.realtarget);
2319         }
2320
2321         /* Finally, the important part: extract the tree of files.  */
2322         if (extract_flags & (WIMLIB_EXTRACT_FLAG_SEQUENTIAL |
2323                              WIMLIB_EXTRACT_FLAG_FROM_PIPE)) {
2324                 /* Sequential extraction requested, so two passes are needed
2325                  * (one for directory structure, one for streams.)  */
2326                 if (progress_func)
2327                         progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN,
2328                                       &ctx.progress);
2329
2330                 if (!(extract_flags & WIMLIB_EXTRACT_FLAG_RESUME)) {
2331                         ret = for_dentry_in_tree(root, dentry_extract_skeleton, &ctx);
2332                         if (ret)
2333                                 goto out_free_realtarget;
2334                 }
2335                 if (progress_func)
2336                         progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_END,
2337                                       &ctx.progress);
2338                 if (extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE)
2339                         ret = extract_streams_from_pipe(&ctx);
2340                 else
2341                         ret = extract_stream_list(&ctx);
2342                 if (ret)
2343                         goto out_free_realtarget;
2344         } else {
2345                 /* Sequential extraction was not requested, so we can make do
2346                  * with one pass where we both create the files and extract
2347                  * streams.   */
2348                 if (progress_func)
2349                         progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN,
2350                                       &ctx.progress);
2351                 ret = for_dentry_in_tree(root, dentry_extract, &ctx);
2352                 if (ret)
2353                         goto out_free_realtarget;
2354                 if (progress_func)
2355                         progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_END,
2356                                       &ctx.progress);
2357         }
2358
2359         /* If the total number of bytes to extract was miscalculated, just jump
2360          * to the calculated number in order to avoid confusing the progress
2361          * function.  This should only occur when extracting from a pipe.  */
2362         if (ctx.progress.extract.completed_bytes != ctx.progress.extract.total_bytes)
2363         {
2364                 DEBUG("Calculated %"PRIu64" bytes to extract, but actually "
2365                       "extracted %"PRIu64,
2366                       ctx.progress.extract.total_bytes,
2367                       ctx.progress.extract.completed_bytes);
2368         }
2369         if (progress_func &&
2370             ctx.progress.extract.completed_bytes < ctx.progress.extract.total_bytes)
2371         {
2372                 ctx.progress.extract.completed_bytes = ctx.progress.extract.total_bytes;
2373                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS, &ctx.progress);
2374         }
2375
2376         /* Apply security descriptors and timestamps.  This is done at the end,
2377          * and in a depth-first manner, to prevent timestamps from getting
2378          * changed by subsequent extract operations and to minimize the chance
2379          * of the restored security descriptors getting in our way.  */
2380         if (progress_func)
2381                 progress_func(WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS,
2382                               &ctx.progress);
2383         ret = for_dentry_in_tree_depth(root, dentry_extract_final, &ctx);
2384         if (ret)
2385                 goto out_free_realtarget;
2386
2387         if (progress_func) {
2388                 progress_func(*wim_source_path ? WIMLIB_PROGRESS_MSG_EXTRACT_TREE_END :
2389                               WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END,
2390                               &ctx.progress);
2391         }
2392
2393         do_extract_warnings(&ctx);
2394
2395         ret = 0;
2396 out_free_realtarget:
2397         FREE(ctx.realtarget);
2398 out_teardown_stream_list:
2399         /* Free memory allocated as part of the mapping from each
2400          * wim_lookup_table_entry to the dentries that reference it.  */
2401         if (ctx.extract_flags & WIMLIB_EXTRACT_FLAG_SEQUENTIAL)
2402                 list_for_each_entry(lte, &ctx.stream_list, extraction_list)
2403                         if (lte->out_refcnt > ARRAY_LEN(lte->inline_lte_dentries))
2404                                 FREE(lte->lte_dentries);
2405 out_dentry_reset_needs_extraction:
2406         for_dentry_in_tree(root, dentry_reset_needs_extraction, NULL);
2407 out_finish_or_abort_extract:
2408         if (ret) {
2409                 if (ctx.ops->abort_extract)
2410                         ctx.ops->abort_extract(&ctx);
2411         } else {
2412                 if (ctx.ops->finish_extract)
2413                         ret = ctx.ops->finish_extract(&ctx);
2414         }
2415 out:
2416         return ret;
2417 }
2418
2419 /* Validates a single wimlib_extract_command, mostly checking to make sure the
2420  * extract flags make sense. */
2421 static int
2422 check_extract_command(struct wimlib_extract_command *cmd, int wim_header_flags)
2423 {
2424         int extract_flags;
2425
2426         /* Empty destination path? */
2427         if (cmd->fs_dest_path[0] == T('\0'))
2428                 return WIMLIB_ERR_INVALID_PARAM;
2429
2430         extract_flags = cmd->extract_flags;
2431
2432         /* Check for invalid flag combinations  */
2433         if ((extract_flags &
2434              (WIMLIB_EXTRACT_FLAG_SYMLINK |
2435               WIMLIB_EXTRACT_FLAG_HARDLINK)) == (WIMLIB_EXTRACT_FLAG_SYMLINK |
2436                                                  WIMLIB_EXTRACT_FLAG_HARDLINK))
2437                 return WIMLIB_ERR_INVALID_PARAM;
2438
2439         if ((extract_flags &
2440              (WIMLIB_EXTRACT_FLAG_NO_ACLS |
2441               WIMLIB_EXTRACT_FLAG_STRICT_ACLS)) == (WIMLIB_EXTRACT_FLAG_NO_ACLS |
2442                                                     WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2443                 return WIMLIB_ERR_INVALID_PARAM;
2444
2445         if ((extract_flags &
2446              (WIMLIB_EXTRACT_FLAG_RPFIX |
2447               WIMLIB_EXTRACT_FLAG_NORPFIX)) == (WIMLIB_EXTRACT_FLAG_RPFIX |
2448                                                 WIMLIB_EXTRACT_FLAG_NORPFIX))
2449                 return WIMLIB_ERR_INVALID_PARAM;
2450
2451         if ((extract_flags &
2452              (WIMLIB_EXTRACT_FLAG_RESUME |
2453               WIMLIB_EXTRACT_FLAG_FROM_PIPE)) == WIMLIB_EXTRACT_FLAG_RESUME)
2454                 return WIMLIB_ERR_INVALID_PARAM;
2455
2456         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
2457 #ifndef WITH_NTFS_3G
2458                 ERROR("wimlib was compiled without support for NTFS-3g, so\n"
2459                       "        we cannot apply a WIM image directly to a NTFS volume.");
2460                 return WIMLIB_ERR_UNSUPPORTED;
2461 #endif
2462         }
2463
2464         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_RPFIX |
2465                               WIMLIB_EXTRACT_FLAG_NORPFIX)) == 0)
2466         {
2467                 /* Do reparse point fixups by default if the WIM header says
2468                  * they are enabled and we are extracting a full image. */
2469                 if (wim_header_flags & WIM_HDR_FLAG_RP_FIX)
2470                         extract_flags |= WIMLIB_EXTRACT_FLAG_RPFIX;
2471         }
2472
2473         /* TODO: Since UNIX data entries are stored in the file resources, in a
2474          * completely sequential extraction they may come up before the
2475          * corresponding file or symbolic link data.  This needs to be handled
2476          * better.  */
2477         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_UNIX_DATA |
2478                               WIMLIB_EXTRACT_FLAG_SEQUENTIAL))
2479                                     == (WIMLIB_EXTRACT_FLAG_UNIX_DATA |
2480                                         WIMLIB_EXTRACT_FLAG_SEQUENTIAL))
2481         {
2482                 if (extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE) {
2483                         WARNING("Setting UNIX file/owner group may "
2484                                 "be impossible on some\n"
2485                                 "          symbolic links "
2486                                 "when applying from a pipe.");
2487                 } else {
2488                         extract_flags &= ~WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
2489                         WARNING("Disabling sequential extraction for "
2490                                 "UNIX data mode");
2491                 }
2492         }
2493
2494         cmd->extract_flags = extract_flags;
2495         return 0;
2496 }
2497
2498
2499 /* Internal function to execute extraction commands for a WIM image.  The paths
2500  * in the extract commands are expected to be already "canonicalized".  */
2501 static int
2502 do_wimlib_extract_files(WIMStruct *wim,
2503                         int image,
2504                         struct wimlib_extract_command *cmds,
2505                         size_t num_cmds,
2506                         wimlib_progress_func_t progress_func)
2507 {
2508         int ret;
2509         bool found_link_cmd = false;
2510         bool found_nolink_cmd = false;
2511
2512         /* Select the image from which we are extracting files */
2513         ret = select_wim_image(wim, image);
2514         if (ret)
2515                 return ret;
2516
2517         /* Make sure there are no streams in the WIM that have not been
2518          * checksummed yet.  */
2519         ret = wim_checksum_unhashed_streams(wim);
2520         if (ret)
2521                 return ret;
2522
2523         /* Check for problems with the extraction commands */
2524         for (size_t i = 0; i < num_cmds; i++) {
2525                 ret = check_extract_command(&cmds[i], wim->hdr.flags);
2526                 if (ret)
2527                         return ret;
2528                 if (cmds[i].extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
2529                                              WIMLIB_EXTRACT_FLAG_HARDLINK)) {
2530                         found_link_cmd = true;
2531                 } else {
2532                         found_nolink_cmd = true;
2533                 }
2534                 if (found_link_cmd && found_nolink_cmd) {
2535                         ERROR("Symlink or hardlink extraction mode must "
2536                               "be set on all extraction commands");
2537                         return WIMLIB_ERR_INVALID_PARAM;
2538                 }
2539         }
2540
2541         /* Execute the extraction commands */
2542         for (size_t i = 0; i < num_cmds; i++) {
2543                 ret = extract_tree(wim,
2544                                    cmds[i].wim_source_path,
2545                                    cmds[i].fs_dest_path,
2546                                    cmds[i].extract_flags,
2547                                    progress_func);
2548                 if (ret)
2549                         return ret;
2550         }
2551         return 0;
2552 }
2553
2554 /* API function documented in wimlib.h  */
2555 WIMLIBAPI int
2556 wimlib_extract_files(WIMStruct *wim,
2557                      int image,
2558                      const struct wimlib_extract_command *cmds,
2559                      size_t num_cmds,
2560                      int default_extract_flags,
2561                      WIMStruct **additional_swms,
2562                      unsigned num_additional_swms,
2563                      wimlib_progress_func_t progress_func)
2564 {
2565         int ret;
2566         struct wimlib_extract_command *cmds_copy;
2567         int all_flags = 0;
2568
2569         default_extract_flags &= WIMLIB_EXTRACT_MASK_PUBLIC;
2570
2571         ret = verify_swm_set(wim, additional_swms, num_additional_swms);
2572         if (ret)
2573                 goto out;
2574
2575         if (num_cmds == 0)
2576                 goto out;
2577
2578         if (num_additional_swms)
2579                 merge_lookup_tables(wim, additional_swms, num_additional_swms);
2580
2581         cmds_copy = CALLOC(num_cmds, sizeof(cmds[0]));
2582         if (!cmds_copy) {
2583                 ret = WIMLIB_ERR_NOMEM;
2584                 goto out_restore_lookup_table;
2585         }
2586
2587         for (size_t i = 0; i < num_cmds; i++) {
2588                 cmds_copy[i].extract_flags = (default_extract_flags |
2589                                                  cmds[i].extract_flags)
2590                                                 & WIMLIB_EXTRACT_MASK_PUBLIC;
2591                 all_flags |= cmds_copy[i].extract_flags;
2592
2593                 cmds_copy[i].wim_source_path = canonicalize_wim_path(cmds[i].wim_source_path);
2594                 if (!cmds_copy[i].wim_source_path) {
2595                         ret = WIMLIB_ERR_NOMEM;
2596                         goto out_free_cmds_copy;
2597                 }
2598
2599                 cmds_copy[i].fs_dest_path = canonicalize_fs_path(cmds[i].fs_dest_path);
2600                 if (!cmds_copy[i].fs_dest_path) {
2601                         ret = WIMLIB_ERR_NOMEM;
2602                         goto out_free_cmds_copy;
2603                 }
2604
2605         }
2606         ret = do_wimlib_extract_files(wim, image,
2607                                       cmds_copy, num_cmds,
2608                                       progress_func);
2609
2610         if (all_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
2611                          WIMLIB_EXTRACT_FLAG_HARDLINK))
2612         {
2613                 for_lookup_table_entry(wim->lookup_table,
2614                                        lte_free_extracted_file, NULL);
2615         }
2616 out_free_cmds_copy:
2617         for (size_t i = 0; i < num_cmds; i++) {
2618                 FREE(cmds_copy[i].wim_source_path);
2619                 FREE(cmds_copy[i].fs_dest_path);
2620         }
2621         FREE(cmds_copy);
2622 out_restore_lookup_table:
2623         if (num_additional_swms)
2624                 unmerge_lookup_table(wim);
2625 out:
2626         return ret;
2627 }
2628
2629 /*
2630  * Extracts an image from a WIM file.
2631  *
2632  * @wim:                WIMStruct for the WIM file.
2633  *
2634  * @image:              Number of the single image to extract.
2635  *
2636  * @target:             Directory or NTFS volume to extract the image to.
2637  *
2638  * @extract_flags:      Bitwise or of WIMLIB_EXTRACT_FLAG_*.
2639  *
2640  * @progress_func:      If non-NULL, a progress function to be called
2641  *                      periodically.
2642  *
2643  * Returns 0 on success; nonzero on failure.
2644  */
2645 static int
2646 extract_single_image(WIMStruct *wim, int image,
2647                      const tchar *target, int extract_flags,
2648                      wimlib_progress_func_t progress_func)
2649 {
2650         int ret;
2651         tchar *target_copy = canonicalize_fs_path(target);
2652         if (!target_copy)
2653                 return WIMLIB_ERR_NOMEM;
2654         struct wimlib_extract_command cmd = {
2655                 .wim_source_path = T(""),
2656                 .fs_dest_path = target_copy,
2657                 .extract_flags = extract_flags,
2658         };
2659         ret = do_wimlib_extract_files(wim, image, &cmd, 1, progress_func);
2660         FREE(target_copy);
2661         return ret;
2662 }
2663
2664 static const tchar * const filename_forbidden_chars =
2665 T(
2666 #ifdef __WIN32__
2667 "<>:\"/\\|?*"
2668 #else
2669 "/"
2670 #endif
2671 );
2672
2673 /* This function checks if it is okay to use a WIM image's name as a directory
2674  * name.  */
2675 static bool
2676 image_name_ok_as_dir(const tchar *image_name)
2677 {
2678         return image_name && *image_name &&
2679                 !tstrpbrk(image_name, filename_forbidden_chars) &&
2680                 tstrcmp(image_name, T(".")) &&
2681                 tstrcmp(image_name, T(".."));
2682 }
2683
2684 /* Extracts all images from the WIM to the directory @target, with the images
2685  * placed in subdirectories named by their image names. */
2686 static int
2687 extract_all_images(WIMStruct *wim,
2688                    const tchar *target,
2689                    int extract_flags,
2690                    wimlib_progress_func_t progress_func)
2691 {
2692         size_t image_name_max_len = max(xml_get_max_image_name_len(wim), 20);
2693         size_t output_path_len = tstrlen(target);
2694         tchar buf[output_path_len + 1 + image_name_max_len + 1];
2695         int ret;
2696         int image;
2697         const tchar *image_name;
2698         struct stat stbuf;
2699
2700         extract_flags |= WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
2701
2702         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
2703                 ERROR("Cannot extract multiple images in NTFS extraction mode.");
2704                 return WIMLIB_ERR_INVALID_PARAM;
2705         }
2706
2707         if (tstat(target, &stbuf)) {
2708                 if (errno == ENOENT) {
2709                         if (tmkdir(target, 0755)) {
2710                                 ERROR_WITH_ERRNO("Failed to create directory \"%"TS"\"", target);
2711                                 return WIMLIB_ERR_MKDIR;
2712                         }
2713                 } else {
2714                         ERROR_WITH_ERRNO("Failed to stat \"%"TS"\"", target);
2715                         return WIMLIB_ERR_STAT;
2716                 }
2717         } else if (!S_ISDIR(stbuf.st_mode)) {
2718                 ERROR("\"%"TS"\" is not a directory", target);
2719                 return WIMLIB_ERR_NOTDIR;
2720         }
2721
2722         tmemcpy(buf, target, output_path_len);
2723         buf[output_path_len] = OS_PREFERRED_PATH_SEPARATOR;
2724         for (image = 1; image <= wim->hdr.image_count; image++) {
2725                 image_name = wimlib_get_image_name(wim, image);
2726                 if (image_name_ok_as_dir(image_name)) {
2727                         tstrcpy(buf + output_path_len + 1, image_name);
2728                 } else {
2729                         /* Image name is empty or contains forbidden characters.
2730                          * Use image number instead. */
2731                         tsprintf(buf + output_path_len + 1, T("%d"), image);
2732                 }
2733                 ret = extract_single_image(wim, image, buf, extract_flags,
2734                                            progress_func);
2735                 if (ret)
2736                         return ret;
2737         }
2738         return 0;
2739 }
2740
2741 static int
2742 do_wimlib_extract_image(WIMStruct *wim,
2743                         int image,
2744                         const tchar *target,
2745                         int extract_flags,
2746                         WIMStruct **additional_swms,
2747                         unsigned num_additional_swms,
2748                         wimlib_progress_func_t progress_func)
2749 {
2750         int ret;
2751
2752         if (extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE) {
2753                 wimlib_assert(wim->hdr.part_number == 1);
2754                 wimlib_assert(num_additional_swms == 0);
2755         } else {
2756                 ret = verify_swm_set(wim, additional_swms, num_additional_swms);
2757                 if (ret)
2758                         return ret;
2759
2760                 if (num_additional_swms)
2761                         merge_lookup_tables(wim, additional_swms, num_additional_swms);
2762         }
2763
2764         if (image == WIMLIB_ALL_IMAGES) {
2765                 ret = extract_all_images(wim, target, extract_flags,
2766                                          progress_func);
2767         } else {
2768                 ret = extract_single_image(wim, image, target, extract_flags,
2769                                            progress_func);
2770         }
2771
2772         if (extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
2773                              WIMLIB_EXTRACT_FLAG_HARDLINK))
2774         {
2775                 for_lookup_table_entry(wim->lookup_table,
2776                                        lte_free_extracted_file,
2777                                        NULL);
2778         }
2779         if (num_additional_swms)
2780                 unmerge_lookup_table(wim);
2781         return ret;
2782 }
2783
2784 /* API function documented in wimlib.h  */
2785 WIMLIBAPI int
2786 wimlib_extract_image_from_pipe(int pipe_fd, const tchar *image_num_or_name,
2787                                const tchar *target, int extract_flags,
2788                                wimlib_progress_func_t progress_func)
2789 {
2790         int ret;
2791         WIMStruct *pwm;
2792         struct filedes *in_fd;
2793         int image;
2794         unsigned i;
2795
2796         extract_flags &= WIMLIB_EXTRACT_MASK_PUBLIC;
2797
2798         if (extract_flags & WIMLIB_EXTRACT_FLAG_TO_STDOUT)
2799                 return WIMLIB_ERR_INVALID_PARAM;
2800
2801         extract_flags |= WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
2802
2803         /* Read the WIM header from the pipe and get a WIMStruct to represent
2804          * the pipable WIM.  Caveats:  Unlike getting a WIMStruct with
2805          * wimlib_open_wim(), getting a WIMStruct in this way will result in
2806          * an empty lookup table, no XML data read, and no filename set.  */
2807         ret = open_wim_as_WIMStruct(&pipe_fd,
2808                                     WIMLIB_OPEN_FLAG_FROM_PIPE |
2809                                                 WIMLIB_OPEN_FLAG_SPLIT_OK,
2810                                     &pwm, progress_func);
2811         if (ret)
2812                 return ret;
2813
2814         /* Sanity check to make sure this is a pipable WIM.  */
2815         if (pwm->hdr.magic != PWM_MAGIC) {
2816                 ERROR("The WIM being read from file descriptor %d "
2817                       "is not pipable!", pipe_fd);
2818                 ret = WIMLIB_ERR_NOT_PIPABLE;
2819                 goto out_wimlib_free;
2820         }
2821
2822         /* Sanity check to make sure the first part of a pipable split WIM is
2823          * sent over the pipe first.  */
2824         if (pwm->hdr.part_number != 1) {
2825                 ERROR("The first part of the split WIM must be "
2826                       "sent over the pipe first.");
2827                 ret = WIMLIB_ERR_INVALID_PIPABLE_WIM;
2828                 goto out_wimlib_free;
2829         }
2830
2831         in_fd = &pwm->in_fd;
2832         wimlib_assert(in_fd->offset == WIM_HEADER_DISK_SIZE);
2833
2834         /* As mentioned, the WIMStruct we created from the pipe does not have
2835          * XML data yet.  Fix this by reading the extra copy of the XML data
2836          * that directly follows the header in pipable WIMs.  (Note: see
2837          * write_pipable_wim() for more details about the format of pipable
2838          * WIMs.)  */
2839         {
2840                 struct wim_lookup_table_entry xml_lte;
2841                 ret = read_pwm_stream_header(pwm, &xml_lte, 0, NULL);
2842                 if (ret)
2843                         goto out_wimlib_free;
2844
2845                 if (!(xml_lte.resource_entry.flags & WIM_RESHDR_FLAG_METADATA))
2846                 {
2847                         ERROR("Expected XML data, but found non-metadata "
2848                               "stream.");
2849                         ret = WIMLIB_ERR_INVALID_PIPABLE_WIM;
2850                         goto out_wimlib_free;
2851                 }
2852
2853                 copy_resource_entry(&pwm->hdr.xml_res_entry,
2854                                     &xml_lte.resource_entry);
2855
2856                 ret = read_wim_xml_data(pwm);
2857                 if (ret)
2858                         goto out_wimlib_free;
2859                 if (wim_info_get_num_images(pwm->wim_info) != pwm->hdr.image_count) {
2860                         ERROR("Image count in XML data is not the same as in WIM header.");
2861                         ret = WIMLIB_ERR_XML;
2862                         goto out_wimlib_free;
2863                 }
2864         }
2865
2866         /* Get image index (this may use the XML data that was just read to
2867          * resolve an image name).  */
2868         if (image_num_or_name) {
2869                 image = wimlib_resolve_image(pwm, image_num_or_name);
2870                 if (image == WIMLIB_NO_IMAGE) {
2871                         ERROR("\"%"TS"\" is not a valid image in the pipable WIM!",
2872                               image_num_or_name);
2873                         ret = WIMLIB_ERR_INVALID_IMAGE;
2874                         goto out_wimlib_free;
2875                 } else if (image == WIMLIB_ALL_IMAGES) {
2876                         ERROR("Applying all images from a pipe is not supported.");
2877                         ret = WIMLIB_ERR_INVALID_IMAGE;
2878                         goto out_wimlib_free;
2879                 }
2880         } else {
2881                 if (pwm->hdr.image_count != 1) {
2882                         ERROR("No image was specified, but the pipable WIM "
2883                               "did not contain exactly 1 image");
2884                         ret = WIMLIB_ERR_INVALID_IMAGE;
2885                         goto out_wimlib_free;
2886                 }
2887                 image = 1;
2888         }
2889
2890         /* Load the needed metadata resource.  */
2891         for (i = 1; i <= pwm->hdr.image_count; i++) {
2892                 struct wim_lookup_table_entry *metadata_lte;
2893                 struct wim_image_metadata *imd;
2894
2895                 metadata_lte = new_lookup_table_entry();
2896                 if (!metadata_lte) {
2897                         ret = WIMLIB_ERR_NOMEM;
2898                         goto out_wimlib_free;
2899                 }
2900
2901                 ret = read_pwm_stream_header(pwm, metadata_lte, 0, NULL);
2902                 imd = pwm->image_metadata[i - 1];
2903                 imd->metadata_lte = metadata_lte;
2904                 if (ret)
2905                         goto out_wimlib_free;
2906
2907                 if (!(metadata_lte->resource_entry.flags &
2908                       WIM_RESHDR_FLAG_METADATA))
2909                 {
2910                         ERROR("Expected metadata resource, but found "
2911                               "non-metadata stream.");
2912                         ret = WIMLIB_ERR_INVALID_PIPABLE_WIM;
2913                         goto out_wimlib_free;
2914                 }
2915
2916                 if (i == image) {
2917                         /* Metadata resource is for the images being extracted.
2918                          * Parse it and save the metadata in memory.  */
2919                         ret = read_metadata_resource(pwm, imd);
2920                         if (ret)
2921                                 goto out_wimlib_free;
2922                         imd->modified = 1;
2923                 } else {
2924                         /* Metadata resource is not for the image being
2925                          * extracted.  Skip over it.  */
2926                         ret = skip_pwm_stream(metadata_lte);
2927                         if (ret)
2928                                 goto out_wimlib_free;
2929                 }
2930         }
2931         /* Extract the image.  */
2932         extract_flags |= WIMLIB_EXTRACT_FLAG_FROM_PIPE;
2933         ret = do_wimlib_extract_image(pwm, image, target,
2934                                       extract_flags, NULL, 0, progress_func);
2935         /* Clean up and return.  */
2936 out_wimlib_free:
2937         wimlib_free(pwm);
2938         return ret;
2939 }
2940
2941 /* API function documented in wimlib.h  */
2942 WIMLIBAPI int
2943 wimlib_extract_image(WIMStruct *wim,
2944                      int image,
2945                      const tchar *target,
2946                      int extract_flags,
2947                      WIMStruct **additional_swms,
2948                      unsigned num_additional_swms,
2949                      wimlib_progress_func_t progress_func)
2950 {
2951         extract_flags &= WIMLIB_EXTRACT_MASK_PUBLIC;
2952         return do_wimlib_extract_image(wim, image, target, extract_flags,
2953                                        additional_swms, num_additional_swms,
2954                                        progress_func);
2955 }