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