]> wimlib.net Git - wimlib/blob - src/extract_image.c
0d1db2c0813cc713890792510b4893fc17111e41
[wimlib] / src / extract_image.c
1 /*
2  * extract_image.c
3  *
4  * Support for extracting WIM files.
5  *
6  * This code does NOT contain any filesystem-specific features.  In particular,
7  * security information (i.e. file permissions) and alternate data streams are
8  * ignored, except possibly to read an alternate data stream that contains
9  * symbolic link data.
10  */
11
12 /*
13  * Copyright (C) 2012 Eric Biggers
14  *
15  * This file is part of wimlib, a library for working with WIM files.
16  *
17  * wimlib is free software; you can redistribute it and/or modify it under the
18  * terms of the GNU General Public License as published by the Free
19  * Software Foundation; either version 3 of the License, or (at your option)
20  * any later version.
21  *
22  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
23  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
24  * A PARTICULAR PURPOSE. See the GNU General Public License for more
25  * details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with wimlib; if not, see http://www.gnu.org/licenses/.
29  */
30
31 #include "config.h"
32
33 #include <dirent.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <string.h>
37 #include <sys/stat.h>
38 #include <stdlib.h>
39 #include <sys/time.h>
40
41 #ifdef HAVE_UTIME_H
42 #include <utime.h>
43 #endif
44
45 #include <unistd.h>
46
47 #include "dentry.h"
48 #include "lookup_table.h"
49 #include "timestamp.h"
50 #include "wimlib_internal.h"
51 #include "xml.h"
52
53 #ifdef WITH_NTFS_3G
54 #include <ntfs-3g/volume.h>
55 #endif
56
57 static int extract_regular_file_linked(struct wim_dentry *dentry,
58                                        const char *output_path,
59                                        struct apply_args *args,
60                                        struct wim_lookup_table_entry *lte)
61 {
62         /* This mode overrides the normal hard-link extraction and
63          * instead either symlinks or hardlinks *all* identical files in
64          * the WIM, even if they are in a different image (in the case
65          * of a multi-image extraction) */
66
67         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_HARDLINK) {
68                 if (link(lte->extracted_file, output_path) != 0) {
69                         ERROR_WITH_ERRNO("Failed to hard link "
70                                          "`%s' to `%s'",
71                                          output_path, lte->extracted_file);
72                         return WIMLIB_ERR_LINK;
73                 }
74         } else {
75                 int num_path_components;
76                 int num_output_dir_path_components;
77                 size_t extracted_file_len;
78                 char *p;
79                 const char *p2;
80                 size_t i;
81
82                 num_path_components =
83                         get_num_path_components(dentry->full_path_utf8) - 1;
84                 num_output_dir_path_components =
85                         get_num_path_components(args->target);
86
87                 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_MULTI_IMAGE) {
88                         num_path_components++;
89                         num_output_dir_path_components--;
90                 }
91                 extracted_file_len = strlen(lte->extracted_file);
92
93                 char buf[extracted_file_len + 3 * num_path_components + 1];
94                 p = &buf[0];
95
96                 for (i = 0; i < num_path_components; i++) {
97                         *p++ = '.';
98                         *p++ = '.';
99                         *p++ = '/';
100                 }
101                 p2 = lte->extracted_file;
102                 while (*p2 == '/')
103                         p2++;
104                 while (num_output_dir_path_components--)
105                         p2 = path_next_part(p2, NULL);
106                 strcpy(p, p2);
107                 if (symlink(buf, output_path) != 0) {
108                         ERROR_WITH_ERRNO("Failed to symlink `%s' to "
109                                          "`%s'",
110                                          buf, lte->extracted_file);
111                         return WIMLIB_ERR_LINK;
112                 }
113         }
114         return 0;
115 }
116
117 static int extract_regular_file_unlinked(struct wim_dentry *dentry,
118                                          struct apply_args *args,
119                                          const char *output_path,
120                                          struct wim_lookup_table_entry *lte)
121 {
122         /* Normal mode of extraction.  Regular files and hard links are
123          * extracted in the way that they appear in the WIM. */
124
125         int out_fd;
126         int ret;
127         struct wim_inode *inode = dentry->d_inode;
128
129         if (!((args->extract_flags & WIMLIB_EXTRACT_FLAG_MULTI_IMAGE)
130                 && (args->extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
131                                      WIMLIB_EXTRACT_FLAG_HARDLINK))))
132         {
133                 /* If the dentry is part of a hard link set of at least 2
134                  * dentries and one of the other dentries has already been
135                  * extracted, make a hard link to the file corresponding to this
136                  * already-extracted directory.  Otherwise, extract the file and
137                  * set the inode->i_extracted_file field so that other dentries
138                  * in the hard link group can link to it. */
139                 if (inode->i_nlink > 1) {
140                         if (inode->i_extracted_file) {
141                                 DEBUG("Extracting hard link `%s' => `%s'",
142                                       output_path, inode->i_extracted_file);
143                                 if (link(inode->i_extracted_file, output_path) != 0) {
144                                         ERROR_WITH_ERRNO("Failed to hard link "
145                                                          "`%s' to `%s'",
146                                                          output_path,
147                                                          inode->i_extracted_file);
148                                         return WIMLIB_ERR_LINK;
149                                 }
150                                 return 0;
151                         }
152                         FREE(inode->i_extracted_file);
153                         inode->i_extracted_file = STRDUP(output_path);
154                         if (!inode->i_extracted_file) {
155                                 ERROR("Failed to allocate memory for filename");
156                                 return WIMLIB_ERR_NOMEM;
157                         }
158                 }
159         }
160
161         /* Extract the contents of the file to @output_path. */
162
163         out_fd = open(output_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
164         if (out_fd == -1) {
165                 ERROR_WITH_ERRNO("Failed to open the file `%s' for writing",
166                                  output_path);
167                 return WIMLIB_ERR_OPEN;
168         }
169
170         if (!lte) {
171                 /* Empty file with no lookup table entry */
172                 DEBUG("Empty file `%s'.", output_path);
173                 ret = 0;
174                 goto out;
175         }
176
177         ret = extract_wim_resource_to_fd(lte, out_fd, wim_resource_size(lte));
178         if (ret != 0) {
179                 ERROR("Failed to extract resource to `%s'", output_path);
180                 goto out;
181         }
182         args->progress.extract.completed_bytes += wim_resource_size(lte);
183 out:
184         if (close(out_fd) != 0) {
185                 ERROR_WITH_ERRNO("Failed to close file `%s'", output_path);
186                 ret = WIMLIB_ERR_WRITE;
187         }
188         return ret;
189 }
190
191 static int extract_regular_file(struct wim_dentry *dentry,
192                                 struct apply_args *args,
193                                 const char *output_path)
194 {
195         struct wim_lookup_table_entry *lte;
196         const struct wim_inode *inode = dentry->d_inode;
197
198         lte = inode_unnamed_lte_resolved(inode);
199
200         if (lte && (args->extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
201                                            WIMLIB_EXTRACT_FLAG_HARDLINK)))
202         {
203                 if (lte->extracted_file) {
204                         return extract_regular_file_linked(dentry, output_path, args, lte);
205                 } else {
206                         lte->extracted_file = STRDUP(output_path);
207                         if (!lte->extracted_file)
208                                 return WIMLIB_ERR_NOMEM;
209                 }
210         }
211         return extract_regular_file_unlinked(dentry, args, output_path, lte);
212 }
213
214 static int extract_symlink(struct wim_dentry *dentry,
215                            struct apply_args *args,
216                            const char *output_path)
217 {
218         char target[4096];
219         ssize_t ret = inode_readlink(dentry->d_inode, target,
220                                      sizeof(target), args->w, 0);
221         struct wim_lookup_table_entry *lte;
222
223         if (ret <= 0) {
224                 ERROR("Could not read the symbolic link from dentry `%s'",
225                       dentry->full_path_utf8);
226                 return WIMLIB_ERR_INVALID_DENTRY;
227         }
228         ret = symlink(target, output_path);
229         if (ret != 0) {
230                 ERROR_WITH_ERRNO("Failed to symlink `%s' to `%s'",
231                                  output_path, target);
232                 return WIMLIB_ERR_LINK;
233         }
234         lte = inode_unnamed_lte_resolved(dentry->d_inode);
235         args->progress.extract.completed_bytes += wim_resource_size(lte);
236         return 0;
237 }
238
239 static int extract_directory(const char *output_path, bool is_root)
240 {
241         int ret;
242         struct stat stbuf;
243         ret = stat(output_path, &stbuf);
244         if (ret == 0) {
245                 if (S_ISDIR(stbuf.st_mode)) {
246                         /*if (!is_root)*/
247                                 /*WARNING("`%s' already exists", output_path);*/
248                         return 0;
249                 } else {
250                         ERROR("`%s' is not a directory", output_path);
251                         return WIMLIB_ERR_MKDIR;
252                 }
253         } else {
254                 if (errno != ENOENT) {
255                         ERROR_WITH_ERRNO("Failed to stat `%s'", output_path);
256                         return WIMLIB_ERR_STAT;
257                 }
258         }
259         if (mkdir(output_path, S_IRWXU | S_IRGRP | S_IXGRP |
260                                S_IROTH | S_IXOTH) != 0) {
261                 ERROR_WITH_ERRNO("Cannot create directory `%s'",
262                                  output_path);
263                 return WIMLIB_ERR_MKDIR;
264         }
265         return 0;
266 }
267
268 /* Extracts a file, directory, or symbolic link from the WIM archive. */
269 static int apply_dentry_normal(struct wim_dentry *dentry, void *arg)
270 {
271         struct apply_args *args = arg;
272         struct wim_inode *inode = dentry->d_inode;
273         size_t len;
274
275         len = strlen(args->target);
276         char output_path[len + dentry->full_path_utf8_len + 1];
277         memcpy(output_path, args->target, len);
278         memcpy(output_path + len, dentry->full_path_utf8, dentry->full_path_utf8_len);
279         output_path[len + dentry->full_path_utf8_len] = '\0';
280
281         if (inode_is_symlink(inode))
282                 return extract_symlink(dentry, args, output_path);
283         else if (inode_is_directory(inode))
284                 return extract_directory(output_path, false);
285         else
286                 return extract_regular_file(dentry, args, output_path);
287 }
288
289 /* Apply timestamps to an extracted file or directory */
290 static int apply_dentry_timestamps_normal(struct wim_dentry *dentry, void *arg)
291 {
292         struct apply_args *args = arg;
293         size_t len = strlen(args->target);
294         char output_path[len + dentry->full_path_utf8_len + 1];
295         const struct wim_inode *inode = dentry->d_inode;
296         int ret;
297
298         memcpy(output_path, args->target, len);
299         memcpy(output_path + len, dentry->full_path_utf8, dentry->full_path_utf8_len);
300         output_path[len + dentry->full_path_utf8_len] = '\0';
301
302         /* Convert the WIM timestamps, which are accurate to 100 nanoseconds,
303          * into struct timeval's. */
304         struct timeval tv[2];
305         wim_timestamp_to_timeval(inode->i_last_access_time, &tv[0]);
306         wim_timestamp_to_timeval(inode->i_last_write_time, &tv[1]);
307         #ifdef HAVE_LUTIMES
308         ret = lutimes(output_path, tv);
309         #else
310         ret = -1;
311         errno = ENOSYS;
312         #endif
313         if (ret != 0) {
314                 #ifdef HAVE_UTIME
315                 if (errno == ENOSYS) {
316                         struct utimbuf buf;
317                         buf.actime = wim_timestamp_to_unix(inode->i_last_access_time);
318                         buf.modtime = wim_timestamp_to_unix(inode->i_last_write_time);
319                         if (utime(output_path, &buf) == 0)
320                                 return 0;
321                 }
322                 #endif
323                 if (errno != ENOSYS || args->num_lutimes_warnings < 10) {
324                         /*WARNING("Failed to set timestamp on file `%s': %s",*/
325                                 /*output_path, strerror(errno));*/
326                         args->num_lutimes_warnings++;
327                 }
328         }
329         return 0;
330 }
331
332 /* Extract a dentry if it hasn't already been extracted, and either the dentry
333  * has no streams or WIMLIB_EXTRACT_FLAG_NO_STREAMS is not specified. */
334 static int maybe_apply_dentry(struct wim_dentry *dentry, void *arg)
335 {
336         struct apply_args *args = arg;
337         int ret;
338
339         if (dentry->is_extracted)
340                 return 0;
341
342         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_STREAMS)
343                 if (inode_unnamed_lte_resolved(dentry->d_inode))
344                         return 0;
345
346         if ((args->extract_flags & WIMLIB_EXTRACT_FLAG_VERBOSE) &&
347              args->progress_func) {
348                 args->progress.extract.cur_path = dentry->full_path_utf8;
349                 args->progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY,
350                                     &args->progress);
351         }
352         ret = args->apply_dentry(dentry, args);
353         if (ret == 0)
354                 dentry->is_extracted = 1;
355         return ret;
356 }
357
358 static int cmp_streams_by_wim_position(const void *p1, const void *p2)
359 {
360         const struct wim_lookup_table_entry *lte1, *lte2;
361         lte1 = *(const struct wim_lookup_table_entry**)p1;
362         lte2 = *(const struct wim_lookup_table_entry**)p2;
363         if (lte1->resource_entry.offset < lte2->resource_entry.offset)
364                 return -1;
365         else if (lte1->resource_entry.offset > lte2->resource_entry.offset)
366                 return 1;
367         else
368                 return 0;
369 }
370
371 static int sort_stream_list_by_wim_position(struct list_head *stream_list)
372 {
373         struct list_head *cur;
374         size_t num_streams;
375         struct wim_lookup_table_entry **array;
376         size_t i;
377         size_t array_size;
378
379         num_streams = 0;
380         list_for_each(cur, stream_list)
381                 num_streams++;
382         array_size = num_streams * sizeof(array[0]);
383         array = MALLOC(array_size);
384         if (!array) {
385                 ERROR("Failed to allocate %zu bytes to sort stream entries",
386                       array_size);
387                 return WIMLIB_ERR_NOMEM;
388         }
389         cur = stream_list->next;
390         for (i = 0; i < num_streams; i++) {
391                 array[i] = container_of(cur, struct wim_lookup_table_entry, staging_list);
392                 cur = cur->next;
393         }
394
395         qsort(array, num_streams, sizeof(array[0]), cmp_streams_by_wim_position);
396
397         INIT_LIST_HEAD(stream_list);
398         for (i = 0; i < num_streams; i++)
399                 list_add_tail(&array[i]->staging_list, stream_list);
400         FREE(array);
401         return 0;
402 }
403
404 static void calculate_bytes_to_extract(struct list_head *stream_list,
405                                        int extract_flags,
406                                        union wimlib_progress_info *progress)
407 {
408         struct wim_lookup_table_entry *lte;
409         u64 total_bytes = 0;
410         u64 num_streams = 0;
411
412         /* For each stream to be extracted... */
413         list_for_each_entry(lte, stream_list, staging_list) {
414                 if (extract_flags &
415                     (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
416                 {
417                         /* In the symlink or hard link extraction mode, each
418                          * stream will be extracted one time regardless of how
419                          * many dentries share the stream. */
420                         wimlib_assert(!(extract_flags & WIMLIB_EXTRACT_FLAG_NTFS));
421                         if (!lte->extracted_file) {
422                                 num_streams++;
423                                 total_bytes += wim_resource_size(lte);
424                         }
425                 } else {
426                         num_streams += lte->out_refcnt;
427                         total_bytes += lte->out_refcnt * wim_resource_size(lte);
428                 }
429         }
430         progress->extract.num_streams = num_streams;
431         progress->extract.total_bytes = total_bytes;
432         progress->extract.completed_bytes = 0;
433 }
434
435 static void maybe_add_stream_for_extraction(struct wim_lookup_table_entry *lte,
436                                             struct list_head *stream_list)
437 {
438         if (++lte->out_refcnt == 1) {
439                 INIT_LIST_HEAD(&lte->inode_list);
440                 list_add_tail(&lte->staging_list, stream_list);
441         }
442 }
443
444 static void inode_find_streams_for_extraction(struct wim_inode *inode,
445                                               struct list_head *stream_list,
446                                               int extract_flags)
447 {
448         struct wim_lookup_table_entry *lte;
449         bool inode_added = false;
450
451         lte = inode_unnamed_lte_resolved(inode);
452         if (lte) {
453                 maybe_add_stream_for_extraction(lte, stream_list);
454                 list_add_tail(&inode->i_lte_inode_list, &lte->inode_list);
455                 inode_added = true;
456         }
457 #ifdef WITH_NTFS_3G
458         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
459                 for (unsigned i = 0; i < inode->i_num_ads; i++) {
460                         if (inode->i_ads_entries[i].stream_name_len != 0) {
461                                 lte = inode->i_ads_entries[i].lte;
462                                 if (lte) {
463                                         maybe_add_stream_for_extraction(lte,
464                                                                         stream_list);
465                                         if (!inode_added) {
466                                                 list_add_tail(&inode->i_lte_inode_list,
467                                                               &lte->inode_list);
468                                                 inode_added = true;
469                                         }
470                                 }
471                         }
472                 }
473         }
474 #endif
475 }
476
477 static void find_streams_for_extraction(struct hlist_head *inode_list,
478                                         struct list_head *stream_list,
479                                         struct wim_lookup_table *lookup_table,
480                                         int extract_flags)
481 {
482         struct wim_inode *inode;
483         struct hlist_node *cur;
484         struct wim_dentry *dentry;
485
486         for_lookup_table_entry(lookup_table, lte_zero_out_refcnt, NULL);
487         INIT_LIST_HEAD(stream_list);
488         hlist_for_each_entry(inode, cur, inode_list, i_hlist) {
489                 if (!inode->i_resolved)
490                         inode_resolve_ltes(inode, lookup_table);
491                 inode_for_each_dentry(dentry, inode)
492                         dentry->is_extracted = 0;
493                 inode_find_streams_for_extraction(inode, stream_list,
494                                                   extract_flags);
495         }
496 }
497
498 struct apply_operations {
499         int (*apply_dentry)(struct wim_dentry *dentry, void *arg);
500         int (*apply_dentry_timestamps)(struct wim_dentry *dentry, void *arg);
501 };
502
503 static const struct apply_operations normal_apply_operations = {
504         .apply_dentry = apply_dentry_normal,
505         .apply_dentry_timestamps = apply_dentry_timestamps_normal,
506 };
507
508 #ifdef WITH_NTFS_3G
509 static const struct apply_operations ntfs_apply_operations = {
510         .apply_dentry = apply_dentry_ntfs,
511         .apply_dentry_timestamps = apply_dentry_timestamps_ntfs,
512 };
513 #endif
514
515 static int apply_stream_list(struct list_head *stream_list,
516                              struct apply_args *args,
517                              const struct apply_operations *ops,
518                              wimlib_progress_func_t progress_func)
519 {
520         uint64_t bytes_per_progress = args->progress.extract.total_bytes / 100;
521         uint64_t next_progress = bytes_per_progress;
522         struct wim_lookup_table_entry *lte;
523         struct wim_inode *inode;
524         struct wim_dentry *dentry;
525         int ret;
526
527         /* This complicated loop is essentially looping through the dentries,
528          * although dentries may be visited more than once (if a dentry contains
529          * two different nonempty streams) or not at all (if a dentry contains
530          * no non-empty streams).
531          *
532          * The outer loop is over the distinct streams to be extracted so that
533          * sequential reading of the WIM can be implemented. */
534
535         /* For each distinct stream to be extracted */
536         list_for_each_entry(lte, stream_list, staging_list) {
537                 /* For each inode that contains the stream */
538                 list_for_each_entry(inode, &lte->inode_list, i_lte_inode_list) {
539                         /* For each dentry that points to the inode */
540                         inode_for_each_dentry(dentry, inode) {
541                                 /* Extract the dentry if it was not already
542                                  * extracted */
543                                 ret = maybe_apply_dentry(dentry, args);
544                                 if (ret != 0)
545                                         return ret;
546                                 if (progress_func &&
547                                     args->progress.extract.completed_bytes >= next_progress)
548                                 {
549                                         progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS,
550                                                       &args->progress);
551                                         if (args->progress.extract.completed_bytes >=
552                                             args->progress.extract.total_bytes)
553                                         {
554                                                 next_progress = ~0ULL;
555                                         } else {
556                                                 next_progress =
557                                                         min (args->progress.extract.completed_bytes +
558                                                              bytes_per_progress,
559                                                              args->progress.extract.total_bytes);
560                                         }
561                                 }
562                         }
563                 }
564         }
565         return 0;
566 }
567
568 /* Extracts the image @image from the WIM @w to the directory or NTFS volume
569  * @target. */
570 static int extract_single_image(WIMStruct *w, int image,
571                                 const char *target, int extract_flags,
572                                 wimlib_progress_func_t progress_func)
573 {
574         int ret;
575         struct list_head stream_list;
576         struct hlist_head *inode_list;
577
578         struct apply_args args;
579         const struct apply_operations *ops;
580
581         args.w                    = w;
582         args.target               = target;
583         args.extract_flags        = extract_flags;
584         args.num_lutimes_warnings = 0;
585         args.stream_list          = &stream_list;
586         args.progress_func        = progress_func;
587
588         if (progress_func) {
589                 args.progress.extract.wimfile_name = w->filename;
590                 args.progress.extract.image = image;
591                 args.progress.extract.extract_flags = (extract_flags &
592                                                        WIMLIB_EXTRACT_MASK_PUBLIC);
593                 args.progress.extract.image_name = wimlib_get_image_name(w, image);
594                 args.progress.extract.target = target;
595         }
596
597 #ifdef WITH_NTFS_3G
598         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
599                 args.vol = ntfs_mount(target, 0);
600                 if (!args.vol) {
601                         ERROR_WITH_ERRNO("Failed to mount NTFS volume `%s'", target);
602                         return WIMLIB_ERR_NTFS_3G;
603                 }
604                 ops = &ntfs_apply_operations;
605         } else
606 #endif
607                 ops = &normal_apply_operations;
608
609         ret = select_wim_image(w, image);
610         if (ret != 0)
611                 goto out;
612
613         inode_list = &w->image_metadata[image - 1].inode_list;
614
615         /* Build a list of the streams that need to be extracted */
616         find_streams_for_extraction(inode_list, &stream_list,
617                                     w->lookup_table, extract_flags);
618
619         /* Calculate the number of bytes of data that will be extracted */
620         calculate_bytes_to_extract(&stream_list, extract_flags,
621                                    &args.progress);
622
623         if (progress_func) {
624                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN,
625                               &args.progress);
626         }
627
628         /* If a sequential extraction was specified, sort the streams to be
629          * extracted by their position in the WIM file, so that the WIM file can
630          * be read sequentially. */
631         if (extract_flags & WIMLIB_EXTRACT_FLAG_SEQUENTIAL) {
632                 ret = sort_stream_list_by_wim_position(&stream_list);
633                 if (ret != 0) {
634                         WARNING("Falling back to non-sequential extraction");
635                         extract_flags &= ~WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
636                 }
637         }
638
639         if (progress_func) {
640                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN,
641                               &args.progress);
642         }
643
644         /* Make the directory structure and extract empty files */
645         args.extract_flags |= WIMLIB_EXTRACT_FLAG_NO_STREAMS;
646         args.apply_dentry = ops->apply_dentry;
647         ret = for_dentry_in_tree(wim_root_dentry(w), maybe_apply_dentry, &args);
648         args.extract_flags &= ~WIMLIB_EXTRACT_FLAG_NO_STREAMS;
649         if (ret != 0)
650                 goto out;
651
652         if (progress_func) {
653                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_END,
654                               &args.progress);
655         }
656
657         /* Extract non-empty files */
658         ret = apply_stream_list(&stream_list, &args, ops, progress_func);
659         if (ret != 0)
660                 goto out;
661
662         if (progress_func) {
663                 progress_func(WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS,
664                               &args.progress);
665         }
666
667         /* Apply timestamps */
668         ret = for_dentry_in_tree_depth(wim_root_dentry(w),
669                                        ops->apply_dentry_timestamps, &args);
670         if (ret != 0)
671                 goto out;
672
673         if (progress_func) {
674                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END,
675                               &args.progress);
676         }
677 out:
678 #ifdef WITH_NTFS_3G
679         /* Unmount the NTFS volume */
680         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
681                 if (ntfs_umount(args.vol, FALSE) != 0) {
682                         ERROR_WITH_ERRNO("Failed to unmount NTFS volume `%s'", args.target);
683                         if (ret == 0)
684                                 ret = WIMLIB_ERR_NTFS_3G;
685                 }
686         }
687 #endif
688         return ret;
689 }
690
691
692 /* Extracts all images from the WIM to the directory @target, with the images
693  * placed in subdirectories named by their image names. */
694 static int extract_all_images(WIMStruct *w, const char *target,
695                               int extract_flags,
696                               wimlib_progress_func_t progress_func)
697 {
698         size_t image_name_max_len = max(xml_get_max_image_name_len(w), 20);
699         size_t output_path_len = strlen(target);
700         char buf[output_path_len + 1 + image_name_max_len + 1];
701         int ret;
702         int image;
703         const char *image_name;
704
705         ret = extract_directory(target, true);
706         if (ret != 0)
707                 return ret;
708
709         memcpy(buf, target, output_path_len);
710         buf[output_path_len] = '/';
711         for (image = 1; image <= w->hdr.image_count; image++) {
712                 image_name = wimlib_get_image_name(w, image);
713                 if (image_name && *image_name) {
714                         strcpy(buf + output_path_len + 1, image_name);
715                 } else {
716                         /* Image name is empty. Use image number instead */
717                         sprintf(buf + output_path_len + 1, "%d", image);
718                 }
719                 ret = extract_single_image(w, image, buf, extract_flags,
720                                            progress_func);
721                 if (ret != 0)
722                         return ret;
723         }
724         return 0;
725 }
726
727 /* Extracts a single image or all images from a WIM file to a directory or NTFS
728  * volume. */
729 WIMLIBAPI int wimlib_extract_image(WIMStruct *w,
730                                    int image,
731                                    const char *target,
732                                    int extract_flags,
733                                    WIMStruct **additional_swms,
734                                    unsigned num_additional_swms,
735                                    wimlib_progress_func_t progress_func)
736 {
737         struct wim_lookup_table *joined_tab, *w_tab_save;
738         int ret;
739
740         if (!target)
741                 return WIMLIB_ERR_INVALID_PARAM;
742
743         extract_flags &= WIMLIB_EXTRACT_MASK_PUBLIC;
744
745         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
746                         == (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
747                 return WIMLIB_ERR_INVALID_PARAM;
748
749         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
750 #ifdef WITH_NTFS_3G
751                 if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))) {
752                         ERROR("Cannot specify symlink or hardlink flags when applying\n"
753                               "        directly to a NTFS volume");
754                         return WIMLIB_ERR_INVALID_PARAM;
755                 }
756                 if (image == WIMLIB_ALL_IMAGES) {
757                         ERROR("Can only apply a single image when applying "
758                               "directly to a NTFS volume");
759                         return WIMLIB_ERR_INVALID_PARAM;
760                 }
761 #else
762                 ERROR("wimlib was compiled without support for NTFS-3g, so");
763                 ERROR("we cannot apply a WIM image directly to a NTFS volume");
764                 return WIMLIB_ERR_UNSUPPORTED;
765 #endif
766         }
767
768         ret = verify_swm_set(w, additional_swms, num_additional_swms);
769         if (ret != 0)
770                 return ret;
771
772         if (num_additional_swms) {
773                 ret = new_joined_lookup_table(w, additional_swms,
774                                               num_additional_swms, &joined_tab);
775                 if (ret != 0)
776                         return ret;
777                 w_tab_save = w->lookup_table;
778                 w->lookup_table = joined_tab;
779         }
780
781         if (image == WIMLIB_ALL_IMAGES) {
782                 extract_flags |= WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
783                 ret = extract_all_images(w, target, extract_flags,
784                                          progress_func);
785         } else {
786                 extract_flags &= ~WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
787                 ret = extract_single_image(w, image, target, extract_flags,
788                                            progress_func);
789         }
790
791         if (extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
792                              WIMLIB_EXTRACT_FLAG_HARDLINK))
793         {
794                 for_lookup_table_entry(w->lookup_table,
795                                        lte_free_extracted_file,
796                                        NULL);
797         }
798
799         if (num_additional_swms) {
800                 free_lookup_table(w->lookup_table);
801                 w->lookup_table = w_tab_save;
802         }
803         return ret;
804 }