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