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