]> wimlib.net Git - wimlib/blob - src/extract.c
extract.c: dentry_is_supported(): check all relevant attributes
[wimlib] / src / extract.c
1 /*
2  * extract.c
3  *
4  * Support for extracting WIM images, or files or directories contained in a WIM
5  * image.
6  */
7
8 /*
9  * Copyright (C) 2012, 2013, 2014 Eric Biggers
10  *
11  * This file is free software; you can redistribute it and/or modify it under
12  * the terms of the GNU Lesser General Public License as published by the Free
13  * Software Foundation; either version 3 of the License, or (at your option) any
14  * later version.
15  *
16  * This file is distributed in the hope that it will be useful, but WITHOUT
17  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
19  * details.
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * along with this file; if not, see http://www.gnu.org/licenses/.
23  */
24
25 /*
26  * This file provides the API functions wimlib_extract_image(),
27  * wimlib_extract_image_from_pipe(), wimlib_extract_paths(), and
28  * wimlib_extract_pathlist().  Internally, all end up calling
29  * do_wimlib_extract_paths() and extract_trees().
30  *
31  * Although wimlib supports multiple extraction modes/backends (NTFS-3g, UNIX,
32  * Win32), this file does not itself have code to extract files or directories
33  * to any specific target; instead, it handles generic functionality and relies
34  * on lower-level callback functions declared in `struct apply_operations' to do
35  * the actual extraction.
36  */
37
38 #ifdef HAVE_CONFIG_H
39 #  include "config.h"
40 #endif
41
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <sys/stat.h>
45 #include <unistd.h>
46
47 #include "wimlib/apply.h"
48 #include "wimlib/assert.h"
49 #include "wimlib/dentry.h"
50 #include "wimlib/encoding.h"
51 #include "wimlib/endianness.h"
52 #include "wimlib/error.h"
53 #include "wimlib/lookup_table.h"
54 #include "wimlib/metadata.h"
55 #include "wimlib/pathlist.h"
56 #include "wimlib/paths.h"
57 #include "wimlib/reparse.h"
58 #include "wimlib/resource.h"
59 #include "wimlib/security.h"
60 #include "wimlib/unix_data.h"
61 #ifdef __WIN32__
62 #  include "wimlib/win32.h" /* for realpath() equivalent */
63 #endif
64 #include "wimlib/xml.h"
65 #include "wimlib/wildcard.h"
66 #include "wimlib/wim.h"
67
68 #define WIMLIB_EXTRACT_FLAG_FROM_PIPE   0x80000000
69 #define WIMLIB_EXTRACT_FLAG_IMAGEMODE   0x40000000
70
71 /* Keep in sync with wimlib.h  */
72 #define WIMLIB_EXTRACT_MASK_PUBLIC                              \
73         (WIMLIB_EXTRACT_FLAG_NTFS                       |       \
74          WIMLIB_EXTRACT_FLAG_UNIX_DATA                  |       \
75          WIMLIB_EXTRACT_FLAG_NO_ACLS                    |       \
76          WIMLIB_EXTRACT_FLAG_STRICT_ACLS                |       \
77          WIMLIB_EXTRACT_FLAG_RPFIX                      |       \
78          WIMLIB_EXTRACT_FLAG_NORPFIX                    |       \
79          WIMLIB_EXTRACT_FLAG_TO_STDOUT                  |       \
80          WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES  |       \
81          WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS         |       \
82          WIMLIB_EXTRACT_FLAG_STRICT_TIMESTAMPS          |       \
83          WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES         |       \
84          WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS            |       \
85          WIMLIB_EXTRACT_FLAG_GLOB_PATHS                 |       \
86          WIMLIB_EXTRACT_FLAG_STRICT_GLOB                |       \
87          WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES              |       \
88          WIMLIB_EXTRACT_FLAG_NO_PRESERVE_DIR_STRUCTURE  |       \
89          WIMLIB_EXTRACT_FLAG_WIMBOOT)
90
91 /* Send WIMLIB_PROGRESS_MSG_EXTRACT_FILE_STRUCTURE or
92  * WIMLIB_PROGRESS_MSG_EXTRACT_METADATA.  */
93 int
94 do_file_extract_progress(struct apply_ctx *ctx, enum wimlib_progress_msg msg)
95 {
96         ctx->count_until_file_progress = 500;  /* Arbitrary value to limit calls  */
97         return extract_progress(ctx, msg);
98 }
99
100 static int
101 start_file_phase(struct apply_ctx *ctx, uint64_t end_file_count, enum wimlib_progress_msg msg)
102 {
103         ctx->progress.extract.current_file_count = 0;
104         ctx->progress.extract.end_file_count = end_file_count;
105         return do_file_extract_progress(ctx, msg);
106 }
107
108 int
109 start_file_structure_phase(struct apply_ctx *ctx, uint64_t end_file_count)
110 {
111         return start_file_phase(ctx, end_file_count, WIMLIB_PROGRESS_MSG_EXTRACT_FILE_STRUCTURE);
112 }
113
114 int
115 start_file_metadata_phase(struct apply_ctx *ctx, uint64_t end_file_count)
116 {
117         return start_file_phase(ctx, end_file_count, WIMLIB_PROGRESS_MSG_EXTRACT_METADATA);
118 }
119
120 static int
121 end_file_phase(struct apply_ctx *ctx, enum wimlib_progress_msg msg)
122 {
123         ctx->progress.extract.current_file_count = ctx->progress.extract.end_file_count;
124         return do_file_extract_progress(ctx, msg);
125 }
126
127 int
128 end_file_structure_phase(struct apply_ctx *ctx)
129 {
130         return end_file_phase(ctx, WIMLIB_PROGRESS_MSG_EXTRACT_FILE_STRUCTURE);
131 }
132
133 int
134 end_file_metadata_phase(struct apply_ctx *ctx)
135 {
136         return end_file_phase(ctx, WIMLIB_PROGRESS_MSG_EXTRACT_METADATA);
137 }
138
139 /* Check whether the extraction of a dentry should be skipped completely.  */
140 static bool
141 dentry_is_supported(struct wim_dentry *dentry,
142                     const struct wim_features *supported_features)
143 {
144         struct wim_inode *inode = dentry->d_inode;
145
146         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
147                 if (!(supported_features->reparse_points ||
148                       (inode_is_symlink(inode) &&
149                        supported_features->symlink_reparse_points)))
150                         return false;
151         }
152
153         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
154                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
155                         if (!supported_features->encrypted_directories)
156                                 return false;
157                 } else {
158                         if (!supported_features->encrypted_files)
159                                 return false;
160                 }
161         }
162
163         return true;
164 }
165
166
167 #define PWM_ALLOW_WIM_HDR 0x00001
168
169 /* Read the header from a stream in a pipable WIM.  */
170 static int
171 read_pwm_stream_header(WIMStruct *pwm, struct wim_lookup_table_entry *lte,
172                        struct wim_resource_spec *rspec,
173                        int flags, struct wim_header_disk *hdr_ret)
174 {
175         union {
176                 struct pwm_stream_hdr stream_hdr;
177                 struct wim_header_disk pwm_hdr;
178         } buf;
179         struct wim_reshdr reshdr;
180         int ret;
181
182         ret = full_read(&pwm->in_fd, &buf.stream_hdr, sizeof(buf.stream_hdr));
183         if (ret)
184                 goto read_error;
185
186         if ((flags & PWM_ALLOW_WIM_HDR) &&
187             le64_to_cpu(buf.stream_hdr.magic) == PWM_MAGIC)
188         {
189                 BUILD_BUG_ON(sizeof(buf.pwm_hdr) < sizeof(buf.stream_hdr));
190                 ret = full_read(&pwm->in_fd, &buf.stream_hdr + 1,
191                                 sizeof(buf.pwm_hdr) - sizeof(buf.stream_hdr));
192
193                 if (ret)
194                         goto read_error;
195                 lte->resource_location = RESOURCE_NONEXISTENT;
196                 memcpy(hdr_ret, &buf.pwm_hdr, sizeof(buf.pwm_hdr));
197                 return 0;
198         }
199
200         if (le64_to_cpu(buf.stream_hdr.magic) != PWM_STREAM_MAGIC) {
201                 ERROR("Data read on pipe is invalid (expected stream header).");
202                 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
203         }
204
205         copy_hash(lte->hash, buf.stream_hdr.hash);
206
207         reshdr.size_in_wim = 0;
208         reshdr.flags = le32_to_cpu(buf.stream_hdr.flags);
209         reshdr.offset_in_wim = pwm->in_fd.offset;
210         reshdr.uncompressed_size = le64_to_cpu(buf.stream_hdr.uncompressed_size);
211         wim_res_hdr_to_spec(&reshdr, pwm, rspec);
212         lte_bind_wim_resource_spec(lte, rspec);
213         lte->flags = rspec->flags;
214         lte->size = rspec->uncompressed_size;
215         lte->offset_in_res = 0;
216         return 0;
217
218 read_error:
219         ERROR_WITH_ERRNO("Error reading pipable WIM from pipe");
220         return ret;
221 }
222
223 static int
224 load_streams_from_pipe(struct apply_ctx *ctx,
225                        const struct read_stream_list_callbacks *cbs)
226 {
227         struct wim_lookup_table_entry *found_lte = NULL;
228         struct wim_resource_spec *rspec = NULL;
229         struct wim_lookup_table *lookup_table;
230         int ret;
231
232         ret = WIMLIB_ERR_NOMEM;
233         found_lte = new_lookup_table_entry();
234         if (!found_lte)
235                 goto out;
236
237         rspec = MALLOC(sizeof(struct wim_resource_spec));
238         if (!rspec)
239                 goto out;
240
241         lookup_table = ctx->wim->lookup_table;
242         memcpy(ctx->progress.extract.guid, ctx->wim->hdr.guid, WIM_GUID_LEN);
243         ctx->progress.extract.part_number = ctx->wim->hdr.part_number;
244         ctx->progress.extract.total_parts = ctx->wim->hdr.total_parts;
245         ret = extract_progress(ctx, WIMLIB_PROGRESS_MSG_EXTRACT_SPWM_PART_BEGIN);
246         if (ret)
247                 goto out;
248
249         while (ctx->num_streams_remaining) {
250                 struct wim_header_disk pwm_hdr;
251                 struct wim_lookup_table_entry *needed_lte;
252
253                 if (found_lte->resource_location != RESOURCE_NONEXISTENT)
254                         lte_unbind_wim_resource_spec(found_lte);
255                 ret = read_pwm_stream_header(ctx->wim, found_lte, rspec,
256                                              PWM_ALLOW_WIM_HDR, &pwm_hdr);
257                 if (ret)
258                         goto out;
259
260                 if ((found_lte->resource_location != RESOURCE_NONEXISTENT)
261                     && !(found_lte->flags & WIM_RESHDR_FLAG_METADATA)
262                     && (needed_lte = lookup_stream(lookup_table, found_lte->hash))
263                     && (needed_lte->out_refcnt))
264                 {
265                         needed_lte->offset_in_res = found_lte->offset_in_res;
266                         needed_lte->flags = found_lte->flags;
267                         needed_lte->size = found_lte->size;
268
269                         lte_unbind_wim_resource_spec(found_lte);
270                         lte_bind_wim_resource_spec(needed_lte, rspec);
271
272                         ret = (*cbs->begin_stream)(needed_lte,
273                                                    cbs->begin_stream_ctx);
274                         if (ret) {
275                                 lte_unbind_wim_resource_spec(needed_lte);
276                                 goto out;
277                         }
278
279                         ret = extract_stream(needed_lte, needed_lte->size,
280                                              cbs->consume_chunk,
281                                              cbs->consume_chunk_ctx);
282
283                         ret = (*cbs->end_stream)(needed_lte, ret,
284                                                  cbs->end_stream_ctx);
285                         lte_unbind_wim_resource_spec(needed_lte);
286                         if (ret)
287                                 goto out;
288                         ctx->num_streams_remaining--;
289                 } else if (found_lte->resource_location != RESOURCE_NONEXISTENT) {
290                         ret = skip_wim_stream(found_lte);
291                         if (ret)
292                                 goto out;
293                 } else {
294                         u16 part_number = le16_to_cpu(pwm_hdr.part_number);
295                         u16 total_parts = le16_to_cpu(pwm_hdr.total_parts);
296
297                         if (part_number != ctx->progress.extract.part_number ||
298                             total_parts != ctx->progress.extract.total_parts ||
299                             memcmp(pwm_hdr.guid, ctx->progress.extract.guid,
300                                    WIM_GUID_LEN))
301                         {
302                                 ctx->progress.extract.part_number = part_number;
303                                 ctx->progress.extract.total_parts = total_parts;
304                                 memcpy(ctx->progress.extract.guid,
305                                        pwm_hdr.guid, WIM_GUID_LEN);
306                                 ret = extract_progress(ctx,
307                                                        WIMLIB_PROGRESS_MSG_EXTRACT_SPWM_PART_BEGIN);
308                                 if (ret)
309                                         goto out;
310                         }
311                 }
312         }
313         ret = 0;
314 out:
315         if (found_lte && found_lte->resource_location != RESOURCE_IN_WIM)
316                 FREE(rspec);
317         free_lookup_table_entry(found_lte);
318         return ret;
319 }
320
321 /* Creates a temporary file opened for writing.  The open file descriptor is
322  * returned in @fd_ret and its name is returned in @name_ret (dynamically
323  * allocated).  */
324 static int
325 create_temporary_file(struct filedes *fd_ret, tchar **name_ret)
326 {
327         tchar *name;
328         int open_flags;
329         int raw_fd;
330
331 retry:
332         name = ttempnam(NULL, T("wimlib"));
333         if (!name) {
334                 ERROR_WITH_ERRNO("Failed to create temporary filename");
335                 return WIMLIB_ERR_NOMEM;
336         }
337
338         open_flags = O_WRONLY | O_CREAT | O_EXCL | O_BINARY;
339 #ifdef __WIN32__
340         open_flags |= _O_SHORT_LIVED;
341 #endif
342         raw_fd = topen(name, open_flags, 0600);
343
344         if (raw_fd < 0) {
345                 if (errno == EEXIST) {
346                         FREE(name);
347                         goto retry;
348                 }
349                 ERROR_WITH_ERRNO("Failed to create temporary file "
350                                  "\"%"TS"\"", name);
351                 FREE(name);
352                 return WIMLIB_ERR_OPEN;
353         }
354
355         filedes_init(fd_ret, raw_fd);
356         *name_ret = name;
357         return 0;
358 }
359
360 static int
361 begin_extract_stream_wrapper(struct wim_lookup_table_entry *lte, void *_ctx)
362 {
363         struct apply_ctx *ctx = _ctx;
364
365         ctx->cur_stream = lte;
366         ctx->cur_stream_offset = 0;
367
368         if (unlikely(lte->out_refcnt > MAX_OPEN_STREAMS))
369                 return create_temporary_file(&ctx->tmpfile_fd, &ctx->tmpfile_name);
370         else
371                 return (*ctx->saved_cbs->begin_stream)(lte, ctx->saved_cbs->begin_stream_ctx);
372 }
373
374 static int
375 extract_chunk_wrapper(const void *chunk, size_t size, void *_ctx)
376 {
377         struct apply_ctx *ctx = _ctx;
378         union wimlib_progress_info *progress = &ctx->progress;
379         int ret;
380
381         ctx->cur_stream_offset += size;
382
383         if (likely(ctx->supported_features.hard_links)) {
384                 progress->extract.completed_bytes +=
385                         (u64)size * ctx->cur_stream->out_refcnt;
386                 if (ctx->cur_stream_offset == ctx->cur_stream->size)
387                         progress->extract.completed_streams += ctx->cur_stream->out_refcnt;
388         } else {
389                 const struct stream_owner *owners = stream_owners(ctx->cur_stream);
390                 for (u32 i = 0; i < ctx->cur_stream->out_refcnt; i++) {
391                         const struct wim_inode *inode = owners[i].inode;
392                         const struct wim_dentry *dentry;
393
394                         list_for_each_entry(dentry,
395                                             &inode->i_extraction_aliases,
396                                             d_extraction_alias_node)
397                         {
398                                 progress->extract.completed_bytes += size;
399                                 if (ctx->cur_stream_offset == ctx->cur_stream->size)
400                                         progress->extract.completed_streams++;
401                         }
402                 }
403         }
404         if (progress->extract.completed_bytes >= ctx->next_progress) {
405
406                 ret = extract_progress(ctx, WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS);
407                 if (ret)
408                         return ret;
409
410                 if (progress->extract.completed_bytes >=
411                     progress->extract.total_bytes)
412                 {
413                         ctx->next_progress = UINT64_MAX;
414                 } else {
415                         /* Send new message as soon as another 1/128 of the
416                          * total has been extracted.  (Arbitrary number.)  */
417                         ctx->next_progress =
418                                 progress->extract.completed_bytes +
419                                         progress->extract.total_bytes / 128;
420
421                         /* ... Unless that would be more than 5000000 bytes, in
422                          * which case send the next after the next 5000000
423                          * bytes.  (Another arbitrary number.)  */
424                         if (progress->extract.completed_bytes + 5000000 <
425                             ctx->next_progress)
426                                 ctx->next_progress =
427                                         progress->extract.completed_bytes + 5000000;
428
429                         /* ... But always send a message as soon as we're
430                          * completely done.  */
431                         if (progress->extract.total_bytes < ctx->next_progress)
432                                 ctx->next_progress = progress->extract.total_bytes;
433                 }
434         }
435
436         if (unlikely(filedes_valid(&ctx->tmpfile_fd))) {
437                 /* Just extracting to temporary file for now.  */
438                 ret = full_write(&ctx->tmpfile_fd, chunk, size);
439                 if (ret) {
440                         ERROR_WITH_ERRNO("Error writing data to "
441                                          "temporary file \"%"TS"\"",
442                                          ctx->tmpfile_name);
443                 }
444                 return ret;
445         } else {
446                 return (*ctx->saved_cbs->consume_chunk)(chunk, size,
447                                                         ctx->saved_cbs->consume_chunk_ctx);
448         }
449 }
450
451 static int
452 extract_from_tmpfile(const tchar *tmpfile_name, struct apply_ctx *ctx)
453 {
454         struct wim_lookup_table_entry tmpfile_lte;
455         struct wim_lookup_table_entry *orig_lte = ctx->cur_stream;
456         const struct read_stream_list_callbacks *cbs = ctx->saved_cbs;
457         int ret;
458         const u32 orig_refcnt = orig_lte->out_refcnt;
459
460         BUILD_BUG_ON(MAX_OPEN_STREAMS < ARRAY_LEN(orig_lte->inline_stream_owners));
461
462         struct stream_owner *owners = orig_lte->stream_owners;
463
464         /* Copy the stream's data from the temporary file to each of its
465          * destinations.
466          *
467          * This is executed only in the very uncommon case that a
468          * single-instance stream is being extracted to more than
469          * MAX_OPEN_STREAMS locations!  */
470
471         memcpy(&tmpfile_lte, orig_lte, sizeof(struct wim_lookup_table_entry));
472         tmpfile_lte.resource_location = RESOURCE_IN_FILE_ON_DISK;
473         tmpfile_lte.file_on_disk = ctx->tmpfile_name;
474         ret = 0;
475         for (u32 i = 0; i < orig_refcnt; i++) {
476
477                 /* Note: it usually doesn't matter whether we pass the original
478                  * stream entry to callbacks provided by the extraction backend
479                  * as opposed to the tmpfile stream entry, since they shouldn't
480                  * actually read data from the stream other than through the
481                  * read_stream_prefix() call below.  But for
482                  * WIMLIB_EXTRACT_FLAG_WIMBOOT mode on Windows it does matter
483                  * because it needs the original stream location in order to
484                  * create the external backing reference.  */
485
486                 orig_lte->out_refcnt = 1;
487                 orig_lte->inline_stream_owners[0] = owners[i];
488
489                 ret = (*cbs->begin_stream)(orig_lte, cbs->begin_stream_ctx);
490                 if (ret)
491                         break;
492
493                 /* Extra SHA-1 isn't necessary here, but it shouldn't hurt as
494                  * this case is very rare anyway.  */
495                 ret = extract_stream(&tmpfile_lte, tmpfile_lte.size,
496                                      cbs->consume_chunk,
497                                      cbs->consume_chunk_ctx);
498
499                 ret = (*cbs->end_stream)(orig_lte, ret, cbs->end_stream_ctx);
500                 if (ret)
501                         break;
502         }
503         FREE(owners);
504         orig_lte->out_refcnt = 0;
505         return ret;
506 }
507
508 static int
509 end_extract_stream_wrapper(struct wim_lookup_table_entry *stream,
510                            int status, void *_ctx)
511 {
512         struct apply_ctx *ctx = _ctx;
513
514         if (unlikely(filedes_valid(&ctx->tmpfile_fd))) {
515                 filedes_close(&ctx->tmpfile_fd);
516                 if (!status)
517                         status = extract_from_tmpfile(ctx->tmpfile_name, ctx);
518                 filedes_invalidate(&ctx->tmpfile_fd);
519                 tunlink(ctx->tmpfile_name);
520                 FREE(ctx->tmpfile_name);
521                 return status;
522         } else {
523                 return (*ctx->saved_cbs->end_stream)(stream, status,
524                                                      ctx->saved_cbs->end_stream_ctx);
525         }
526 }
527
528 /*
529  * Read the list of single-instance streams to extract and feed their data into
530  * the specified callback functions.
531  *
532  * This handles checksumming each stream.
533  *
534  * This also handles sending WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS.
535  *
536  * This also works if the WIM is being read from a pipe, whereas attempting to
537  * read streams directly (e.g. with read_full_stream_into_buf()) will not.
538  *
539  * This also will split up streams that will need to be extracted to more than
540  * MAX_OPEN_STREAMS locations, as measured by the 'out_refcnt' of each stream.
541  * Therefore, the apply_operations implementation need not worry about running
542  * out of file descriptors, unless it might open more than one file descriptor
543  * per nominal destination (e.g. Win32 currently might because the destination
544  * file system might not support hard links).
545  */
546 int
547 extract_stream_list(struct apply_ctx *ctx,
548                     const struct read_stream_list_callbacks *cbs)
549 {
550         struct read_stream_list_callbacks wrapper_cbs = {
551                 .begin_stream      = begin_extract_stream_wrapper,
552                 .begin_stream_ctx  = ctx,
553                 .consume_chunk     = extract_chunk_wrapper,
554                 .consume_chunk_ctx = ctx,
555                 .end_stream        = end_extract_stream_wrapper,
556                 .end_stream_ctx    = ctx,
557         };
558         ctx->saved_cbs = cbs;
559         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE) {
560                 return load_streams_from_pipe(ctx, &wrapper_cbs);
561         } else {
562                 return read_stream_list(&ctx->stream_list,
563                                         offsetof(struct wim_lookup_table_entry,
564                                                  extraction_list),
565                                         &wrapper_cbs, VERIFY_STREAM_HASHES);
566         }
567 }
568
569 /* Extract a WIM dentry to standard output.
570  *
571  * This obviously doesn't make sense in all cases.  We return an error if the
572  * dentry does not correspond to a regular file.  Otherwise we extract the
573  * unnamed data stream only.  */
574 static int
575 extract_dentry_to_stdout(struct wim_dentry *dentry,
576                          const struct wim_lookup_table *lookup_table)
577 {
578         struct wim_inode *inode = dentry->d_inode;
579         struct wim_lookup_table_entry *lte;
580         struct filedes _stdout;
581
582         if (inode->i_attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
583                                    FILE_ATTRIBUTE_DIRECTORY))
584         {
585                 ERROR("\"%"TS"\" is not a regular file and therefore cannot be "
586                       "extracted to standard output", dentry_full_path(dentry));
587                 return WIMLIB_ERR_NOT_A_REGULAR_FILE;
588         }
589
590         lte = inode_unnamed_lte(inode, lookup_table);
591         if (!lte) {
592                 const u8 *hash = inode_unnamed_stream_hash(inode);
593                 if (!is_zero_hash(hash))
594                         return stream_not_found_error(inode, hash);
595                 return 0;
596         }
597
598         filedes_init(&_stdout, STDOUT_FILENO);
599         return extract_full_stream_to_fd(lte, &_stdout);
600 }
601
602 static int
603 extract_dentries_to_stdout(struct wim_dentry **dentries, size_t num_dentries,
604                            const struct wim_lookup_table *lookup_table)
605 {
606         for (size_t i = 0; i < num_dentries; i++) {
607                 int ret = extract_dentry_to_stdout(dentries[i], lookup_table);
608                 if (ret)
609                         return ret;
610         }
611         return 0;
612 }
613
614 /**********************************************************************/
615
616 /*
617  * Removes duplicate dentries from the array.
618  *
619  * Returns the new number of dentries, packed at the front of the array.
620  */
621 static size_t
622 remove_duplicate_trees(struct wim_dentry **trees, size_t num_trees)
623 {
624         size_t i, j = 0;
625         for (i = 0; i < num_trees; i++) {
626                 if (!trees[i]->tmp_flag) {
627                         /* Found distinct dentry.  */
628                         trees[i]->tmp_flag = 1;
629                         trees[j++] = trees[i];
630                 }
631         }
632         for (i = 0; i < j; i++)
633                 trees[i]->tmp_flag = 0;
634         return j;
635 }
636
637 /*
638  * Remove dentries that are descendants of other dentries in the array.
639  *
640  * Returns the new number of dentries, packed at the front of the array.
641  */
642 static size_t
643 remove_contained_trees(struct wim_dentry **trees, size_t num_trees)
644 {
645         size_t i, j = 0;
646         for (i = 0; i < num_trees; i++)
647                 trees[i]->tmp_flag = 1;
648         for (i = 0; i < num_trees; i++) {
649                 struct wim_dentry *d = trees[i];
650                 while (!dentry_is_root(d)) {
651                         d = d->d_parent;
652                         if (d->tmp_flag)
653                                 goto tree_contained;
654                 }
655                 trees[j++] = trees[i];
656                 continue;
657
658         tree_contained:
659                 trees[i]->tmp_flag = 0;
660         }
661
662         for (i = 0; i < j; i++)
663                 trees[i]->tmp_flag = 0;
664         return j;
665 }
666
667 static int
668 dentry_append_to_list(struct wim_dentry *dentry, void *_dentry_list)
669 {
670         struct list_head *dentry_list = _dentry_list;
671         list_add_tail(&dentry->d_extraction_list_node, dentry_list);
672         return 0;
673 }
674
675 static void
676 dentry_reset_extraction_list_node(struct wim_dentry *dentry)
677 {
678         dentry->d_extraction_list_node = (struct list_head){NULL, NULL};
679 }
680
681 static int
682 dentry_delete_from_list(struct wim_dentry *dentry, void *_ignore)
683 {
684         list_del(&dentry->d_extraction_list_node);
685         dentry_reset_extraction_list_node(dentry);
686         return 0;
687 }
688
689 /*
690  * Build the preliminary list of dentries to be extracted.
691  *
692  * The list maintains the invariant that if d1 and d2 are in the list and d1 is
693  * an ancestor of d2, then d1 appears before d2 in the list.
694  */
695 static void
696 build_dentry_list(struct list_head *dentry_list, struct wim_dentry **trees,
697                   size_t num_trees, bool add_ancestors)
698 {
699         INIT_LIST_HEAD(dentry_list);
700
701         /* Add the trees recursively.  */
702         for (size_t i = 0; i < num_trees; i++)
703                 for_dentry_in_tree(trees[i], dentry_append_to_list, dentry_list);
704
705         /* If requested, add ancestors of the trees.  */
706         if (add_ancestors) {
707                 for (size_t i = 0; i < num_trees; i++) {
708                         struct wim_dentry *dentry = trees[i];
709                         struct wim_dentry *ancestor;
710                         struct list_head *place_after;
711
712                         if (dentry_is_root(dentry))
713                                 continue;
714
715                         place_after = dentry_list;
716                         ancestor = dentry;
717                         do {
718                                 ancestor = ancestor->d_parent;
719                                 if (will_extract_dentry(ancestor)) {
720                                         place_after = &ancestor->d_extraction_list_node;
721                                         break;
722                                 }
723                         } while (!dentry_is_root(ancestor));
724
725                         ancestor = dentry;
726                         do {
727                                 ancestor = ancestor->d_parent;
728                                 if (will_extract_dentry(ancestor))
729                                         break;
730                                 list_add(&ancestor->d_extraction_list_node, place_after);
731                         } while (!dentry_is_root(ancestor));
732                 }
733         }
734 }
735
736 static void
737 destroy_dentry_list(struct list_head *dentry_list)
738 {
739         struct wim_dentry *dentry, *tmp;
740         struct wim_inode *inode;
741
742         list_for_each_entry_safe(dentry, tmp, dentry_list, d_extraction_list_node) {
743                 inode = dentry->d_inode;
744                 dentry_reset_extraction_list_node(dentry);
745                 inode->i_visited = 0;
746                 inode->i_can_externally_back = 0;
747                 if ((void *)dentry->d_extraction_name != (void *)dentry->file_name)
748                         FREE(dentry->d_extraction_name);
749                 dentry->d_extraction_name = NULL;
750                 dentry->d_extraction_name_nchars = 0;
751         }
752 }
753
754 static void
755 destroy_stream_list(struct list_head *stream_list)
756 {
757         struct wim_lookup_table_entry *lte;
758
759         list_for_each_entry(lte, stream_list, extraction_list)
760                 if (lte->out_refcnt > ARRAY_LEN(lte->inline_stream_owners))
761                         FREE(lte->stream_owners);
762 }
763
764 #ifdef __WIN32__
765 static const utf16lechar replacement_char = cpu_to_le16(0xfffd);
766 #else
767 static const utf16lechar replacement_char = cpu_to_le16('?');
768 #endif
769
770 static bool
771 file_name_valid(utf16lechar *name, size_t num_chars, bool fix)
772 {
773         size_t i;
774
775         if (num_chars == 0)
776                 return true;
777         for (i = 0; i < num_chars; i++) {
778                 switch (name[i]) {
779         #ifdef __WIN32__
780                 case cpu_to_le16('\\'):
781                 case cpu_to_le16(':'):
782                 case cpu_to_le16('*'):
783                 case cpu_to_le16('?'):
784                 case cpu_to_le16('"'):
785                 case cpu_to_le16('<'):
786                 case cpu_to_le16('>'):
787                 case cpu_to_le16('|'):
788         #endif
789                 case cpu_to_le16('/'):
790                 case cpu_to_le16('\0'):
791                         if (fix)
792                                 name[i] = replacement_char;
793                         else
794                                 return false;
795                 }
796         }
797
798 #ifdef __WIN32__
799         if (name[num_chars - 1] == cpu_to_le16(' ') ||
800             name[num_chars - 1] == cpu_to_le16('.'))
801         {
802                 if (fix)
803                         name[num_chars - 1] = replacement_char;
804                 else
805                         return false;
806         }
807 #endif
808         return true;
809 }
810
811 static int
812 dentry_calculate_extraction_name(struct wim_dentry *dentry,
813                                  struct apply_ctx *ctx)
814 {
815         int ret;
816
817         if (unlikely(!dentry_is_supported(dentry, &ctx->supported_features)))
818                 goto skip_dentry;
819
820         if (dentry_is_root(dentry))
821                 return 0;
822
823 #ifdef WITH_NTFS_3G
824         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
825                 dentry->d_extraction_name = dentry->file_name;
826                 dentry->d_extraction_name_nchars = dentry->file_name_nbytes /
827                                                    sizeof(utf16lechar);
828                 return 0;
829         }
830 #endif
831
832         if (!ctx->supported_features.case_sensitive_filenames) {
833                 struct wim_dentry *other;
834                 list_for_each_entry(other, &dentry->d_ci_conflict_list,
835                                     d_ci_conflict_list)
836                 {
837                         if (will_extract_dentry(other)) {
838                                 if (ctx->extract_flags &
839                                     WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS) {
840                                         WARNING("\"%"TS"\" has the same "
841                                                 "case-insensitive name as "
842                                                 "\"%"TS"\"; extracting "
843                                                 "dummy name instead",
844                                                 dentry_full_path(dentry),
845                                                 dentry_full_path(other));
846                                         goto out_replace;
847                                 } else {
848                                         WARNING("Not extracting \"%"TS"\": "
849                                                 "has same case-insensitive "
850                                                 "name as \"%"TS"\"",
851                                                 dentry_full_path(dentry),
852                                                 dentry_full_path(other));
853                                         goto skip_dentry;
854                                 }
855                         }
856                 }
857         }
858
859         if (file_name_valid(dentry->file_name, dentry->file_name_nbytes / 2, false)) {
860                 ret = utf16le_get_tstr(dentry->file_name,
861                                        dentry->file_name_nbytes,
862                                        (const tchar **)&dentry->d_extraction_name,
863                                        &dentry->d_extraction_name_nchars);
864                 dentry->d_extraction_name_nchars /= sizeof(tchar);
865                 return ret;
866         } else {
867                 if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES)
868                 {
869                         WARNING("\"%"TS"\" has an invalid filename "
870                                 "that is not supported on this platform; "
871                                 "extracting dummy name instead",
872                                 dentry_full_path(dentry));
873                         goto out_replace;
874                 } else {
875                         WARNING("Not extracting \"%"TS"\": has an invalid filename "
876                                 "that is not supported on this platform",
877                                 dentry_full_path(dentry));
878                         goto skip_dentry;
879                 }
880         }
881
882 out_replace:
883         {
884                 utf16lechar utf16_name_copy[dentry->file_name_nbytes / 2];
885
886                 memcpy(utf16_name_copy, dentry->file_name, dentry->file_name_nbytes);
887                 file_name_valid(utf16_name_copy, dentry->file_name_nbytes / 2, true);
888
889                 const tchar *tchar_name;
890                 size_t tchar_nchars;
891
892                 ret = utf16le_get_tstr(utf16_name_copy,
893                                        dentry->file_name_nbytes,
894                                        &tchar_name, &tchar_nchars);
895                 if (ret)
896                         return ret;
897
898                 tchar_nchars /= sizeof(tchar);
899
900                 size_t fixed_name_num_chars = tchar_nchars;
901                 tchar fixed_name[tchar_nchars + 50];
902
903                 tmemcpy(fixed_name, tchar_name, tchar_nchars);
904                 fixed_name_num_chars += tsprintf(fixed_name + tchar_nchars,
905                                                  T(" (invalid filename #%lu)"),
906                                                  ++ctx->invalid_sequence);
907
908                 utf16le_put_tstr(tchar_name);
909
910                 dentry->d_extraction_name = memdup(fixed_name,
911                                                    2 * fixed_name_num_chars + 2);
912                 if (!dentry->d_extraction_name)
913                         return WIMLIB_ERR_NOMEM;
914                 dentry->d_extraction_name_nchars = fixed_name_num_chars;
915         }
916         return 0;
917
918 skip_dentry:
919         for_dentry_in_tree(dentry, dentry_delete_from_list, NULL);
920         return 0;
921 }
922
923 /*
924  * Calculate the actual filename component at which each WIM dentry will be
925  * extracted, with special handling for dentries that are unsupported by the
926  * extraction backend or have invalid names.
927  *
928  * ctx->supported_features must be filled in.
929  *
930  * Possible error codes: WIMLIB_ERR_NOMEM, WIMLIB_ERR_INVALID_UTF16_STRING
931  */
932 static int
933 dentry_list_calculate_extraction_names(struct list_head *dentry_list,
934                                        struct apply_ctx *ctx)
935 {
936         struct list_head *prev, *cur;
937
938         /* Can't use list_for_each_entry() because a call to
939          * dentry_calculate_extraction_name() may delete the current dentry and
940          * its children from the list.  */
941
942         prev = dentry_list;
943         for (;;) {
944                 struct wim_dentry *dentry;
945                 int ret;
946
947                 cur = prev->next;
948                 if (cur == dentry_list)
949                         break;
950
951                 dentry = list_entry(cur, struct wim_dentry, d_extraction_list_node);
952
953                 ret = dentry_calculate_extraction_name(dentry, ctx);
954                 if (ret)
955                         return ret;
956
957                 if (prev->next == cur)
958                         prev = cur;
959                 else
960                         ; /* Current dentry and its children (which follow in
961                              the list) were deleted.  prev stays the same.  */
962         }
963         return 0;
964 }
965
966 static int
967 dentry_resolve_streams(struct wim_dentry *dentry, int extract_flags,
968                        struct wim_lookup_table *lookup_table)
969 {
970         struct wim_inode *inode = dentry->d_inode;
971         struct wim_lookup_table_entry *lte;
972         int ret;
973         bool force = false;
974
975         /* Special case:  when extracting from a pipe, the WIM lookup table is
976          * initially empty, so "resolving" an inode's streams is initially not
977          * possible.  However, we still need to keep track of which streams,
978          * identified by SHA1 message digests, need to be extracted, so we
979          * "resolve" the inode's streams anyway by allocating new entries.  */
980         if (extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE)
981                 force = true;
982         ret = inode_resolve_streams(inode, lookup_table, force);
983         if (ret)
984                 return ret;
985         for (u32 i = 0; i <= inode->i_num_ads; i++) {
986                 lte = inode_stream_lte_resolved(inode, i);
987                 if (lte)
988                         lte->out_refcnt = 0;
989         }
990         return 0;
991 }
992
993 /*
994  * For each dentry to be extracted, resolve all streams in the corresponding
995  * inode and set 'out_refcnt' in each to 0.
996  *
997  * Possible error codes: WIMLIB_ERR_RESOURCE_NOT_FOUND, WIMLIB_ERR_NOMEM.
998  */
999 static int
1000 dentry_list_resolve_streams(struct list_head *dentry_list,
1001                             struct apply_ctx *ctx)
1002 {
1003         struct wim_dentry *dentry;
1004         int ret;
1005
1006         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1007                 ret = dentry_resolve_streams(dentry,
1008                                              ctx->extract_flags,
1009                                              ctx->wim->lookup_table);
1010                 if (ret)
1011                         return ret;
1012         }
1013         return 0;
1014 }
1015
1016 static int
1017 ref_stream(struct wim_lookup_table_entry *lte, unsigned stream_idx,
1018            struct wim_dentry *dentry, struct apply_ctx *ctx)
1019 {
1020         struct wim_inode *inode = dentry->d_inode;
1021         struct stream_owner *stream_owners;
1022
1023         if (!lte)
1024                 return 0;
1025
1026         /* Tally the size only for each extraction of the stream (not hard
1027          * links).  */
1028         if (inode->i_visited && ctx->supported_features.hard_links)
1029                 return 0;
1030
1031         ctx->progress.extract.total_bytes += lte->size;
1032         ctx->progress.extract.total_streams++;
1033
1034         if (inode->i_visited)
1035                 return 0;
1036
1037         /* Add stream to the dentry_list only one time, even if it's going
1038          * to be extracted to multiple inodes.  */
1039         if (lte->out_refcnt == 0) {
1040                 list_add_tail(&lte->extraction_list, &ctx->stream_list);
1041                 ctx->num_streams_remaining++;
1042         }
1043
1044         /* If inode not yet been visited, append it to the stream_owners array.  */
1045         if (lte->out_refcnt < ARRAY_LEN(lte->inline_stream_owners)) {
1046                 stream_owners = lte->inline_stream_owners;
1047         } else {
1048                 struct stream_owner *prev_stream_owners;
1049                 size_t alloc_stream_owners;
1050
1051                 if (lte->out_refcnt == ARRAY_LEN(lte->inline_stream_owners)) {
1052                         prev_stream_owners = NULL;
1053                         alloc_stream_owners = ARRAY_LEN(lte->inline_stream_owners);
1054                 } else {
1055                         prev_stream_owners = lte->stream_owners;
1056                         alloc_stream_owners = lte->alloc_stream_owners;
1057                 }
1058
1059                 if (lte->out_refcnt == alloc_stream_owners) {
1060                         alloc_stream_owners *= 2;
1061                         stream_owners = REALLOC(prev_stream_owners,
1062                                                alloc_stream_owners *
1063                                                 sizeof(stream_owners[0]));
1064                         if (!stream_owners)
1065                                 return WIMLIB_ERR_NOMEM;
1066                         if (!prev_stream_owners) {
1067                                 memcpy(stream_owners,
1068                                        lte->inline_stream_owners,
1069                                        sizeof(lte->inline_stream_owners));
1070                         }
1071                         lte->stream_owners = stream_owners;
1072                         lte->alloc_stream_owners = alloc_stream_owners;
1073                 }
1074                 stream_owners = lte->stream_owners;
1075         }
1076         stream_owners[lte->out_refcnt].inode = inode;
1077         if (stream_idx == 0) {
1078                 stream_owners[lte->out_refcnt].stream_name = NULL;
1079         } else {
1080                 stream_owners[lte->out_refcnt].stream_name =
1081                         inode->i_ads_entries[stream_idx - 1].stream_name;
1082         }
1083         lte->out_refcnt++;
1084         return 0;
1085 }
1086
1087 static int
1088 ref_unnamed_stream(struct wim_dentry *dentry, struct apply_ctx *ctx)
1089 {
1090         struct wim_inode *inode = dentry->d_inode;
1091         int ret;
1092         unsigned stream_idx;
1093         struct wim_lookup_table_entry *stream;
1094
1095         if (unlikely(inode_is_encrypted_directory(inode)))
1096                 return 0;
1097
1098         if (unlikely(ctx->apply_ops->will_externally_back)) {
1099                 ret = (*ctx->apply_ops->will_externally_back)(dentry, ctx);
1100                 if (ret >= 0) {
1101                         if (ret) /* Error */
1102                                 return ret;
1103                         /* Will externally back */
1104                         return 0;
1105                 }
1106                 /* Won't externally back */
1107         }
1108
1109         stream = inode_unnamed_stream_resolved(inode, &stream_idx);
1110         return ref_stream(stream, stream_idx, dentry, ctx);
1111 }
1112
1113 static int
1114 dentry_ref_streams(struct wim_dentry *dentry, struct apply_ctx *ctx)
1115 {
1116         struct wim_inode *inode = dentry->d_inode;
1117         int ret;
1118
1119         /* The unnamed data stream will almost always be extracted, but there
1120          * exist cases in which it won't be.  */
1121         ret = ref_unnamed_stream(dentry, ctx);
1122         if (ret)
1123                 return ret;
1124
1125         /* Named data streams will be extracted only if supported in the current
1126          * extraction mode and volume, and to avoid complications, if not doing
1127          * a linked extraction.  */
1128         if (ctx->supported_features.named_data_streams) {
1129                 for (unsigned i = 0; i < inode->i_num_ads; i++) {
1130                         if (!inode->i_ads_entries[i].stream_name_nbytes)
1131                                 continue;
1132                         ret = ref_stream(inode->i_ads_entries[i].lte, i + 1,
1133                                          dentry, ctx);
1134                         if (ret)
1135                                 return ret;
1136                 }
1137         }
1138         inode->i_visited = 1;
1139         return 0;
1140 }
1141
1142 /*
1143  * For each dentry to be extracted, iterate through the data streams of the
1144  * corresponding inode.  For each such stream that is not to be ignored due to
1145  * the supported features or extraction flags, add it to the list of streams to
1146  * be extracted (ctx->stream_list) if not already done so.
1147  *
1148  * Also builds a mapping from each stream to the inodes referencing it.
1149  *
1150  * This also initializes the extract progress info with byte and stream
1151  * information.
1152  *
1153  * ctx->supported_features must be filled in.
1154  *
1155  * Possible error codes: WIMLIB_ERR_NOMEM.
1156  */
1157 static int
1158 dentry_list_ref_streams(struct list_head *dentry_list, struct apply_ctx *ctx)
1159 {
1160         struct wim_dentry *dentry;
1161         int ret;
1162
1163         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1164                 ret = dentry_ref_streams(dentry, ctx);
1165                 if (ret)
1166                         return ret;
1167         }
1168         list_for_each_entry(dentry, dentry_list, d_extraction_list_node)
1169                 dentry->d_inode->i_visited = 0;
1170         return 0;
1171 }
1172
1173 static void
1174 dentry_list_build_inode_alias_lists(struct list_head *dentry_list)
1175 {
1176         struct wim_dentry *dentry;
1177         struct wim_inode *inode;
1178
1179         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1180                 inode = dentry->d_inode;
1181                 if (!inode->i_visited)
1182                         INIT_LIST_HEAD(&inode->i_extraction_aliases);
1183                 list_add_tail(&dentry->d_extraction_alias_node,
1184                               &inode->i_extraction_aliases);
1185                 inode->i_visited = 1;
1186         }
1187         list_for_each_entry(dentry, dentry_list, d_extraction_list_node)
1188                 dentry->d_inode->i_visited = 0;
1189 }
1190
1191 static void
1192 inode_tally_features(const struct wim_inode *inode,
1193                      struct wim_features *features)
1194 {
1195         if (inode->i_attributes & FILE_ATTRIBUTE_ARCHIVE)
1196                 features->archive_files++;
1197         if (inode->i_attributes & FILE_ATTRIBUTE_HIDDEN)
1198                 features->hidden_files++;
1199         if (inode->i_attributes & FILE_ATTRIBUTE_SYSTEM)
1200                 features->system_files++;
1201         if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED)
1202                 features->compressed_files++;
1203         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1204                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1205                         features->encrypted_directories++;
1206                 else
1207                         features->encrypted_files++;
1208         }
1209         if (inode->i_attributes & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED)
1210                 features->not_context_indexed_files++;
1211         if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE)
1212                 features->sparse_files++;
1213         if (inode_has_named_stream(inode))
1214                 features->named_data_streams++;
1215         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1216                 features->reparse_points++;
1217                 if (inode_is_symlink(inode))
1218                         features->symlink_reparse_points++;
1219                 else
1220                         features->other_reparse_points++;
1221         }
1222         if (inode->i_security_id != -1)
1223                 features->security_descriptors++;
1224         if (inode_has_unix_data(inode))
1225                 features->unix_data++;
1226 }
1227
1228 /* Tally features necessary to extract a dentry and the corresponding inode.  */
1229 static void
1230 dentry_tally_features(struct wim_dentry *dentry, struct wim_features *features)
1231 {
1232         struct wim_inode *inode = dentry->d_inode;
1233
1234         if (dentry_has_short_name(dentry))
1235                 features->short_names++;
1236
1237         if (inode->i_visited) {
1238                 features->hard_links++;
1239         } else {
1240                 inode_tally_features(inode, features);
1241                 inode->i_visited = 1;
1242         }
1243 }
1244
1245 /* Tally the features necessary to extract the specified dentries.  */
1246 static void
1247 dentry_list_get_features(struct list_head *dentry_list,
1248                          struct wim_features *features)
1249 {
1250         struct wim_dentry *dentry;
1251
1252         list_for_each_entry(dentry, dentry_list, d_extraction_list_node)
1253                 dentry_tally_features(dentry, features);
1254
1255         list_for_each_entry(dentry, dentry_list, d_extraction_list_node)
1256                 dentry->d_inode->i_visited = 0;
1257 }
1258
1259 static int
1260 do_feature_check(const struct wim_features *required_features,
1261                  const struct wim_features *supported_features,
1262                  int extract_flags)
1263 {
1264         /* File attributes.  */
1265         if (!(extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)) {
1266                 /* Note: Don't bother the user about FILE_ATTRIBUTE_ARCHIVE.
1267                  * We're an archive program, so theoretically we can do what we
1268                  * want with it.  */
1269
1270                 if (required_features->hidden_files &&
1271                     !supported_features->hidden_files)
1272                         WARNING("Ignoring FILE_ATTRIBUTE_HIDDEN of %lu files",
1273                                 required_features->hidden_files);
1274
1275                 if (required_features->system_files &&
1276                     !supported_features->system_files)
1277                         WARNING("Ignoring FILE_ATTRIBUTE_SYSTEM of %lu files",
1278                                 required_features->system_files);
1279
1280                 if (required_features->compressed_files &&
1281                     !supported_features->compressed_files)
1282                         WARNING("Ignoring FILE_ATTRIBUTE_COMPRESSED of %lu files",
1283                                 required_features->compressed_files);
1284
1285                 if (required_features->not_context_indexed_files &&
1286                     !supported_features->not_context_indexed_files)
1287                         WARNING("Ignoring FILE_ATTRIBUTE_NOT_CONTENT_INDEXED of %lu files",
1288                                 required_features->not_context_indexed_files);
1289
1290                 if (required_features->sparse_files &&
1291                     !supported_features->sparse_files)
1292                         WARNING("Ignoring FILE_ATTRIBUTE_SPARSE_FILE of %lu files",
1293                                 required_features->sparse_files);
1294
1295                 if (required_features->encrypted_directories &&
1296                     !supported_features->encrypted_directories)
1297                         WARNING("Ignoring FILE_ATTRIBUTE_ENCRYPTED of %lu directories",
1298                                 required_features->encrypted_directories);
1299         }
1300
1301         /* Encrypted files.  */
1302         if (required_features->encrypted_files &&
1303             !supported_features->encrypted_files)
1304                 WARNING("Ignoring %lu encrypted files",
1305                         required_features->encrypted_files);
1306
1307         /* Named data streams.  */
1308         if (required_features->named_data_streams &&
1309             (!supported_features->named_data_streams))
1310                 WARNING("Ignoring named data streams of %lu files",
1311                         required_features->named_data_streams);
1312
1313         /* Hard links.  */
1314         if (required_features->hard_links && !supported_features->hard_links)
1315                 WARNING("Extracting %lu hard links as independent files",
1316                         required_features->hard_links);
1317
1318         /* Symbolic links and reparse points.  */
1319         if ((extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS) &&
1320             required_features->symlink_reparse_points &&
1321             !supported_features->symlink_reparse_points &&
1322             !supported_features->reparse_points)
1323         {
1324                 ERROR("Extraction backend does not support symbolic links!");
1325                 return WIMLIB_ERR_UNSUPPORTED;
1326         }
1327         if (required_features->reparse_points &&
1328             !supported_features->reparse_points)
1329         {
1330                 if (supported_features->symlink_reparse_points) {
1331                         if (required_features->other_reparse_points) {
1332                                 WARNING("Ignoring %lu non-symlink/junction "
1333                                         "reparse point files",
1334                                         required_features->other_reparse_points);
1335                         }
1336                 } else {
1337                         WARNING("Ignoring %lu reparse point files",
1338                                 required_features->reparse_points);
1339                 }
1340         }
1341
1342         /* Security descriptors.  */
1343         if (((extract_flags & (WIMLIB_EXTRACT_FLAG_STRICT_ACLS |
1344                                WIMLIB_EXTRACT_FLAG_UNIX_DATA))
1345              == WIMLIB_EXTRACT_FLAG_STRICT_ACLS) &&
1346             required_features->security_descriptors &&
1347             !supported_features->security_descriptors)
1348         {
1349                 ERROR("Extraction backend does not support security descriptors!");
1350                 return WIMLIB_ERR_UNSUPPORTED;
1351         }
1352         if (!(extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS) &&
1353             required_features->security_descriptors &&
1354             !supported_features->security_descriptors)
1355                 WARNING("Ignoring Windows NT security descriptors of %lu files",
1356                         required_features->security_descriptors);
1357
1358         /* UNIX data.  */
1359         if ((extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) &&
1360             required_features->unix_data && !supported_features->unix_data)
1361         {
1362                 ERROR("Extraction backend does not support UNIX data!");
1363                 return WIMLIB_ERR_UNSUPPORTED;
1364         }
1365
1366         if (required_features->unix_data &&
1367             !(extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA))
1368         {
1369                 WARNING("Ignoring UNIX metadata of %lu files",
1370                         required_features->unix_data);
1371         }
1372
1373         /* DOS Names.  */
1374         if (required_features->short_names &&
1375             !supported_features->short_names)
1376         {
1377                 if (extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES) {
1378                         ERROR("Extraction backend does not support DOS names!");
1379                         return WIMLIB_ERR_UNSUPPORTED;
1380                 }
1381                 WARNING("Ignoring DOS names of %lu files",
1382                         required_features->short_names);
1383         }
1384
1385         /* Timestamps.  */
1386         if ((extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_TIMESTAMPS) &&
1387             !supported_features->timestamps)
1388         {
1389                 ERROR("Extraction backend does not support timestamps!");
1390                 return WIMLIB_ERR_UNSUPPORTED;
1391         }
1392
1393         return 0;
1394 }
1395
1396 static const struct apply_operations *
1397 select_apply_operations(int extract_flags)
1398 {
1399 #ifdef WITH_NTFS_3G
1400         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS)
1401                 return &ntfs_3g_apply_ops;
1402 #endif
1403 #ifdef __WIN32__
1404         return &win32_apply_ops;
1405 #else
1406         return &unix_apply_ops;
1407 #endif
1408 }
1409
1410 static int
1411 extract_trees(WIMStruct *wim, struct wim_dentry **trees, size_t num_trees,
1412               const tchar *target, int extract_flags)
1413 {
1414         const struct apply_operations *ops;
1415         struct apply_ctx *ctx;
1416         int ret;
1417         LIST_HEAD(dentry_list);
1418
1419         if (extract_flags & WIMLIB_EXTRACT_FLAG_TO_STDOUT) {
1420                 ret = extract_dentries_to_stdout(trees, num_trees,
1421                                                  wim->lookup_table);
1422                 goto out;
1423         }
1424
1425         num_trees = remove_duplicate_trees(trees, num_trees);
1426         num_trees = remove_contained_trees(trees, num_trees);
1427
1428         ops = select_apply_operations(extract_flags);
1429
1430         if (num_trees > 1 && ops->single_tree_only) {
1431                 ERROR("Extracting multiple directory trees "
1432                       "at once is not supported in %s extraction mode!",
1433                       ops->name);
1434                 ret = WIMLIB_ERR_UNSUPPORTED;
1435                 goto out;
1436         }
1437
1438         ctx = CALLOC(1, ops->context_size);
1439         if (!ctx) {
1440                 ret = WIMLIB_ERR_NOMEM;
1441                 goto out;
1442         }
1443
1444         ctx->wim = wim;
1445         ctx->target = target;
1446         ctx->target_nchars = tstrlen(target);
1447         ctx->extract_flags = extract_flags;
1448         if (ctx->wim->progfunc) {
1449                 ctx->progfunc = ctx->wim->progfunc;
1450                 ctx->progctx = ctx->wim->progctx;
1451                 ctx->progress.extract.image = wim->current_image;
1452                 ctx->progress.extract.extract_flags = (extract_flags &
1453                                                        WIMLIB_EXTRACT_MASK_PUBLIC);
1454                 ctx->progress.extract.wimfile_name = wim->filename;
1455                 ctx->progress.extract.image_name = wimlib_get_image_name(wim,
1456                                                                          wim->current_image);
1457                 ctx->progress.extract.target = target;
1458         }
1459         INIT_LIST_HEAD(&ctx->stream_list);
1460         filedes_invalidate(&ctx->tmpfile_fd);
1461         ctx->apply_ops = ops;
1462
1463         ret = (*ops->get_supported_features)(target, &ctx->supported_features);
1464         if (ret)
1465                 goto out_cleanup;
1466
1467         build_dentry_list(&dentry_list, trees, num_trees,
1468                           !(extract_flags &
1469                             WIMLIB_EXTRACT_FLAG_NO_PRESERVE_DIR_STRUCTURE));
1470
1471         dentry_list_get_features(&dentry_list, &ctx->required_features);
1472
1473         ret = do_feature_check(&ctx->required_features, &ctx->supported_features,
1474                                ctx->extract_flags);
1475         if (ret)
1476                 goto out_cleanup;
1477
1478         ret = dentry_list_calculate_extraction_names(&dentry_list, ctx);
1479         if (ret)
1480                 goto out_cleanup;
1481
1482         if (unlikely(list_empty(&dentry_list))) {
1483                 WARNING("There is nothing to extract!");
1484                 goto out_cleanup;
1485         }
1486
1487         ret = dentry_list_resolve_streams(&dentry_list, ctx);
1488         if (ret)
1489                 goto out_cleanup;
1490
1491         dentry_list_build_inode_alias_lists(&dentry_list);
1492
1493         ret = dentry_list_ref_streams(&dentry_list, ctx);
1494         if (ret)
1495                 goto out_cleanup;
1496
1497         if (extract_flags & WIMLIB_EXTRACT_FLAG_FROM_PIPE) {
1498                 /* When extracting from a pipe, the number of bytes of data to
1499                  * extract can't be determined in the normal way (examining the
1500                  * lookup table), since at this point all we have is a set of
1501                  * SHA1 message digests of streams that need to be extracted.
1502                  * However, we can get a reasonably accurate estimate by taking
1503                  * <TOTALBYTES> from the corresponding <IMAGE> in the WIM XML
1504                  * data.  This does assume that a full image is being extracted,
1505                  * but currently there is no API for doing otherwise.  (Also,
1506                  * subtract <HARDLINKBYTES> from this if hard links are
1507                  * supported by the extraction mode.)  */
1508                 ctx->progress.extract.total_bytes =
1509                         wim_info_get_image_total_bytes(wim->wim_info,
1510                                                        wim->current_image);
1511                 if (ctx->supported_features.hard_links) {
1512                         ctx->progress.extract.total_bytes -=
1513                                 wim_info_get_image_hard_link_bytes(wim->wim_info,
1514                                                                    wim->current_image);
1515                 }
1516         }
1517
1518         ret = extract_progress(ctx,
1519                                ((extract_flags & WIMLIB_EXTRACT_FLAG_IMAGEMODE) ?
1520                                        WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN :
1521                                        WIMLIB_PROGRESS_MSG_EXTRACT_TREE_BEGIN));
1522         if (ret)
1523                 goto out_cleanup;
1524
1525         ret = (*ops->extract)(&dentry_list, ctx);
1526         if (ret)
1527                 goto out_cleanup;
1528
1529         if (ctx->progress.extract.completed_bytes <
1530             ctx->progress.extract.total_bytes)
1531         {
1532                 ctx->progress.extract.completed_bytes =
1533                         ctx->progress.extract.total_bytes;
1534                 ret = extract_progress(ctx, WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS);
1535                 if (ret)
1536                         goto out_cleanup;
1537         }
1538
1539         ret = extract_progress(ctx,
1540                                ((extract_flags & WIMLIB_EXTRACT_FLAG_IMAGEMODE) ?
1541                                        WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END :
1542                                        WIMLIB_PROGRESS_MSG_EXTRACT_TREE_END));
1543 out_cleanup:
1544         destroy_stream_list(&ctx->stream_list);
1545         destroy_dentry_list(&dentry_list);
1546         FREE(ctx);
1547 out:
1548         return ret;
1549 }
1550
1551 static int
1552 mkdir_if_needed(const tchar *target)
1553 {
1554         if (!tmkdir(target, 0755))
1555                 return 0;
1556
1557         if (errno == EEXIST)
1558                 return 0;
1559
1560 #ifdef __WIN32__
1561         /* _wmkdir() fails with EACCES if called on a drive root directory.  */
1562         if (errno == EACCES)
1563                 return 0;
1564 #endif
1565
1566         ERROR_WITH_ERRNO("Failed to create directory \"%"TS"\"", target);
1567         return WIMLIB_ERR_MKDIR;
1568 }
1569
1570 /* Make sure the extraction flags make sense, and update them if needed.  */
1571 static int
1572 check_extract_flags(const WIMStruct *wim, int *extract_flags_p)
1573 {
1574         int extract_flags = *extract_flags_p;
1575
1576         /* Check for invalid flag combinations  */
1577
1578         if ((extract_flags &
1579              (WIMLIB_EXTRACT_FLAG_NO_ACLS |
1580               WIMLIB_EXTRACT_FLAG_STRICT_ACLS)) == (WIMLIB_EXTRACT_FLAG_NO_ACLS |
1581                                                     WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
1582                 return WIMLIB_ERR_INVALID_PARAM;
1583
1584         if ((extract_flags &
1585              (WIMLIB_EXTRACT_FLAG_RPFIX |
1586               WIMLIB_EXTRACT_FLAG_NORPFIX)) == (WIMLIB_EXTRACT_FLAG_RPFIX |
1587                                                 WIMLIB_EXTRACT_FLAG_NORPFIX))
1588                 return WIMLIB_ERR_INVALID_PARAM;
1589
1590 #ifndef WITH_NTFS_3G
1591         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1592                 ERROR("wimlib was compiled without support for NTFS-3g, so\n"
1593                       "        it cannot apply a WIM image directly to an NTFS volume.");
1594                 return WIMLIB_ERR_UNSUPPORTED;
1595         }
1596 #endif
1597
1598         if (extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT) {
1599 #ifdef __WIN32__
1600                 if (!wim->filename)
1601                         return WIMLIB_ERR_NO_FILENAME;
1602 #else
1603                 ERROR("WIMBoot extraction is only supported on Windows!");
1604                 return WIMLIB_ERR_UNSUPPORTED;
1605 #endif
1606         }
1607
1608
1609         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_RPFIX |
1610                               WIMLIB_EXTRACT_FLAG_NORPFIX |
1611                               WIMLIB_EXTRACT_FLAG_IMAGEMODE)) ==
1612                                         WIMLIB_EXTRACT_FLAG_IMAGEMODE)
1613         {
1614                 /* For full-image extraction, do reparse point fixups by default
1615                  * if the WIM header says they are enabled.  */
1616                 if (wim->hdr.flags & WIM_HDR_FLAG_RP_FIX)
1617                         extract_flags |= WIMLIB_EXTRACT_FLAG_RPFIX;
1618         }
1619
1620         *extract_flags_p = extract_flags;
1621         return 0;
1622 }
1623
1624 static u32
1625 get_wildcard_flags(int extract_flags)
1626 {
1627         u32 wildcard_flags = 0;
1628
1629         if (extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_GLOB)
1630                 wildcard_flags |= WILDCARD_FLAG_ERROR_IF_NO_MATCH;
1631         else
1632                 wildcard_flags |= WILDCARD_FLAG_WARN_IF_NO_MATCH;
1633
1634         if (default_ignore_case)
1635                 wildcard_flags |= WILDCARD_FLAG_CASE_INSENSITIVE;
1636
1637         return wildcard_flags;
1638 }
1639
1640 struct append_dentry_ctx {
1641         struct wim_dentry **dentries;
1642         size_t num_dentries;
1643         size_t num_alloc_dentries;
1644 };
1645
1646 static int
1647 append_dentry_cb(struct wim_dentry *dentry, void *_ctx)
1648 {
1649         struct append_dentry_ctx *ctx = _ctx;
1650
1651         if (ctx->num_dentries == ctx->num_alloc_dentries) {
1652                 struct wim_dentry **new_dentries;
1653                 size_t new_length;
1654
1655                 new_length = max(ctx->num_alloc_dentries + 8,
1656                                  ctx->num_alloc_dentries * 3 / 2);
1657                 new_dentries = REALLOC(ctx->dentries,
1658                                        new_length * sizeof(ctx->dentries[0]));
1659                 if (new_dentries == NULL)
1660                         return WIMLIB_ERR_NOMEM;
1661                 ctx->dentries = new_dentries;
1662                 ctx->num_alloc_dentries = new_length;
1663         }
1664         ctx->dentries[ctx->num_dentries++] = dentry;
1665         return 0;
1666 }
1667
1668 static int
1669 do_wimlib_extract_paths(WIMStruct *wim, int image, const tchar *target,
1670                         const tchar * const *paths, size_t num_paths,
1671                         int extract_flags)
1672 {
1673         int ret;
1674         struct wim_dentry **trees;
1675         size_t num_trees;
1676
1677         if (wim == NULL || target == NULL || target[0] == T('\0') ||
1678             (num_paths != 0 && paths == NULL))
1679                 return WIMLIB_ERR_INVALID_PARAM;
1680
1681         ret = check_extract_flags(wim, &extract_flags);
1682         if (ret)
1683                 return ret;
1684
1685         ret = select_wim_image(wim, image);
1686         if (ret)
1687                 return ret;
1688
1689         ret = wim_checksum_unhashed_streams(wim);
1690         if (ret)
1691                 return ret;
1692
1693         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_NTFS |
1694                               WIMLIB_EXTRACT_FLAG_NO_PRESERVE_DIR_STRUCTURE)) ==
1695             (WIMLIB_EXTRACT_FLAG_NO_PRESERVE_DIR_STRUCTURE))
1696         {
1697                 ret = mkdir_if_needed(target);
1698                 if (ret)
1699                         return ret;
1700         }
1701
1702         if (extract_flags & WIMLIB_EXTRACT_FLAG_GLOB_PATHS) {
1703
1704                 struct append_dentry_ctx append_dentry_ctx = {
1705                         .dentries = NULL,
1706                         .num_dentries = 0,
1707                         .num_alloc_dentries = 0,
1708                 };
1709
1710                 u32 wildcard_flags = get_wildcard_flags(extract_flags);
1711
1712                 for (size_t i = 0; i < num_paths; i++) {
1713                         tchar *path = canonicalize_wim_path(paths[i]);
1714                         if (path == NULL) {
1715                                 ret = WIMLIB_ERR_NOMEM;
1716                                 trees = append_dentry_ctx.dentries;
1717                                 goto out_free_trees;
1718                         }
1719                         ret = expand_wildcard(wim, path,
1720                                               append_dentry_cb,
1721                                               &append_dentry_ctx,
1722                                               wildcard_flags);
1723                         FREE(path);
1724                         if (ret) {
1725                                 trees = append_dentry_ctx.dentries;
1726                                 goto out_free_trees;
1727                         }
1728                 }
1729                 trees = append_dentry_ctx.dentries;
1730                 num_trees = append_dentry_ctx.num_dentries;
1731         } else {
1732                 trees = MALLOC(num_paths * sizeof(trees[0]));
1733                 if (trees == NULL)
1734                         return WIMLIB_ERR_NOMEM;
1735
1736                 for (size_t i = 0; i < num_paths; i++) {
1737
1738                         tchar *path = canonicalize_wim_path(paths[i]);
1739                         if (path == NULL) {
1740                                 ret = WIMLIB_ERR_NOMEM;
1741                                 goto out_free_trees;
1742                         }
1743
1744                         trees[i] = get_dentry(wim, path,
1745                                               WIMLIB_CASE_PLATFORM_DEFAULT);
1746                         FREE(path);
1747                         if (trees[i] == NULL) {
1748                                   ERROR("Path \"%"TS"\" does not exist "
1749                                         "in WIM image %d",
1750                                         paths[i], wim->current_image);
1751                                   ret = WIMLIB_ERR_PATH_DOES_NOT_EXIST;
1752                                   goto out_free_trees;
1753                         }
1754                 }
1755                 num_trees = num_paths;
1756         }
1757
1758         if (num_trees == 0) {
1759                 ret = 0;
1760                 goto out_free_trees;
1761         }
1762
1763         ret = extract_trees(wim, trees, num_trees, target, extract_flags);
1764 out_free_trees:
1765         FREE(trees);
1766         return ret;
1767 }
1768
1769 static int
1770 extract_single_image(WIMStruct *wim, int image,
1771                      const tchar *target, int extract_flags)
1772 {
1773         const tchar *path = WIMLIB_WIM_ROOT_PATH;
1774         extract_flags |= WIMLIB_EXTRACT_FLAG_IMAGEMODE;
1775         return do_wimlib_extract_paths(wim, image, target, &path, 1, extract_flags);
1776 }
1777
1778 static const tchar * const filename_forbidden_chars =
1779 T(
1780 #ifdef __WIN32__
1781 "<>:\"/\\|?*"
1782 #else
1783 "/"
1784 #endif
1785 );
1786
1787 /* This function checks if it is okay to use a WIM image's name as a directory
1788  * name.  */
1789 static bool
1790 image_name_ok_as_dir(const tchar *image_name)
1791 {
1792         return image_name && *image_name &&
1793                 !tstrpbrk(image_name, filename_forbidden_chars) &&
1794                 tstrcmp(image_name, T(".")) &&
1795                 tstrcmp(image_name, T(".."));
1796 }
1797
1798 /* Extracts all images from the WIM to the directory @target, with the images
1799  * placed in subdirectories named by their image names. */
1800 static int
1801 extract_all_images(WIMStruct *wim, const tchar *target, int extract_flags)
1802 {
1803         size_t image_name_max_len = max(xml_get_max_image_name_len(wim), 20);
1804         size_t output_path_len = tstrlen(target);
1805         tchar buf[output_path_len + 1 + image_name_max_len + 1];
1806         int ret;
1807         int image;
1808         const tchar *image_name;
1809
1810         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1811                 ERROR("Cannot extract multiple images in NTFS extraction mode.");
1812                 return WIMLIB_ERR_INVALID_PARAM;
1813         }
1814
1815         ret = mkdir_if_needed(target);
1816         if (ret)
1817                 return ret;
1818         tmemcpy(buf, target, output_path_len);
1819         buf[output_path_len] = OS_PREFERRED_PATH_SEPARATOR;
1820         for (image = 1; image <= wim->hdr.image_count; image++) {
1821                 image_name = wimlib_get_image_name(wim, image);
1822                 if (image_name_ok_as_dir(image_name)) {
1823                         tstrcpy(buf + output_path_len + 1, image_name);
1824                 } else {
1825                         /* Image name is empty or contains forbidden characters.
1826                          * Use image number instead. */
1827                         tsprintf(buf + output_path_len + 1, T("%d"), image);
1828                 }
1829                 ret = extract_single_image(wim, image, buf, extract_flags);
1830                 if (ret)
1831                         return ret;
1832         }
1833         return 0;
1834 }
1835
1836 static int
1837 do_wimlib_extract_image(WIMStruct *wim, int image, const tchar *target,
1838                         int extract_flags)
1839 {
1840         if (extract_flags & (WIMLIB_EXTRACT_FLAG_NO_PRESERVE_DIR_STRUCTURE |
1841                              WIMLIB_EXTRACT_FLAG_TO_STDOUT |
1842                              WIMLIB_EXTRACT_FLAG_GLOB_PATHS))
1843                 return WIMLIB_ERR_INVALID_PARAM;
1844
1845         if (image == WIMLIB_ALL_IMAGES)
1846                 return extract_all_images(wim, target, extract_flags);
1847         else
1848                 return extract_single_image(wim, image, target, extract_flags);
1849 }
1850
1851
1852 /****************************************************************************
1853  *                          Extraction API                                  *
1854  ****************************************************************************/
1855
1856 WIMLIBAPI int
1857 wimlib_extract_paths(WIMStruct *wim, int image, const tchar *target,
1858                      const tchar * const *paths, size_t num_paths,
1859                      int extract_flags)
1860 {
1861         if (extract_flags & ~WIMLIB_EXTRACT_MASK_PUBLIC)
1862                 return WIMLIB_ERR_INVALID_PARAM;
1863
1864         return do_wimlib_extract_paths(wim, image, target, paths, num_paths,
1865                                        extract_flags);
1866 }
1867
1868 WIMLIBAPI int
1869 wimlib_extract_pathlist(WIMStruct *wim, int image, const tchar *target,
1870                         const tchar *path_list_file, int extract_flags)
1871 {
1872         int ret;
1873         tchar **paths;
1874         size_t num_paths;
1875         void *mem;
1876
1877         ret = read_path_list_file(path_list_file, &paths, &num_paths, &mem);
1878         if (ret) {
1879                 ERROR("Failed to read path list file \"%"TS"\"",
1880                       path_list_file);
1881                 return ret;
1882         }
1883
1884         ret = wimlib_extract_paths(wim, image, target,
1885                                    (const tchar * const *)paths, num_paths,
1886                                    extract_flags);
1887         FREE(paths);
1888         FREE(mem);
1889         return ret;
1890 }
1891
1892 WIMLIBAPI int
1893 wimlib_extract_image_from_pipe_with_progress(int pipe_fd,
1894                                              const tchar *image_num_or_name,
1895                                              const tchar *target,
1896                                              int extract_flags,
1897                                              wimlib_progress_func_t progfunc,
1898                                              void *progctx)
1899 {
1900         int ret;
1901         WIMStruct *pwm;
1902         struct filedes *in_fd;
1903         int image;
1904         unsigned i;
1905
1906         if (extract_flags & ~WIMLIB_EXTRACT_MASK_PUBLIC)
1907                 return WIMLIB_ERR_INVALID_PARAM;
1908
1909         /* Read the WIM header from the pipe and get a WIMStruct to represent
1910          * the pipable WIM.  Caveats:  Unlike getting a WIMStruct with
1911          * wimlib_open_wim(), getting a WIMStruct in this way will result in
1912          * an empty lookup table, no XML data read, and no filename set.  */
1913         ret = open_wim_as_WIMStruct(&pipe_fd, WIMLIB_OPEN_FLAG_FROM_PIPE, &pwm,
1914                                     progfunc, progctx);
1915         if (ret)
1916                 return ret;
1917
1918         /* Sanity check to make sure this is a pipable WIM.  */
1919         if (pwm->hdr.magic != PWM_MAGIC) {
1920                 ERROR("The WIM being read from file descriptor %d "
1921                       "is not pipable!", pipe_fd);
1922                 ret = WIMLIB_ERR_NOT_PIPABLE;
1923                 goto out_wimlib_free;
1924         }
1925
1926         /* Sanity check to make sure the first part of a pipable split WIM is
1927          * sent over the pipe first.  */
1928         if (pwm->hdr.part_number != 1) {
1929                 ERROR("The first part of the split WIM must be "
1930                       "sent over the pipe first.");
1931                 ret = WIMLIB_ERR_INVALID_PIPABLE_WIM;
1932                 goto out_wimlib_free;
1933         }
1934
1935         in_fd = &pwm->in_fd;
1936         wimlib_assert(in_fd->offset == WIM_HEADER_DISK_SIZE);
1937
1938         /* As mentioned, the WIMStruct we created from the pipe does not have
1939          * XML data yet.  Fix this by reading the extra copy of the XML data
1940          * that directly follows the header in pipable WIMs.  (Note: see
1941          * write_pipable_wim() for more details about the format of pipable
1942          * WIMs.)  */
1943         {
1944                 struct wim_lookup_table_entry xml_lte;
1945                 struct wim_resource_spec xml_rspec;
1946                 ret = read_pwm_stream_header(pwm, &xml_lte, &xml_rspec, 0, NULL);
1947                 if (ret)
1948                         goto out_wimlib_free;
1949
1950                 if (!(xml_lte.flags & WIM_RESHDR_FLAG_METADATA))
1951                 {
1952                         ERROR("Expected XML data, but found non-metadata "
1953                               "stream.");
1954                         ret = WIMLIB_ERR_INVALID_PIPABLE_WIM;
1955                         goto out_wimlib_free;
1956                 }
1957
1958                 wim_res_spec_to_hdr(&xml_rspec, &pwm->hdr.xml_data_reshdr);
1959
1960                 ret = read_wim_xml_data(pwm);
1961                 if (ret)
1962                         goto out_wimlib_free;
1963
1964                 if (wim_info_get_num_images(pwm->wim_info) != pwm->hdr.image_count) {
1965                         ERROR("Image count in XML data is not the same as in WIM header.");
1966                         ret = WIMLIB_ERR_IMAGE_COUNT;
1967                         goto out_wimlib_free;
1968                 }
1969         }
1970
1971         /* Get image index (this may use the XML data that was just read to
1972          * resolve an image name).  */
1973         if (image_num_or_name) {
1974                 image = wimlib_resolve_image(pwm, image_num_or_name);
1975                 if (image == WIMLIB_NO_IMAGE) {
1976                         ERROR("\"%"TS"\" is not a valid image in the pipable WIM!",
1977                               image_num_or_name);
1978                         ret = WIMLIB_ERR_INVALID_IMAGE;
1979                         goto out_wimlib_free;
1980                 } else if (image == WIMLIB_ALL_IMAGES) {
1981                         ERROR("Applying all images from a pipe is not supported!");
1982                         ret = WIMLIB_ERR_INVALID_IMAGE;
1983                         goto out_wimlib_free;
1984                 }
1985         } else {
1986                 if (pwm->hdr.image_count != 1) {
1987                         ERROR("No image was specified, but the pipable WIM "
1988                               "did not contain exactly 1 image");
1989                         ret = WIMLIB_ERR_INVALID_IMAGE;
1990                         goto out_wimlib_free;
1991                 }
1992                 image = 1;
1993         }
1994
1995         /* Load the needed metadata resource.  */
1996         for (i = 1; i <= pwm->hdr.image_count; i++) {
1997                 struct wim_lookup_table_entry *metadata_lte;
1998                 struct wim_image_metadata *imd;
1999                 struct wim_resource_spec *metadata_rspec;
2000
2001                 metadata_lte = new_lookup_table_entry();
2002                 if (metadata_lte == NULL) {
2003                         ret = WIMLIB_ERR_NOMEM;
2004                         goto out_wimlib_free;
2005                 }
2006                 metadata_rspec = MALLOC(sizeof(struct wim_resource_spec));
2007                 if (metadata_rspec == NULL) {
2008                         ret = WIMLIB_ERR_NOMEM;
2009                         free_lookup_table_entry(metadata_lte);
2010                         goto out_wimlib_free;
2011                 }
2012
2013                 ret = read_pwm_stream_header(pwm, metadata_lte, metadata_rspec, 0, NULL);
2014                 imd = pwm->image_metadata[i - 1];
2015                 imd->metadata_lte = metadata_lte;
2016                 if (ret) {
2017                         FREE(metadata_rspec);
2018                         goto out_wimlib_free;
2019                 }
2020
2021                 if (!(metadata_lte->flags & WIM_RESHDR_FLAG_METADATA)) {
2022                         ERROR("Expected metadata resource, but found "
2023                               "non-metadata stream.");
2024                         ret = WIMLIB_ERR_INVALID_PIPABLE_WIM;
2025                         goto out_wimlib_free;
2026                 }
2027
2028                 if (i == image) {
2029                         /* Metadata resource is for the image being extracted.
2030                          * Parse it and save the metadata in memory.  */
2031                         ret = read_metadata_resource(imd);
2032                         if (ret)
2033                                 goto out_wimlib_free;
2034                         imd->modified = 1;
2035                 } else {
2036                         /* Metadata resource is not for the image being
2037                          * extracted.  Skip over it.  */
2038                         ret = skip_wim_stream(metadata_lte);
2039                         if (ret)
2040                                 goto out_wimlib_free;
2041                 }
2042         }
2043         /* Extract the image.  */
2044         extract_flags |= WIMLIB_EXTRACT_FLAG_FROM_PIPE;
2045         ret = do_wimlib_extract_image(pwm, image, target, extract_flags);
2046         /* Clean up and return.  */
2047 out_wimlib_free:
2048         wimlib_free(pwm);
2049         return ret;
2050 }
2051
2052
2053 WIMLIBAPI int
2054 wimlib_extract_image_from_pipe(int pipe_fd, const tchar *image_num_or_name,
2055                                const tchar *target, int extract_flags)
2056 {
2057         return wimlib_extract_image_from_pipe_with_progress(pipe_fd,
2058                                                             image_num_or_name,
2059                                                             target,
2060                                                             extract_flags,
2061                                                             NULL,
2062                                                             NULL);
2063 }
2064
2065 WIMLIBAPI int
2066 wimlib_extract_image(WIMStruct *wim, int image, const tchar *target,
2067                      int extract_flags)
2068 {
2069         if (extract_flags & ~WIMLIB_EXTRACT_MASK_PUBLIC)
2070                 return WIMLIB_ERR_INVALID_PARAM;
2071         return do_wimlib_extract_image(wim, image, target, extract_flags);
2072 }