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