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