Win32 capture
[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, 2013 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 symlink_apply_unix_data(const char *link,
118                                    const struct wimlib_unix_data *unix_data)
119 {
120         if (lchown(link, unix_data->uid, unix_data->gid)) {
121                 if (errno == EPERM) {
122                         /* Ignore */
123                         WARNING_WITH_ERRNO("failed to set symlink UNIX owner/group");
124                 } else {
125                         ERROR_WITH_ERRNO("failed to set symlink UNIX owner/group");
126                         return WIMLIB_ERR_INVALID_DENTRY;
127                 }
128         }
129         return 0;
130 }
131
132 static int fd_apply_unix_data(int fd, const struct wimlib_unix_data *unix_data)
133 {
134         if (fchown(fd, unix_data->uid, unix_data->gid)) {
135                 if (errno == EPERM) {
136                         WARNING_WITH_ERRNO("failed to set file UNIX owner/group");
137                         /* Ignore? */
138                 } else {
139                         ERROR_WITH_ERRNO("failed to set file UNIX owner/group");
140                         return WIMLIB_ERR_INVALID_DENTRY;
141                 }
142         }
143
144         if (fchmod(fd, unix_data->mode)) {
145                 if (errno == EPERM) {
146                         WARNING_WITH_ERRNO("failed to set UNIX file mode");
147                         /* Ignore? */
148                 } else {
149                         ERROR_WITH_ERRNO("failed to set UNIX file mode");
150                         return WIMLIB_ERR_INVALID_DENTRY;
151                 }
152         }
153         return 0;
154 }
155
156 static int dir_apply_unix_data(const char *dir,
157                                const struct wimlib_unix_data *unix_data)
158 {
159         int dfd = open(dir, O_RDONLY);
160         int ret;
161         if (dfd >= 0) {
162                 ret = fd_apply_unix_data(dfd, unix_data);
163                 if (close(dfd)) {
164                         ERROR_WITH_ERRNO("can't close directory `%s'", dir);
165                         ret = WIMLIB_ERR_MKDIR;
166                 }
167         } else {
168                 ERROR_WITH_ERRNO("can't open directory `%s'", dir);
169                 ret = WIMLIB_ERR_MKDIR;
170         }
171         return ret;
172 }
173
174 static int extract_regular_file_unlinked(struct wim_dentry *dentry,
175                                          struct apply_args *args,
176                                          const char *output_path,
177                                          struct wim_lookup_table_entry *lte)
178 {
179         /* Normal mode of extraction.  Regular files and hard links are
180          * extracted in the way that they appear in the WIM. */
181
182         int out_fd;
183         int ret;
184         struct wim_inode *inode = dentry->d_inode;
185
186         if (!((args->extract_flags & WIMLIB_EXTRACT_FLAG_MULTI_IMAGE)
187                 && (args->extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
188                                      WIMLIB_EXTRACT_FLAG_HARDLINK))))
189         {
190                 /* If the dentry is part of a hard link set of at least 2
191                  * dentries and one of the other dentries has already been
192                  * extracted, make a hard link to the file corresponding to this
193                  * already-extracted directory.  Otherwise, extract the file and
194                  * set the inode->i_extracted_file field so that other dentries
195                  * in the hard link group can link to it. */
196                 if (inode->i_nlink > 1) {
197                         if (inode->i_extracted_file) {
198                                 DEBUG("Extracting hard link `%s' => `%s'",
199                                       output_path, inode->i_extracted_file);
200                                 if (link(inode->i_extracted_file, output_path) != 0) {
201                                         ERROR_WITH_ERRNO("Failed to hard link "
202                                                          "`%s' to `%s'",
203                                                          output_path,
204                                                          inode->i_extracted_file);
205                                         return WIMLIB_ERR_LINK;
206                                 }
207                                 return 0;
208                         }
209                         FREE(inode->i_extracted_file);
210                         inode->i_extracted_file = STRDUP(output_path);
211                         if (!inode->i_extracted_file) {
212                                 ERROR("Failed to allocate memory for filename");
213                                 return WIMLIB_ERR_NOMEM;
214                         }
215                 }
216         }
217
218         /* Extract the contents of the file to @output_path. */
219
220         out_fd = open(output_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
221         if (out_fd == -1) {
222                 ERROR_WITH_ERRNO("Failed to open the file `%s' for writing",
223                                  output_path);
224                 return WIMLIB_ERR_OPEN;
225         }
226
227         if (!lte) {
228                 /* Empty file with no lookup table entry */
229                 DEBUG("Empty file `%s'.", output_path);
230                 ret = 0;
231                 goto out_extract_unix_data;
232         }
233
234         ret = extract_wim_resource_to_fd(lte, out_fd, wim_resource_size(lte));
235         if (ret != 0) {
236                 ERROR("Failed to extract resource to `%s'", output_path);
237                 goto out;
238         }
239
240 out_extract_unix_data:
241         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
242                 struct wimlib_unix_data unix_data;
243                 ret = inode_get_unix_data(inode, &unix_data, NULL);
244                 if (ret > 0)
245                         ;
246                 else if (ret < 0)
247                         ret = 0;
248                 else
249                         ret = fd_apply_unix_data(out_fd, &unix_data);
250                 if (ret != 0)
251                         goto out;
252         }
253         if (lte)
254                 args->progress.extract.completed_bytes += wim_resource_size(lte);
255 out:
256         if (close(out_fd) != 0) {
257                 ERROR_WITH_ERRNO("Failed to close file `%s'", output_path);
258                 if (ret == 0)
259                         ret = WIMLIB_ERR_WRITE;
260         }
261         return ret;
262 }
263
264 static int extract_regular_file(struct wim_dentry *dentry,
265                                 struct apply_args *args,
266                                 const char *output_path)
267 {
268         struct wim_lookup_table_entry *lte;
269         const struct wim_inode *inode = dentry->d_inode;
270
271         lte = inode_unnamed_lte_resolved(inode);
272
273         if (lte && (args->extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
274                                            WIMLIB_EXTRACT_FLAG_HARDLINK)))
275         {
276                 if (lte->extracted_file) {
277                         return extract_regular_file_linked(dentry, output_path, args, lte);
278                 } else {
279                         lte->extracted_file = STRDUP(output_path);
280                         if (!lte->extracted_file)
281                                 return WIMLIB_ERR_NOMEM;
282                 }
283         }
284         return extract_regular_file_unlinked(dentry, args, output_path, lte);
285 }
286
287 static int extract_symlink(struct wim_dentry *dentry,
288                            struct apply_args *args,
289                            const char *output_path)
290 {
291         char target[4096];
292         ssize_t ret = inode_readlink(dentry->d_inode, target,
293                                      sizeof(target), args->w, 0);
294         struct wim_lookup_table_entry *lte;
295
296         if (ret <= 0) {
297                 ERROR("Could not read the symbolic link from dentry `%s'",
298                       dentry->full_path_utf8);
299                 return WIMLIB_ERR_INVALID_DENTRY;
300         }
301         ret = symlink(target, output_path);
302         if (ret != 0) {
303                 ERROR_WITH_ERRNO("Failed to symlink `%s' to `%s'",
304                                  output_path, target);
305                 return WIMLIB_ERR_LINK;
306         }
307         lte = inode_unnamed_lte_resolved(dentry->d_inode);
308         wimlib_assert(lte != NULL);
309         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
310                 struct wimlib_unix_data unix_data;
311                 ret = inode_get_unix_data(dentry->d_inode, &unix_data, NULL);
312                 if (ret > 0)
313                         ;
314                 else if (ret < 0)
315                         ret = 0;
316                 else
317                         ret = symlink_apply_unix_data(output_path, &unix_data);
318                 if (ret != 0)
319                         return ret;
320         }
321         args->progress.extract.completed_bytes += wim_resource_size(lte);
322         return 0;
323 }
324
325 static int extract_directory(struct wim_dentry *dentry,
326                              const char *output_path, bool is_root)
327 {
328         int ret;
329         struct stat stbuf;
330
331         ret = stat(output_path, &stbuf);
332         if (ret == 0) {
333                 if (S_ISDIR(stbuf.st_mode)) {
334                         /*if (!is_root)*/
335                                 /*WARNING("`%s' already exists", output_path);*/
336                         goto dir_exists;
337                 } else {
338                         ERROR("`%s' is not a directory", output_path);
339                         return WIMLIB_ERR_MKDIR;
340                 }
341         } else {
342                 if (errno != ENOENT) {
343                         ERROR_WITH_ERRNO("Failed to stat `%s'", output_path);
344                         return WIMLIB_ERR_STAT;
345                 }
346         }
347         if (mkdir(output_path, S_IRWXU | S_IRGRP | S_IXGRP |
348                                S_IROTH | S_IXOTH) != 0) {
349                 ERROR_WITH_ERRNO("Cannot create directory `%s'",
350                                  output_path);
351                 return WIMLIB_ERR_MKDIR;
352         }
353 dir_exists:
354         if (dentry) {
355                 struct wimlib_unix_data unix_data;
356                 ret = inode_get_unix_data(dentry->d_inode, &unix_data, NULL);
357                 if (ret > 0)
358                         ;
359                 else if (ret < 0)
360                         ret = 0;
361                 else
362                         ret = dir_apply_unix_data(output_path, &unix_data);
363         } else {
364                 ret = 0;
365         }
366         return ret;
367 }
368
369 /* Extracts a file, directory, or symbolic link from the WIM archive. */
370 static int apply_dentry_normal(struct wim_dentry *dentry, void *arg)
371 {
372         struct apply_args *args = arg;
373         struct wim_inode *inode = dentry->d_inode;
374         size_t len;
375
376         len = strlen(args->target);
377         char output_path[len + dentry->full_path_utf8_len + 1];
378         memcpy(output_path, args->target, len);
379         memcpy(output_path + len, dentry->full_path_utf8, dentry->full_path_utf8_len);
380         output_path[len + dentry->full_path_utf8_len] = '\0';
381
382         if (inode_is_symlink(inode))
383                 return extract_symlink(dentry, args, output_path);
384         else if (inode_is_directory(inode))
385                 return extract_directory((args->extract_flags &
386                                            WIMLIB_EXTRACT_FLAG_UNIX_DATA) ? dentry : NULL,
387                                          output_path, false);
388         else
389                 return extract_regular_file(dentry, args, output_path);
390 }
391
392 /* Apply timestamps to an extracted file or directory */
393 static int apply_dentry_timestamps_normal(struct wim_dentry *dentry, void *arg)
394 {
395         struct apply_args *args = arg;
396         size_t len = strlen(args->target);
397         char output_path[len + dentry->full_path_utf8_len + 1];
398         const struct wim_inode *inode = dentry->d_inode;
399         int ret;
400
401         memcpy(output_path, args->target, len);
402         memcpy(output_path + len, dentry->full_path_utf8, dentry->full_path_utf8_len);
403         output_path[len + dentry->full_path_utf8_len] = '\0';
404
405         /* Convert the WIM timestamps, which are accurate to 100 nanoseconds,
406          * into struct timeval's. */
407         struct timeval tv[2];
408         wim_timestamp_to_timeval(inode->i_last_access_time, &tv[0]);
409         wim_timestamp_to_timeval(inode->i_last_write_time, &tv[1]);
410         #ifdef HAVE_LUTIMES
411         ret = lutimes(output_path, tv);
412         #else
413         ret = -1;
414         errno = ENOSYS;
415         #endif
416         if (ret != 0) {
417                 #ifdef HAVE_UTIME
418                 if (errno == ENOSYS) {
419                         struct utimbuf buf;
420                         buf.actime = wim_timestamp_to_unix(inode->i_last_access_time);
421                         buf.modtime = wim_timestamp_to_unix(inode->i_last_write_time);
422                         if (utime(output_path, &buf) == 0)
423                                 return 0;
424                 }
425                 #endif
426                 if (errno != ENOSYS || args->num_lutimes_warnings < 10) {
427                         /*WARNING_WITH_ERRNO("Failed to set timestamp on file `%s',*/
428                                             /*output_path");*/
429                         args->num_lutimes_warnings++;
430                 }
431         }
432         return 0;
433 }
434
435 /* Extract a dentry if it hasn't already been extracted, and either the dentry
436  * has no streams or WIMLIB_EXTRACT_FLAG_NO_STREAMS is not specified. */
437 static int maybe_apply_dentry(struct wim_dentry *dentry, void *arg)
438 {
439         struct apply_args *args = arg;
440         int ret;
441
442         if (dentry->is_extracted)
443                 return 0;
444
445         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_STREAMS)
446                 if (inode_unnamed_lte_resolved(dentry->d_inode))
447                         return 0;
448
449         if ((args->extract_flags & WIMLIB_EXTRACT_FLAG_VERBOSE) &&
450              args->progress_func) {
451                 args->progress.extract.cur_path = dentry->full_path_utf8;
452                 args->progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY,
453                                     &args->progress);
454         }
455         ret = args->apply_dentry(dentry, args);
456         if (ret == 0)
457                 dentry->is_extracted = 1;
458         return ret;
459 }
460
461 static int cmp_streams_by_wim_position(const void *p1, const void *p2)
462 {
463         const struct wim_lookup_table_entry *lte1, *lte2;
464         lte1 = *(const struct wim_lookup_table_entry**)p1;
465         lte2 = *(const struct wim_lookup_table_entry**)p2;
466         if (lte1->resource_entry.offset < lte2->resource_entry.offset)
467                 return -1;
468         else if (lte1->resource_entry.offset > lte2->resource_entry.offset)
469                 return 1;
470         else
471                 return 0;
472 }
473
474 static int sort_stream_list_by_wim_position(struct list_head *stream_list)
475 {
476         struct list_head *cur;
477         size_t num_streams;
478         struct wim_lookup_table_entry **array;
479         size_t i;
480         size_t array_size;
481
482         num_streams = 0;
483         list_for_each(cur, stream_list)
484                 num_streams++;
485         array_size = num_streams * sizeof(array[0]);
486         array = MALLOC(array_size);
487         if (!array) {
488                 ERROR("Failed to allocate %zu bytes to sort stream entries",
489                       array_size);
490                 return WIMLIB_ERR_NOMEM;
491         }
492         cur = stream_list->next;
493         for (i = 0; i < num_streams; i++) {
494                 array[i] = container_of(cur, struct wim_lookup_table_entry, staging_list);
495                 cur = cur->next;
496         }
497
498         qsort(array, num_streams, sizeof(array[0]), cmp_streams_by_wim_position);
499
500         INIT_LIST_HEAD(stream_list);
501         for (i = 0; i < num_streams; i++)
502                 list_add_tail(&array[i]->staging_list, stream_list);
503         FREE(array);
504         return 0;
505 }
506
507 static void calculate_bytes_to_extract(struct list_head *stream_list,
508                                        int extract_flags,
509                                        union wimlib_progress_info *progress)
510 {
511         struct wim_lookup_table_entry *lte;
512         u64 total_bytes = 0;
513         u64 num_streams = 0;
514
515         /* For each stream to be extracted... */
516         list_for_each_entry(lte, stream_list, staging_list) {
517                 if (extract_flags &
518                     (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
519                 {
520                         /* In the symlink or hard link extraction mode, each
521                          * stream will be extracted one time regardless of how
522                          * many dentries share the stream. */
523                         wimlib_assert(!(extract_flags & WIMLIB_EXTRACT_FLAG_NTFS));
524                         if (!lte->extracted_file) {
525                                 num_streams++;
526                                 total_bytes += wim_resource_size(lte);
527                         }
528                 } else {
529                         num_streams += lte->out_refcnt;
530                         total_bytes += lte->out_refcnt * wim_resource_size(lte);
531                 }
532         }
533         progress->extract.num_streams = num_streams;
534         progress->extract.total_bytes = total_bytes;
535         progress->extract.completed_bytes = 0;
536 }
537
538 static void maybe_add_stream_for_extraction(struct wim_lookup_table_entry *lte,
539                                             struct list_head *stream_list)
540 {
541         if (++lte->out_refcnt == 1) {
542                 INIT_LIST_HEAD(&lte->inode_list);
543                 list_add_tail(&lte->staging_list, stream_list);
544         }
545 }
546
547 static void inode_find_streams_for_extraction(struct wim_inode *inode,
548                                               struct list_head *stream_list,
549                                               int extract_flags)
550 {
551         struct wim_lookup_table_entry *lte;
552         bool inode_added = false;
553
554         lte = inode_unnamed_lte_resolved(inode);
555         if (lte) {
556                 maybe_add_stream_for_extraction(lte, stream_list);
557                 list_add_tail(&inode->i_lte_inode_list, &lte->inode_list);
558                 inode_added = true;
559         }
560 #ifdef WITH_NTFS_3G
561         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
562                 for (unsigned i = 0; i < inode->i_num_ads; i++) {
563                         if (inode->i_ads_entries[i].stream_name_len != 0) {
564                                 lte = inode->i_ads_entries[i].lte;
565                                 if (lte) {
566                                         maybe_add_stream_for_extraction(lte,
567                                                                         stream_list);
568                                         if (!inode_added) {
569                                                 list_add_tail(&inode->i_lte_inode_list,
570                                                               &lte->inode_list);
571                                                 inode_added = true;
572                                         }
573                                 }
574                         }
575                 }
576         }
577 #endif
578 }
579
580 static void find_streams_for_extraction(struct hlist_head *inode_list,
581                                         struct list_head *stream_list,
582                                         struct wim_lookup_table *lookup_table,
583                                         int extract_flags)
584 {
585         struct wim_inode *inode;
586         struct hlist_node *cur;
587         struct wim_dentry *dentry;
588
589         for_lookup_table_entry(lookup_table, lte_zero_out_refcnt, NULL);
590         INIT_LIST_HEAD(stream_list);
591         hlist_for_each_entry(inode, cur, inode_list, i_hlist) {
592                 if (!inode->i_resolved)
593                         inode_resolve_ltes(inode, lookup_table);
594                 inode_for_each_dentry(dentry, inode)
595                         dentry->is_extracted = 0;
596                 inode_find_streams_for_extraction(inode, stream_list,
597                                                   extract_flags);
598         }
599 }
600
601 struct apply_operations {
602         int (*apply_dentry)(struct wim_dentry *dentry, void *arg);
603         int (*apply_dentry_timestamps)(struct wim_dentry *dentry, void *arg);
604 };
605
606 static const struct apply_operations normal_apply_operations = {
607         .apply_dentry = apply_dentry_normal,
608         .apply_dentry_timestamps = apply_dentry_timestamps_normal,
609 };
610
611 #ifdef WITH_NTFS_3G
612 static const struct apply_operations ntfs_apply_operations = {
613         .apply_dentry = apply_dentry_ntfs,
614         .apply_dentry_timestamps = apply_dentry_timestamps_ntfs,
615 };
616 #endif
617
618 static int apply_stream_list(struct list_head *stream_list,
619                              struct apply_args *args,
620                              const struct apply_operations *ops,
621                              wimlib_progress_func_t progress_func)
622 {
623         uint64_t bytes_per_progress = args->progress.extract.total_bytes / 100;
624         uint64_t next_progress = bytes_per_progress;
625         struct wim_lookup_table_entry *lte;
626         struct wim_inode *inode;
627         struct wim_dentry *dentry;
628         int ret;
629
630         /* This complicated loop is essentially looping through the dentries,
631          * although dentries may be visited more than once (if a dentry contains
632          * two different nonempty streams) or not at all (if a dentry contains
633          * no non-empty streams).
634          *
635          * The outer loop is over the distinct streams to be extracted so that
636          * sequential reading of the WIM can be implemented. */
637
638         /* For each distinct stream to be extracted */
639         list_for_each_entry(lte, stream_list, staging_list) {
640                 /* For each inode that contains the stream */
641                 list_for_each_entry(inode, &lte->inode_list, i_lte_inode_list) {
642                         /* For each dentry that points to the inode */
643                         inode_for_each_dentry(dentry, inode) {
644                                 /* Extract the dentry if it was not already
645                                  * extracted */
646                                 ret = maybe_apply_dentry(dentry, args);
647                                 if (ret != 0)
648                                         return ret;
649                                 if (progress_func &&
650                                     args->progress.extract.completed_bytes >= next_progress)
651                                 {
652                                         progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS,
653                                                       &args->progress);
654                                         if (args->progress.extract.completed_bytes >=
655                                             args->progress.extract.total_bytes)
656                                         {
657                                                 next_progress = ~0ULL;
658                                         } else {
659                                                 next_progress =
660                                                         min (args->progress.extract.completed_bytes +
661                                                              bytes_per_progress,
662                                                              args->progress.extract.total_bytes);
663                                         }
664                                 }
665                         }
666                 }
667         }
668         return 0;
669 }
670
671 /* Extracts the image @image from the WIM @w to the directory or NTFS volume
672  * @target. */
673 static int extract_single_image(WIMStruct *w, int image,
674                                 const char *target, int extract_flags,
675                                 wimlib_progress_func_t progress_func)
676 {
677         int ret;
678         struct list_head stream_list;
679         struct hlist_head *inode_list;
680
681         struct apply_args args;
682         const struct apply_operations *ops;
683
684         args.w                    = w;
685         args.target               = target;
686         args.extract_flags        = extract_flags;
687         args.num_lutimes_warnings = 0;
688         args.stream_list          = &stream_list;
689         args.progress_func        = progress_func;
690
691         if (progress_func) {
692                 args.progress.extract.wimfile_name = w->filename;
693                 args.progress.extract.image = image;
694                 args.progress.extract.extract_flags = (extract_flags &
695                                                        WIMLIB_EXTRACT_MASK_PUBLIC);
696                 args.progress.extract.image_name = wimlib_get_image_name(w, image);
697                 args.progress.extract.target = target;
698         }
699
700 #ifdef WITH_NTFS_3G
701         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
702                 args.vol = ntfs_mount(target, 0);
703                 if (!args.vol) {
704                         ERROR_WITH_ERRNO("Failed to mount NTFS volume `%s'", target);
705                         return WIMLIB_ERR_NTFS_3G;
706                 }
707                 ops = &ntfs_apply_operations;
708         } else
709 #endif
710                 ops = &normal_apply_operations;
711
712         ret = select_wim_image(w, image);
713         if (ret != 0)
714                 goto out;
715
716         inode_list = &w->image_metadata[image - 1].inode_list;
717
718         /* Build a list of the streams that need to be extracted */
719         find_streams_for_extraction(inode_list, &stream_list,
720                                     w->lookup_table, extract_flags);
721
722         /* Calculate the number of bytes of data that will be extracted */
723         calculate_bytes_to_extract(&stream_list, extract_flags,
724                                    &args.progress);
725
726         if (progress_func) {
727                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN,
728                               &args.progress);
729         }
730
731         /* If a sequential extraction was specified, sort the streams to be
732          * extracted by their position in the WIM file, so that the WIM file can
733          * be read sequentially. */
734         if (extract_flags & WIMLIB_EXTRACT_FLAG_SEQUENTIAL) {
735                 ret = sort_stream_list_by_wim_position(&stream_list);
736                 if (ret != 0) {
737                         WARNING("Falling back to non-sequential extraction");
738                         extract_flags &= ~WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
739                 }
740         }
741
742         if (progress_func) {
743                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN,
744                               &args.progress);
745         }
746
747         /* Make the directory structure and extract empty files */
748         args.extract_flags |= WIMLIB_EXTRACT_FLAG_NO_STREAMS;
749         args.apply_dentry = ops->apply_dentry;
750         ret = for_dentry_in_tree(wim_root_dentry(w), maybe_apply_dentry, &args);
751         args.extract_flags &= ~WIMLIB_EXTRACT_FLAG_NO_STREAMS;
752         if (ret != 0)
753                 goto out;
754
755         if (progress_func) {
756                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_END,
757                               &args.progress);
758         }
759
760         /* Extract non-empty files */
761         ret = apply_stream_list(&stream_list, &args, ops, progress_func);
762         if (ret != 0)
763                 goto out;
764
765         if (progress_func) {
766                 progress_func(WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS,
767                               &args.progress);
768         }
769
770         /* Apply timestamps */
771         ret = for_dentry_in_tree_depth(wim_root_dentry(w),
772                                        ops->apply_dentry_timestamps, &args);
773         if (ret != 0)
774                 goto out;
775
776         if (progress_func) {
777                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END,
778                               &args.progress);
779         }
780 out:
781 #ifdef WITH_NTFS_3G
782         /* Unmount the NTFS volume */
783         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
784                 if (ntfs_umount(args.vol, FALSE) != 0) {
785                         ERROR_WITH_ERRNO("Failed to unmount NTFS volume `%s'", args.target);
786                         if (ret == 0)
787                                 ret = WIMLIB_ERR_NTFS_3G;
788                 }
789         }
790 #endif
791         return ret;
792 }
793
794
795 /* Extracts all images from the WIM to the directory @target, with the images
796  * placed in subdirectories named by their image names. */
797 static int extract_all_images(WIMStruct *w, const char *target,
798                               int extract_flags,
799                               wimlib_progress_func_t progress_func)
800 {
801         size_t image_name_max_len = max(xml_get_max_image_name_len(w), 20);
802         size_t output_path_len = strlen(target);
803         char buf[output_path_len + 1 + image_name_max_len + 1];
804         int ret;
805         int image;
806         const char *image_name;
807
808         ret = extract_directory(NULL, target, true);
809         if (ret != 0)
810                 return ret;
811
812         memcpy(buf, target, output_path_len);
813         buf[output_path_len] = '/';
814         for (image = 1; image <= w->hdr.image_count; image++) {
815                 image_name = wimlib_get_image_name(w, image);
816                 if (image_name && *image_name) {
817                         strcpy(buf + output_path_len + 1, image_name);
818                 } else {
819                         /* Image name is empty. Use image number instead */
820                         sprintf(buf + output_path_len + 1, "%d", image);
821                 }
822                 ret = extract_single_image(w, image, buf, extract_flags,
823                                            progress_func);
824                 if (ret != 0)
825                         return ret;
826         }
827         return 0;
828 }
829
830 /* Extracts a single image or all images from a WIM file to a directory or NTFS
831  * volume. */
832 WIMLIBAPI int wimlib_extract_image(WIMStruct *w,
833                                    int image,
834                                    const char *target,
835                                    int extract_flags,
836                                    WIMStruct **additional_swms,
837                                    unsigned num_additional_swms,
838                                    wimlib_progress_func_t progress_func)
839 {
840         struct wim_lookup_table *joined_tab, *w_tab_save;
841         int ret;
842
843         if (!target)
844                 return WIMLIB_ERR_INVALID_PARAM;
845
846         extract_flags &= WIMLIB_EXTRACT_MASK_PUBLIC;
847
848         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
849                         == (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
850                 return WIMLIB_ERR_INVALID_PARAM;
851
852         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
853 #ifdef WITH_NTFS_3G
854                 if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))) {
855                         ERROR("Cannot specify symlink or hardlink flags when applying\n"
856                               "        directly to a NTFS volume");
857                         return WIMLIB_ERR_INVALID_PARAM;
858                 }
859                 if (image == WIMLIB_ALL_IMAGES) {
860                         ERROR("Can only apply a single image when applying "
861                               "directly to a NTFS volume");
862                         return WIMLIB_ERR_INVALID_PARAM;
863                 }
864                 if (extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
865                         ERROR("Cannot restore UNIX-specific data in the NTFS extraction mode");
866                         return WIMLIB_ERR_INVALID_PARAM;
867                 }
868 #else
869                 ERROR("wimlib was compiled without support for NTFS-3g, so");
870                 ERROR("we cannot apply a WIM image directly to a NTFS volume");
871                 return WIMLIB_ERR_UNSUPPORTED;
872 #endif
873         }
874
875         ret = verify_swm_set(w, additional_swms, num_additional_swms);
876         if (ret != 0)
877                 return ret;
878
879         if (num_additional_swms) {
880                 ret = new_joined_lookup_table(w, additional_swms,
881                                               num_additional_swms, &joined_tab);
882                 if (ret != 0)
883                         return ret;
884                 w_tab_save = w->lookup_table;
885                 w->lookup_table = joined_tab;
886         }
887
888         if (image == WIMLIB_ALL_IMAGES) {
889                 extract_flags |= WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
890                 ret = extract_all_images(w, target, extract_flags,
891                                          progress_func);
892         } else {
893                 extract_flags &= ~WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
894                 ret = extract_single_image(w, image, target, extract_flags,
895                                            progress_func);
896         }
897
898         if (extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
899                              WIMLIB_EXTRACT_FLAG_HARDLINK))
900         {
901                 for_lookup_table_entry(w->lookup_table,
902                                        lte_free_extracted_file,
903                                        NULL);
904         }
905
906         if (num_additional_swms) {
907                 free_lookup_table(w->lookup_table);
908                 w->lookup_table = w_tab_save;
909         }
910         return ret;
911 }