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