bebd1d32d71b883d6dc20cbb849cffa39c097bc9
[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 dentry *dentry,
58                                        const char *output_path,
59                                        struct apply_args *args,
60                                        struct 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 dentry *dentry,
118                                          struct apply_args *args,
119                                          const char *output_path,
120                                          struct 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 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 one 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,
137                  * and set the inode->extracted_file field so that other
138                  * dentries in the hard link group can link to it. */
139                 if (inode->link_count > 1) {
140                         if (inode->extracted_file) {
141                                 DEBUG("Extracting hard link `%s' => `%s'",
142                                       output_path, inode->extracted_file);
143                                 if (link(inode->extracted_file, output_path) != 0) {
144                                         ERROR_WITH_ERRNO("Failed to hard link "
145                                                          "`%s' to `%s'",
146                                                          output_path,
147                                                          inode->extracted_file);
148                                         return WIMLIB_ERR_LINK;
149                                 }
150                                 return 0;
151                         }
152                         FREE(inode->extracted_file);
153                         inode->extracted_file = STRDUP(output_path);
154                         if (!inode->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 /*
192  * Extracts a regular file from the WIM archive.
193  */
194 static int extract_regular_file(struct dentry *dentry,
195                                 struct apply_args *args,
196                                 const char *output_path)
197 {
198         struct lookup_table_entry *lte;
199         const struct inode *inode = dentry->d_inode;
200
201         lte = inode_unnamed_lte_resolved(inode);
202
203         if (lte && (args->extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
204                                            WIMLIB_EXTRACT_FLAG_HARDLINK)))
205         {
206                 if (lte->extracted_file) {
207                         return extract_regular_file_linked(dentry, output_path, args, lte);
208                 } else {
209                         lte->extracted_file = STRDUP(output_path);
210                         if (!lte->extracted_file)
211                                 return WIMLIB_ERR_NOMEM;
212                 }
213         }
214         return extract_regular_file_unlinked(dentry, args, output_path, lte);
215 }
216
217 static int extract_symlink(struct dentry *dentry,
218                            struct apply_args *args,
219                            const char *output_path)
220 {
221         char target[4096];
222         ssize_t ret = inode_readlink(dentry->d_inode, target,
223                                      sizeof(target), args->w, 0);
224         struct lookup_table_entry *lte;
225
226         if (ret <= 0) {
227                 ERROR("Could not read the symbolic link from dentry `%s'",
228                       dentry->full_path_utf8);
229                 return WIMLIB_ERR_INVALID_DENTRY;
230         }
231         ret = symlink(target, output_path);
232         if (ret != 0) {
233                 ERROR_WITH_ERRNO("Failed to symlink `%s' to `%s'",
234                                  output_path, target);
235                 return WIMLIB_ERR_LINK;
236         }
237         lte = inode_unnamed_lte_resolved(dentry->d_inode);
238         args->progress.extract.completed_bytes += wim_resource_size(lte);
239         return 0;
240 }
241
242 /*
243  * Extracts a directory from the WIM archive.
244  *
245  * @dentry:             The directory entry for the directory.
246  * @output_path:        The path to which the directory is to be extracted to.
247  * @return:             True on success, false on failure.
248  */
249 static int extract_directory(const char *output_path, bool is_root)
250 {
251         int ret;
252         struct stat stbuf;
253         ret = stat(output_path, &stbuf);
254         if (ret == 0) {
255                 if (S_ISDIR(stbuf.st_mode)) {
256                         /*if (!is_root)*/
257                                 /*WARNING("`%s' already exists", output_path);*/
258                         return 0;
259                 } else {
260                         ERROR("`%s' is not a directory", output_path);
261                         return WIMLIB_ERR_MKDIR;
262                 }
263         } else {
264                 if (errno != ENOENT) {
265                         ERROR_WITH_ERRNO("Failed to stat `%s'", output_path);
266                         return WIMLIB_ERR_STAT;
267                 }
268         }
269         /* Compute the output path directory to the directory. */
270         if (mkdir(output_path, S_IRWXU | S_IRGRP | S_IXGRP |
271                                S_IROTH | S_IXOTH) != 0) {
272                 ERROR_WITH_ERRNO("Cannot create directory `%s'",
273                                  output_path);
274                 return WIMLIB_ERR_MKDIR;
275         }
276         return 0;
277 }
278
279 /*
280  * Extracts a file, directory, or symbolic link from the WIM archive.  For use
281  * in for_dentry_in_tree().
282  */
283 static int apply_dentry_normal(struct dentry *dentry, void *arg)
284 {
285         struct apply_args *args = arg;
286         int extract_flags = args->extract_flags;
287         struct inode *inode = dentry->d_inode;
288         size_t len;
289         int ret;
290
291         if (dentry->is_extracted)
292                 return 0;
293
294         if (extract_flags & WIMLIB_EXTRACT_FLAG_NO_STREAMS)
295                 if (inode_unnamed_lte_resolved(inode))
296                         return 0;
297
298         if ((extract_flags & WIMLIB_EXTRACT_FLAG_VERBOSE) &&
299              args->progress_func)
300         {
301                 args->progress.extract.cur_path = dentry->full_path_utf8;
302                 args->progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY,
303                                     &args->progress);
304         }
305
306         len = strlen(args->target);
307         char output_path[len + dentry->full_path_utf8_len + 1];
308         memcpy(output_path, args->target, len);
309         memcpy(output_path + len, dentry->full_path_utf8, dentry->full_path_utf8_len);
310         output_path[len + dentry->full_path_utf8_len] = '\0';
311
312         if (inode_is_symlink(inode))
313                 ret = extract_symlink(dentry, args, output_path);
314         else if (inode_is_directory(inode))
315                 ret = extract_directory(output_path, false);
316         else
317                 ret = extract_regular_file(dentry, args, output_path);
318         if (ret == 0)
319                 dentry->is_extracted = 1;
320         return ret;
321 }
322
323 /* Apply timestamp to extracted file */
324 static int apply_dentry_timestamps_normal(struct dentry *dentry, void *arg)
325 {
326         struct apply_args *args = arg;
327         size_t len = strlen(args->target);
328         char output_path[len + dentry->full_path_utf8_len + 1];
329         const struct inode *inode = dentry->d_inode;
330         int ret;
331
332         memcpy(output_path, args->target, len);
333         memcpy(output_path + len, dentry->full_path_utf8, dentry->full_path_utf8_len);
334         output_path[len + dentry->full_path_utf8_len] = '\0';
335
336         struct timeval tv[2];
337         wim_timestamp_to_timeval(inode->last_access_time, &tv[0]);
338         wim_timestamp_to_timeval(inode->last_write_time, &tv[1]);
339         #ifdef HAVE_LUTIMES
340         ret = lutimes(output_path, tv);
341         #else
342         ret = -1;
343         errno = ENOSYS;
344         #endif
345         if (ret != 0) {
346                 #ifdef HAVE_UTIME
347                 if (errno == ENOSYS) {
348                         struct utimbuf buf;
349                         buf.actime = wim_timestamp_to_unix(inode->last_access_time);
350                         buf.modtime = wim_timestamp_to_unix(inode->last_write_time);
351                         if (utime(output_path, &buf) == 0)
352                                 return 0;
353                 }
354                 #endif
355                 if (errno != ENOSYS || args->num_lutimes_warnings < 10) {
356                         /*WARNING("Failed to set timestamp on file `%s': %s",*/
357                                 /*output_path, strerror(errno));*/
358                         args->num_lutimes_warnings++;
359                 }
360         }
361         return 0;
362 }
363
364 static int cmp_streams_by_wim_position(const void *p1, const void *p2)
365 {
366         const struct lookup_table_entry *lte1, *lte2;
367         lte1 = *(const struct lookup_table_entry**)p1;
368         lte2 = *(const struct lookup_table_entry**)p2;
369         if (lte1->resource_entry.offset < lte2->resource_entry.offset)
370                 return -1;
371         else if (lte1->resource_entry.offset > lte2->resource_entry.offset)
372                 return 1;
373         else
374                 return 0;
375 }
376
377 static int sort_stream_list_by_wim_position(struct list_head *stream_list)
378 {
379         struct list_head *cur;
380         size_t num_streams;
381         struct lookup_table_entry **array;
382         size_t i;
383         size_t array_size;
384
385         num_streams = 0;
386         list_for_each(cur, stream_list)
387                 num_streams++;
388         array_size = num_streams * sizeof(array[0]);
389         array = MALLOC(array_size);
390         if (!array) {
391                 ERROR("Failed to allocate %zu bytes to sort stream entries",
392                       array_size);
393                 return WIMLIB_ERR_NOMEM;
394         }
395         cur = stream_list->next;
396         for (i = 0; i < num_streams; i++) {
397                 array[i] = container_of(cur, struct lookup_table_entry, staging_list);
398                 cur = cur->next;
399         }
400
401         qsort(array, num_streams, sizeof(array[0]), cmp_streams_by_wim_position);
402
403         INIT_LIST_HEAD(stream_list);
404         for (i = 0; i < num_streams; i++)
405                 list_add_tail(&array[i]->staging_list, stream_list);
406         FREE(array);
407         return 0;
408 }
409
410 static void calculate_bytes_to_extract(struct list_head *stream_list,
411                                        int extract_flags,
412                                        union wimlib_progress_info *progress)
413 {
414         struct lookup_table_entry *lte;
415         u64 total_bytes = 0;
416         u64 num_streams = 0;
417
418         /* For each stream to be extracted... */
419         list_for_each_entry(lte, stream_list, staging_list) {
420                 if (extract_flags &
421                     (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
422                 {
423                         /* In the symlink or hard link extraction mode, each
424                          * stream will be extracted one time regardless of how
425                          * many dentries share the stream. */
426                         wimlib_assert(!(extract_flags & WIMLIB_EXTRACT_FLAG_NTFS));
427                         if (!lte->extracted_file) {
428                                 num_streams++;
429                                 total_bytes += wim_resource_size(lte);
430                         }
431                 } else {
432                         num_streams += lte->out_refcnt;
433                         total_bytes += lte->out_refcnt * wim_resource_size(lte);
434                 }
435         }
436         progress->extract.num_streams = num_streams;
437         progress->extract.total_bytes = total_bytes;
438         progress->extract.completed_bytes = 0;
439 }
440
441 static void maybe_add_stream_for_extraction(struct lookup_table_entry *lte,
442                                             struct list_head *stream_list)
443 {
444         if (++lte->out_refcnt == 1) {
445                 INIT_LIST_HEAD(&lte->inode_list);
446                 list_add_tail(&lte->staging_list, stream_list);
447         }
448 }
449
450 static void inode_find_streams_for_extraction(struct inode *inode,
451                                               struct list_head *stream_list,
452                                               int extract_flags)
453 {
454         struct lookup_table_entry *lte;
455         bool inode_added = false;
456
457         lte = inode_unnamed_lte_resolved(inode);
458
459         if (lte) {
460                 maybe_add_stream_for_extraction(lte, stream_list);
461                 list_add_tail(&inode->lte_inode_list, &lte->inode_list);
462                 inode_added = true;
463         }
464 #ifdef WITH_NTFS_3G
465         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
466                 for (unsigned i = 0; i < inode->num_ads; i++) {
467                         if (inode->ads_entries[i].stream_name_len != 0) {
468                                 lte = inode->ads_entries[i].lte;
469                                 if (lte) {
470                                         maybe_add_stream_for_extraction(lte,
471                                                                         stream_list);
472                                         if (!inode_added) {
473                                                 list_add_tail(&inode->lte_inode_list,
474                                                               &lte->inode_list);
475                                                 inode_added = true;
476                                         }
477                                 }
478                         }
479                 }
480         }
481 #endif
482 }
483
484 static void find_streams_for_extraction(struct hlist_head *inode_list,
485                                         struct list_head *stream_list,
486                                         struct lookup_table *lookup_table,
487                                         int extract_flags)
488 {
489         struct inode *inode;
490         struct hlist_node *cur;
491         struct dentry *dentry;
492
493         for_lookup_table_entry(lookup_table, lte_zero_out_refcnt, NULL);
494         INIT_LIST_HEAD(stream_list);
495         hlist_for_each_entry(inode, cur, inode_list, hlist) {
496                 if (!inode->resolved)
497                         inode_resolve_ltes(inode, lookup_table);
498                 inode_for_each_dentry(dentry, inode)
499                         dentry->is_extracted = 0;
500                 inode_find_streams_for_extraction(inode, stream_list,
501                                                   extract_flags);
502         }
503 }
504
505 struct apply_operations {
506         int (*apply_dentry)(struct dentry *dentry, void *arg);
507         int (*apply_dentry_timestamps)(struct dentry *dentry, void *arg);
508 };
509
510 static const struct apply_operations normal_apply_operations = {
511         .apply_dentry = apply_dentry_normal,
512         .apply_dentry_timestamps = apply_dentry_timestamps_normal,
513 };
514
515 #ifdef WITH_NTFS_3G
516 static const struct apply_operations ntfs_apply_operations = {
517         .apply_dentry = apply_dentry_ntfs,
518         .apply_dentry_timestamps = apply_dentry_timestamps_ntfs,
519 };
520 #endif
521
522 static int apply_stream_list(struct list_head *stream_list,
523                              struct apply_args *args,
524                              const struct apply_operations *ops,
525                              wimlib_progress_func_t progress_func)
526 {
527         uint64_t bytes_per_progress = args->progress.extract.total_bytes / 100;
528         uint64_t next_progress = bytes_per_progress;
529         struct lookup_table_entry *lte;
530         struct inode *inode;
531         struct dentry *dentry;
532         int ret = 0;
533
534         /* This complicated loop is actually just looping through the dentries
535          * (as for_dentry_in_tree() does), but the outer loop is actually over
536          * the distinct streams to be extracted so that sequential reading of
537          * the WIM can be implemented. */
538
539         /* For each distinct stream to be extracted */
540         list_for_each_entry(lte, stream_list, staging_list) {
541                 /* For each inode that contains the stream */
542                 list_for_each_entry(inode, &lte->inode_list, lte_inode_list) {
543                         /* For each dentry that points to the inode */
544                         inode_for_each_dentry(dentry, inode) {
545                                 ret = ops->apply_dentry(dentry, args);
546                                 if (ret != 0)
547                                         goto out;
548                                 if (progress_func &&
549                                     args->progress.extract.completed_bytes >= next_progress)
550                                 {
551                                         progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS,
552                                                       &args->progress);
553                                         if (args->progress.extract.completed_bytes >=
554                                             args->progress.extract.total_bytes)
555                                         {
556                                                 next_progress = ~0ULL;
557                                         } else {
558                                                 next_progress =
559                                                         min (args->progress.extract.completed_bytes +
560                                                              bytes_per_progress,
561                                                              args->progress.extract.total_bytes);
562                                         }
563                                 }
564                         }
565                 }
566         }
567 out:
568         return ret;
569 }
570
571 static int extract_single_image(WIMStruct *w, int image,
572                                 const char *target, int extract_flags,
573                                 wimlib_progress_func_t progress_func)
574 {
575         int ret;
576         struct list_head stream_list;
577         struct hlist_head *inode_list;
578
579         struct apply_args args;
580         const struct apply_operations *ops;
581
582         args.w                    = w;
583         args.target               = target;
584         args.extract_flags        = extract_flags;
585         args.num_lutimes_warnings = 0;
586         args.target               = target;
587         args.stream_list          = &stream_list;
588         args.progress_func        = progress_func;
589
590         if (progress_func) {
591                 args.progress.extract.wimfile_name = w->filename;
592                 args.progress.extract.image = image;
593                 args.progress.extract.extract_flags = (extract_flags &
594                                                        WIMLIB_EXTRACT_MASK_PUBLIC);
595                 args.progress.extract.image_name = wimlib_get_image_name(w, image);
596                 args.progress.extract.target = target;
597         }
598
599 #ifdef WITH_NTFS_3G
600         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
601                 args.vol = ntfs_mount(target, 0);
602                 if (!args.vol) {
603                         ERROR_WITH_ERRNO("Failed to mount NTFS volume `%s'", target);
604                         return WIMLIB_ERR_NTFS_3G;
605                 }
606                 ops = &ntfs_apply_operations;
607         } else
608 #endif
609                 ops = &normal_apply_operations;
610
611         ret = select_wim_image(w, image);
612         if (ret != 0)
613                 goto out;
614
615         inode_list = &w->image_metadata[image - 1].inode_list;
616
617         find_streams_for_extraction(inode_list, &stream_list,
618                                     w->lookup_table, extract_flags);
619
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 (extract_flags & WIMLIB_EXTRACT_FLAG_SEQUENTIAL) {
629                 ret = sort_stream_list_by_wim_position(&stream_list);
630                 if (ret != 0) {
631                         WARNING("Falling back to non-sequential extraction");
632                         extract_flags &= ~WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
633                 }
634         }
635
636         if (progress_func) {
637                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN,
638                               &args.progress);
639         }
640
641         args.extract_flags |= WIMLIB_EXTRACT_FLAG_NO_STREAMS;
642         ret = for_dentry_in_tree(wim_root_dentry(w), ops->apply_dentry, &args);
643         args.extract_flags &= ~WIMLIB_EXTRACT_FLAG_NO_STREAMS;
644         if (ret != 0)
645                 goto out;
646
647         if (progress_func) {
648                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_END,
649                               &args.progress);
650         }
651
652         ret = apply_stream_list(&stream_list, &args, ops, progress_func);
653         if (ret != 0)
654                 goto out;
655
656         if (progress_func) {
657                 progress_func(WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS,
658                               &args.progress);
659         }
660
661         ret = for_dentry_in_tree_depth(wim_root_dentry(w),
662                                        ops->apply_dentry_timestamps, &args);
663         if (ret != 0)
664                 goto out;
665
666         if (progress_func) {
667                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END,
668                               &args.progress);
669         }
670 out:
671 #ifdef WITH_NTFS_3G
672         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
673                 if (ntfs_umount(args.vol, FALSE) != 0) {
674                         ERROR_WITH_ERRNO("Failed to unmount NTFS volume `%s'", args.target);
675                         if (ret == 0)
676                                 ret = WIMLIB_ERR_NTFS_3G;
677                 }
678         }
679 #endif
680         return ret;
681 }
682
683
684 /* Extracts all images from the WIM to @output_dir, with the images placed in
685  * subdirectories named by their image names. */
686 static int extract_all_images(WIMStruct *w, const char *target,
687                               int extract_flags,
688                               wimlib_progress_func_t progress_func)
689 {
690         size_t image_name_max_len = max(xml_get_max_image_name_len(w), 20);
691         size_t output_path_len = strlen(target);
692         char buf[output_path_len + 1 + image_name_max_len + 1];
693         int ret;
694         int image;
695         const char *image_name;
696
697         ret = extract_directory(target, true);
698         if (ret != 0)
699                 return ret;
700
701         memcpy(buf, target, output_path_len);
702         buf[output_path_len] = '/';
703         for (image = 1; image <= w->hdr.image_count; image++) {
704                 image_name = wimlib_get_image_name(w, image);
705                 if (image_name && *image_name) {
706                         strcpy(buf + output_path_len + 1, image_name);
707                 } else {
708                         /* Image name is empty. Use image number instead */
709                         sprintf(buf + output_path_len + 1, "%d", image);
710                 }
711                 ret = extract_single_image(w, image, buf, extract_flags,
712                                            progress_func);
713                 if (ret != 0)
714                         return ret;
715         }
716         return 0;
717 }
718
719 /* Extracts a single image or all images from a WIM file. */
720 WIMLIBAPI int wimlib_extract_image(WIMStruct *w, int image,
721                                    const char *target,
722                                    int extract_flags,
723                                    WIMStruct **additional_swms,
724                                    unsigned num_additional_swms,
725                                    wimlib_progress_func_t progress_func)
726 {
727         struct lookup_table *joined_tab, *w_tab_save;
728         int ret;
729
730         if (!target)
731                 return WIMLIB_ERR_INVALID_PARAM;
732
733         extract_flags &= WIMLIB_EXTRACT_MASK_PUBLIC;
734
735         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
736                         == (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
737                 return WIMLIB_ERR_INVALID_PARAM;
738
739         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
740 #ifdef WITH_NTFS_3G
741                 if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))) {
742                         ERROR("Cannot specify symlink or hardlink flags when applying\n"
743                               "        directly to a NTFS volume");
744                         return WIMLIB_ERR_INVALID_PARAM;
745                 }
746                 if (image == WIMLIB_ALL_IMAGES) {
747                         ERROR("Can only apply a single image when applying "
748                               "directly to a NTFS volume");
749                         return WIMLIB_ERR_INVALID_PARAM;
750                 }
751 #else
752                 ERROR("wimlib was compiled without support for NTFS-3g, so");
753                 ERROR("we cannot apply a WIM image directly to a NTFS volume");
754                 return WIMLIB_ERR_UNSUPPORTED;
755 #endif
756         }
757
758         ret = verify_swm_set(w, additional_swms, num_additional_swms);
759         if (ret != 0)
760                 return ret;
761
762         if (num_additional_swms) {
763                 ret = new_joined_lookup_table(w, additional_swms,
764                                               num_additional_swms, &joined_tab);
765                 if (ret != 0)
766                         return ret;
767                 w_tab_save = w->lookup_table;
768                 w->lookup_table = joined_tab;
769         }
770
771         if (image == WIMLIB_ALL_IMAGES) {
772                 extract_flags |= WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
773                 ret = extract_all_images(w, target, extract_flags,
774                                          progress_func);
775         } else {
776                 extract_flags &= ~WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
777                 ret = extract_single_image(w, image, target, extract_flags,
778                                            progress_func);
779         }
780
781         if (extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
782                              WIMLIB_EXTRACT_FLAG_HARDLINK))
783         {
784                 for_lookup_table_entry(w->lookup_table,
785                                        lte_free_extracted_file,
786                                        NULL);
787         }
788
789         if (num_additional_swms) {
790                 free_lookup_table(w->lookup_table);
791                 w->lookup_table = w_tab_save;
792         }
793         return ret;
794 }