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