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