rpfix extract on UNIX
[wimlib] / src / extract_image.c
1 /*
2  * extract_image.c
3  *
4  * Support for extracting WIM files.
5  */
6
7 /*
8  * Copyright (C) 2012, 2013 Eric Biggers
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
12  * wimlib is free software; you can redistribute it and/or modify it under the
13  * terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your option)
15  * any later version.
16  *
17  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19  * A PARTICULAR PURPOSE. See the GNU General Public License for more
20  * details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with wimlib; if not, see http://www.gnu.org/licenses/.
24  */
25
26 #include "config.h"
27
28 #include <dirent.h>
29
30 #ifdef __WIN32__
31 #  include "win32.h"
32 #else
33 #  ifdef HAVE_UTIME_H
34 #    include <utime.h>
35 #  endif
36 #  include "timestamp.h"
37 #  include <sys/time.h>
38 #endif
39
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <sys/stat.h>
45 #include <unistd.h>
46
47 #include "dentry.h"
48 #include "lookup_table.h"
49 #include "wimlib_internal.h"
50 #include "xml.h"
51
52 #ifdef WITH_NTFS_3G
53 #  include <ntfs-3g/volume.h>
54 #endif
55
56 #ifdef HAVE_ALLOCA_H
57 #  include <alloca.h>
58 #endif
59
60 #ifndef __WIN32__
61
62 /* Returns the number of components of @path.  */
63 static unsigned
64 get_num_path_components(const char *path)
65 {
66         unsigned num_components = 0;
67         while (*path) {
68                 while (*path == '/')
69                         path++;
70                 if (*path)
71                         num_components++;
72                 while (*path && *path != '/')
73                         path++;
74         }
75         return num_components;
76 }
77
78 static const char *
79 path_next_part(const char *path)
80 {
81         while (*path && *path != '/')
82                 path++;
83         while (*path && *path == '/')
84                 path++;
85         return path;
86 }
87
88 static int
89 extract_regular_file_linked(struct wim_dentry *dentry,
90                             const char *output_path,
91                             struct apply_args *args,
92                             struct wim_lookup_table_entry *lte)
93 {
94         /* This mode overrides the normal hard-link extraction and
95          * instead either symlinks or hardlinks *all* identical files in
96          * the WIM, even if they are in a different image (in the case
97          * of a multi-image extraction) */
98
99         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_HARDLINK) {
100                 if (link(lte->extracted_file, output_path) != 0) {
101                         ERROR_WITH_ERRNO("Failed to hard link "
102                                          "`%s' to `%s'",
103                                          output_path, lte->extracted_file);
104                         return WIMLIB_ERR_LINK;
105                 }
106         } else {
107                 int num_path_components;
108                 int num_output_dir_path_components;
109                 size_t extracted_file_len;
110                 char *p;
111                 const char *p2;
112                 size_t i;
113
114                 num_path_components = get_num_path_components(dentry->_full_path) - 1;
115                 num_output_dir_path_components = get_num_path_components(args->target);
116
117                 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_MULTI_IMAGE) {
118                         num_path_components++;
119                         num_output_dir_path_components--;
120                 }
121                 extracted_file_len = strlen(lte->extracted_file);
122
123                 char buf[extracted_file_len + 3 * num_path_components + 1];
124                 p = &buf[0];
125
126                 for (i = 0; i < num_path_components; i++) {
127                         *p++ = '.';
128                         *p++ = '.';
129                         *p++ = '/';
130                 }
131                 p2 = lte->extracted_file;
132                 while (*p2 == '/')
133                         p2++;
134                 while (num_output_dir_path_components > 0) {
135                         p2 = path_next_part(p2);
136                         num_output_dir_path_components--;
137                 }
138                 strcpy(p, p2);
139                 if (symlink(buf, output_path) != 0) {
140                         ERROR_WITH_ERRNO("Failed to symlink `%s' to `%s'",
141                                          buf, lte->extracted_file);
142                         return WIMLIB_ERR_LINK;
143                 }
144         }
145         return 0;
146 }
147
148 static int
149 symlink_apply_unix_data(const char *link,
150                         const struct wimlib_unix_data *unix_data)
151 {
152         if (lchown(link, unix_data->uid, unix_data->gid)) {
153                 if (errno == EPERM) {
154                         /* Ignore */
155                         WARNING_WITH_ERRNO("failed to set symlink UNIX owner/group");
156                 } else {
157                         ERROR_WITH_ERRNO("failed to set symlink UNIX owner/group");
158                         return WIMLIB_ERR_INVALID_DENTRY;
159                 }
160         }
161         return 0;
162 }
163
164 static int
165 fd_apply_unix_data(int fd, const struct wimlib_unix_data *unix_data)
166 {
167         if (fchown(fd, unix_data->uid, unix_data->gid)) {
168                 if (errno == EPERM) {
169                         WARNING_WITH_ERRNO("failed to set file UNIX owner/group");
170                         /* Ignore? */
171                 } else {
172                         ERROR_WITH_ERRNO("failed to set file UNIX owner/group");
173                         return WIMLIB_ERR_INVALID_DENTRY;
174                 }
175         }
176
177         if (fchmod(fd, unix_data->mode)) {
178                 if (errno == EPERM) {
179                         WARNING_WITH_ERRNO("failed to set UNIX file mode");
180                         /* Ignore? */
181                 } else {
182                         ERROR_WITH_ERRNO("failed to set UNIX file mode");
183                         return WIMLIB_ERR_INVALID_DENTRY;
184                 }
185         }
186         return 0;
187 }
188
189 static int
190 dir_apply_unix_data(const char *dir, const struct wimlib_unix_data *unix_data)
191 {
192         int dfd = open(dir, O_RDONLY);
193         int ret;
194         if (dfd >= 0) {
195                 ret = fd_apply_unix_data(dfd, unix_data);
196                 if (close(dfd)) {
197                         ERROR_WITH_ERRNO("can't close directory `%s'", dir);
198                         ret = WIMLIB_ERR_MKDIR;
199                 }
200         } else {
201                 ERROR_WITH_ERRNO("can't open directory `%s'", dir);
202                 ret = WIMLIB_ERR_MKDIR;
203         }
204         return ret;
205 }
206
207 static int
208 extract_regular_file_unlinked(struct wim_dentry *dentry,
209                               struct apply_args *args,
210                               const char *output_path,
211                               struct wim_lookup_table_entry *lte)
212 {
213         /* Normal mode of extraction.  Regular files and hard links are
214          * extracted in the way that they appear in the WIM. */
215
216         int out_fd;
217         int ret;
218         struct wim_inode *inode = dentry->d_inode;
219
220         if (!((args->extract_flags & WIMLIB_EXTRACT_FLAG_MULTI_IMAGE)
221                 && (args->extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
222                                      WIMLIB_EXTRACT_FLAG_HARDLINK))))
223         {
224                 /* If the dentry is part of a hard link set of at least 2
225                  * dentries and one of the other dentries has already been
226                  * extracted, make a hard link to the file corresponding to this
227                  * already-extracted directory.  Otherwise, extract the file and
228                  * set the inode->i_extracted_file field so that other dentries
229                  * in the hard link group can link to it. */
230                 if (inode->i_nlink > 1) {
231                         if (inode->i_extracted_file) {
232                                 DEBUG("Extracting hard link `%s' => `%s'",
233                                       output_path, inode->i_extracted_file);
234                                 if (link(inode->i_extracted_file, output_path) != 0) {
235                                         ERROR_WITH_ERRNO("Failed to hard link "
236                                                          "`%s' to `%s'",
237                                                          output_path,
238                                                          inode->i_extracted_file);
239                                         return WIMLIB_ERR_LINK;
240                                 }
241                                 return 0;
242                         }
243                         FREE(inode->i_extracted_file);
244                         inode->i_extracted_file = STRDUP(output_path);
245                         if (!inode->i_extracted_file) {
246                                 ERROR("Failed to allocate memory for filename");
247                                 return WIMLIB_ERR_NOMEM;
248                         }
249                 }
250         }
251
252         /* Extract the contents of the file to @output_path. */
253
254         out_fd = open(output_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
255         if (out_fd == -1) {
256                 ERROR_WITH_ERRNO("Failed to open the file `%s' for writing",
257                                  output_path);
258                 return WIMLIB_ERR_OPEN;
259         }
260
261         if (!lte) {
262                 /* Empty file with no lookup table entry */
263                 DEBUG("Empty file `%s'.", output_path);
264                 ret = 0;
265                 goto out_extract_unix_data;
266         }
267
268         ret = extract_wim_resource_to_fd(lte, out_fd, wim_resource_size(lte));
269         if (ret) {
270                 ERROR("Failed to extract resource to `%s'", output_path);
271                 goto out;
272         }
273
274 out_extract_unix_data:
275         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
276                 struct wimlib_unix_data unix_data;
277                 ret = inode_get_unix_data(inode, &unix_data, NULL);
278                 if (ret > 0)
279                         ;
280                 else if (ret < 0)
281                         ret = 0;
282                 else
283                         ret = fd_apply_unix_data(out_fd, &unix_data);
284                 if (ret != 0)
285                         goto out;
286         }
287         if (lte)
288                 args->progress.extract.completed_bytes += wim_resource_size(lte);
289 out:
290         if (close(out_fd) != 0) {
291                 ERROR_WITH_ERRNO("Failed to close file `%s'", output_path);
292                 if (ret == 0)
293                         ret = WIMLIB_ERR_WRITE;
294         }
295         return ret;
296 }
297
298 static int
299 extract_regular_file(struct wim_dentry *dentry,
300                      struct apply_args *args,
301                      const char *output_path)
302 {
303         struct wim_lookup_table_entry *lte;
304         const struct wim_inode *inode = dentry->d_inode;
305
306         lte = inode_unnamed_lte_resolved(inode);
307
308         if (lte && (args->extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
309                                            WIMLIB_EXTRACT_FLAG_HARDLINK)))
310         {
311                 if (lte->extracted_file) {
312                         return extract_regular_file_linked(dentry, output_path, args, lte);
313                 } else {
314                         lte->extracted_file = STRDUP(output_path);
315                         if (!lte->extracted_file)
316                                 return WIMLIB_ERR_NOMEM;
317                 }
318         }
319         return extract_regular_file_unlinked(dentry, args, output_path, lte);
320 }
321
322 static int
323 extract_symlink(struct wim_dentry *dentry,
324                 struct apply_args *args,
325                 const char *output_path)
326 {
327         char target[4096 + args->target_realpath_len];
328         char *fixed_target;
329
330         ssize_t ret = inode_readlink(dentry->d_inode,
331                                      target + args->target_realpath_len,
332                                      sizeof(target) - args->target_realpath_len - 1,
333                                      args->w, false);
334         struct wim_lookup_table_entry *lte;
335
336         if (ret <= 0) {
337                 ERROR("Could not read the symbolic link from dentry `%s'",
338                       dentry->_full_path);
339                 return WIMLIB_ERR_INVALID_DENTRY;
340         }
341         target[args->target_realpath_len + ret] = '\0';
342         if (target[args->target_realpath_len] == '/' &&
343             args->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
344         {
345                 memcpy(target, args->target_realpath,
346                        args->target_realpath_len);
347                 fixed_target = target;
348         } else {
349                 fixed_target = target + args->target_realpath_len;
350         }
351         ret = symlink(fixed_target, output_path);
352         if (ret) {
353                 ERROR_WITH_ERRNO("Failed to symlink `%s' to `%s'",
354                                  output_path, fixed_target);
355                 return WIMLIB_ERR_LINK;
356         }
357         lte = inode_unnamed_lte_resolved(dentry->d_inode);
358         wimlib_assert(lte != NULL);
359         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
360                 struct wimlib_unix_data unix_data;
361                 ret = inode_get_unix_data(dentry->d_inode, &unix_data, NULL);
362                 if (ret > 0)
363                         ;
364                 else if (ret < 0)
365                         ret = 0;
366                 else
367                         ret = symlink_apply_unix_data(output_path, &unix_data);
368                 if (ret)
369                         return ret;
370         }
371         args->progress.extract.completed_bytes += wim_resource_size(lte);
372         return 0;
373 }
374
375 #endif /* !__WIN32__ */
376
377 static int
378 extract_directory(struct wim_dentry *dentry,
379                   const tchar *output_path, bool is_root)
380 {
381         int ret;
382         struct stat stbuf;
383
384         ret = tstat(output_path, &stbuf);
385         if (ret == 0) {
386                 if (S_ISDIR(stbuf.st_mode)) {
387                         /*if (!is_root)*/
388                                 /*WARNING("`%s' already exists", output_path);*/
389                         goto dir_exists;
390                 } else {
391                         ERROR("`%"TS"' is not a directory", output_path);
392                         return WIMLIB_ERR_MKDIR;
393                 }
394         } else {
395                 if (errno != ENOENT) {
396                         ERROR_WITH_ERRNO("Failed to stat `%"TS"'", output_path);
397                         return WIMLIB_ERR_STAT;
398                 }
399         }
400
401         if (tmkdir(output_path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH))
402         {
403                 ERROR_WITH_ERRNO("Cannot create directory `%"TS"'", output_path);
404                 return WIMLIB_ERR_MKDIR;
405         }
406 dir_exists:
407         ret = 0;
408 #ifndef __WIN32__
409         if (dentry) {
410                 struct wimlib_unix_data unix_data;
411                 ret = inode_get_unix_data(dentry->d_inode, &unix_data, NULL);
412                 if (ret > 0)
413                         ;
414                 else if (ret < 0)
415                         ret = 0;
416                 else
417                         ret = dir_apply_unix_data(output_path, &unix_data);
418         }
419 #endif
420         return ret;
421 }
422
423 #ifndef __WIN32__
424 static int unix_do_apply_dentry(const char *output_path,
425                                 size_t output_path_len,
426                                 struct wim_dentry *dentry,
427                                 struct apply_args *args)
428 {
429         const struct wim_inode *inode = dentry->d_inode;
430
431         if (inode_is_symlink(inode))
432                 return extract_symlink(dentry, args, output_path);
433         else if (inode_is_directory(inode))
434                 return extract_directory((args->extract_flags &
435                                            WIMLIB_EXTRACT_FLAG_UNIX_DATA) ? dentry : NULL,
436                                          output_path, false);
437         else
438                 return extract_regular_file(dentry, args, output_path);
439 }
440
441 static int
442 unix_do_apply_dentry_timestamps(const char *output_path,
443                                 size_t output_path_len,
444                                 const struct wim_dentry *dentry,
445                                 struct apply_args *args)
446 {
447         int ret;
448         const struct wim_inode *inode = dentry->d_inode;
449
450 #ifdef HAVE_UTIMENSAT
451         /* Convert the WIM timestamps, which are accurate to 100 nanoseconds,
452          * into `struct timespec's for passing to utimensat(), which is accurate
453          * to 1 nanosecond. */
454
455         struct timespec ts[2];
456         ts[0] = wim_timestamp_to_timespec(inode->i_last_access_time);
457         ts[1] = wim_timestamp_to_timespec(inode->i_last_write_time);
458         ret = utimensat(AT_FDCWD, output_path, ts, AT_SYMLINK_NOFOLLOW);
459         if (ret)
460                 ret = errno;
461 #else
462         ret = ENOSYS;
463 #endif
464
465         if (ret == ENOSYS) {
466                 /* utimensat() not implemented or not available */
467         #ifdef HAVE_LUTIMES
468                 /* Convert the WIM timestamps, which are accurate to 100
469                  * nanoseconds, into `struct timeval's for passing to lutimes(),
470                  * which is accurate to 1 microsecond. */
471                 struct timeval tv[2];
472                 tv[0] = wim_timestamp_to_timeval(inode->i_last_access_time);
473                 tv[1] = wim_timestamp_to_timeval(inode->i_last_write_time);
474                 ret = lutimes(output_path, tv);
475                 if (ret)
476                         ret = errno;
477         #endif
478         }
479
480         if (ret == ENOSYS) {
481                 /* utimensat() and lutimes() both not implemented or not
482                  * available */
483         #ifdef HAVE_UTIME
484                 /* Convert the WIM timestamps, which are accurate to 100
485                  * nanoseconds, into a `struct utimbuf's for passing to
486                  * utime(), which is accurate to 1 second. */
487                 struct utimbuf buf;
488                 buf.actime = wim_timestamp_to_unix(inode->i_last_access_time);
489                 buf.modtime = wim_timestamp_to_unix(inode->i_last_write_time);
490                 ret = utime(output_path, &buf);
491         #endif
492         }
493         if (ret && args->num_utime_warnings < 10) {
494                 WARNING_WITH_ERRNO("Failed to set timestamp on file `%s'",
495                                     output_path);
496                 args->num_utime_warnings++;
497         }
498         return 0;
499 }
500 #endif /* !__WIN32__ */
501
502 /* Extracts a file, directory, or symbolic link from the WIM archive. */
503 static int
504 apply_dentry_normal(struct wim_dentry *dentry, void *arg)
505 {
506         struct apply_args *args = arg;
507         tchar *output_path;
508         size_t len;
509
510         len = tstrlen(args->target);
511         if (dentry_is_root(dentry)) {
512                 output_path = (tchar*)args->target;
513         } else {
514                 output_path = alloca(len * sizeof(tchar) + dentry->full_path_nbytes +
515                                      sizeof(tchar));
516                 memcpy(output_path, args->target, len * sizeof(tchar));
517                 memcpy(output_path + len, dentry->_full_path, dentry->full_path_nbytes);
518                 len += dentry->full_path_nbytes / sizeof(tchar);
519                 output_path[len] = T('\0');
520         }
521 #ifdef __WIN32__
522         return win32_do_apply_dentry(output_path, len, dentry, args);
523 #else
524         return unix_do_apply_dentry(output_path, len, dentry, args);
525 #endif
526 }
527
528
529 /* Apply timestamps to an extracted file or directory */
530 static int
531 apply_dentry_timestamps_normal(struct wim_dentry *dentry, void *arg)
532 {
533         struct apply_args *args = arg;
534         size_t len;
535         tchar *output_path;
536
537         len = tstrlen(args->target);
538         if (dentry_is_root(dentry)) {
539                 output_path = (tchar*)args->target;
540         } else {
541                 output_path = alloca(len * sizeof(tchar) + dentry->full_path_nbytes +
542                                      sizeof(tchar));
543                 memcpy(output_path, args->target, len * sizeof(tchar));
544                 memcpy(output_path + len, dentry->_full_path, dentry->full_path_nbytes);
545                 len += dentry->full_path_nbytes / sizeof(tchar);
546                 output_path[len] = T('\0');
547         }
548
549
550 #ifdef __WIN32__
551         return win32_do_apply_dentry_timestamps(output_path, len, dentry, args);
552 #else
553         return unix_do_apply_dentry_timestamps(output_path, len, dentry, args);
554 #endif
555 }
556
557 /* Extract a dentry if it hasn't already been extracted, and either the dentry
558  * has no streams or WIMLIB_EXTRACT_FLAG_NO_STREAMS is not specified. */
559 static int
560 maybe_apply_dentry(struct wim_dentry *dentry, void *arg)
561 {
562         struct apply_args *args = arg;
563         int ret;
564
565         if (dentry->is_extracted)
566                 return 0;
567
568         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_STREAMS)
569                 if (inode_unnamed_lte_resolved(dentry->d_inode))
570                         return 0;
571
572         if ((args->extract_flags & WIMLIB_EXTRACT_FLAG_VERBOSE) &&
573              args->progress_func) {
574                 args->progress.extract.cur_path = dentry->_full_path;
575                 args->progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY,
576                                     &args->progress);
577         }
578         ret = args->apply_dentry(dentry, args);
579         if (ret == 0)
580                 dentry->is_extracted = 1;
581         return ret;
582 }
583
584 static void
585 calculate_bytes_to_extract(struct list_head *stream_list,
586                            int extract_flags,
587                            union wimlib_progress_info *progress)
588 {
589         struct wim_lookup_table_entry *lte;
590         u64 total_bytes = 0;
591         u64 num_streams = 0;
592
593         /* For each stream to be extracted... */
594         list_for_each_entry(lte, stream_list, extraction_list) {
595                 if (extract_flags &
596                     (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
597                 {
598                         /* In the symlink or hard link extraction mode, each
599                          * stream will be extracted one time regardless of how
600                          * many dentries share the stream. */
601                         wimlib_assert(!(extract_flags & WIMLIB_EXTRACT_FLAG_NTFS));
602                         if (!lte->extracted_file) {
603                                 num_streams++;
604                                 total_bytes += wim_resource_size(lte);
605                         }
606                 } else {
607                         num_streams += lte->out_refcnt;
608                         total_bytes += lte->out_refcnt * wim_resource_size(lte);
609                 }
610         }
611         progress->extract.num_streams = num_streams;
612         progress->extract.total_bytes = total_bytes;
613         progress->extract.completed_bytes = 0;
614 }
615
616 static void
617 maybe_add_stream_for_extraction(struct wim_lookup_table_entry *lte,
618                                 struct list_head *stream_list)
619 {
620         if (++lte->out_refcnt == 1) {
621                 INIT_LIST_HEAD(&lte->inode_list);
622                 list_add_tail(&lte->extraction_list, stream_list);
623         }
624 }
625
626 static void
627 inode_find_streams_for_extraction(struct wim_inode *inode,
628                                   struct list_head *stream_list,
629                                   int extract_flags)
630 {
631         struct wim_lookup_table_entry *lte;
632         bool inode_added = false;
633
634         lte = inode_unnamed_lte_resolved(inode);
635         if (lte) {
636                 maybe_add_stream_for_extraction(lte, stream_list);
637                 list_add_tail(&inode->i_lte_inode_list, &lte->inode_list);
638                 inode_added = true;
639         }
640 #ifdef WITH_NTFS_3G
641         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
642                 for (unsigned i = 0; i < inode->i_num_ads; i++) {
643                         if (inode->i_ads_entries[i].stream_name_nbytes != 0) {
644                                 lte = inode->i_ads_entries[i].lte;
645                                 if (lte) {
646                                         maybe_add_stream_for_extraction(lte,
647                                                                         stream_list);
648                                         if (!inode_added) {
649                                                 list_add_tail(&inode->i_lte_inode_list,
650                                                               &lte->inode_list);
651                                                 inode_added = true;
652                                         }
653                                 }
654                         }
655                 }
656         }
657 #endif
658 }
659
660 static void
661 find_streams_for_extraction(struct wim_image_metadata *imd,
662                             struct list_head *stream_list,
663                             struct wim_lookup_table *lookup_table,
664                             int extract_flags)
665 {
666         struct wim_inode *inode;
667         struct wim_dentry *dentry;
668
669         for_lookup_table_entry(lookup_table, lte_zero_out_refcnt, NULL);
670         INIT_LIST_HEAD(stream_list);
671         image_for_each_inode(inode, imd) {
672                 if (!inode->i_resolved)
673                         inode_resolve_ltes(inode, lookup_table);
674                 inode_for_each_dentry(dentry, inode)
675                         dentry->is_extracted = 0;
676                 inode_find_streams_for_extraction(inode, stream_list,
677                                                   extract_flags);
678         }
679 }
680
681 struct apply_operations {
682         int (*apply_dentry)(struct wim_dentry *dentry, void *arg);
683         int (*apply_dentry_timestamps)(struct wim_dentry *dentry, void *arg);
684 };
685
686 static const struct apply_operations normal_apply_operations = {
687         .apply_dentry = apply_dentry_normal,
688         .apply_dentry_timestamps = apply_dentry_timestamps_normal,
689 };
690
691 #ifdef WITH_NTFS_3G
692 static const struct apply_operations ntfs_apply_operations = {
693         .apply_dentry = apply_dentry_ntfs,
694         .apply_dentry_timestamps = apply_dentry_timestamps_ntfs,
695 };
696 #endif
697
698 static int
699 apply_stream_list(struct list_head *stream_list,
700                   struct apply_args *args,
701                   const struct apply_operations *ops,
702                   wimlib_progress_func_t progress_func)
703 {
704         uint64_t bytes_per_progress = args->progress.extract.total_bytes / 100;
705         uint64_t next_progress = bytes_per_progress;
706         struct wim_lookup_table_entry *lte;
707         struct wim_inode *inode;
708         struct wim_dentry *dentry;
709         int ret;
710
711         /* This complicated loop is essentially looping through the dentries,
712          * although dentries may be visited more than once (if a dentry contains
713          * two different nonempty streams) or not at all (if a dentry contains
714          * no non-empty streams).
715          *
716          * The outer loop is over the distinct streams to be extracted so that
717          * sequential reading of the WIM can be implemented. */
718
719         /* For each distinct stream to be extracted */
720         list_for_each_entry(lte, stream_list, extraction_list) {
721                 /* For each inode that contains the stream */
722                 list_for_each_entry(inode, &lte->inode_list, i_lte_inode_list) {
723                         /* For each dentry that points to the inode */
724                         inode_for_each_dentry(dentry, inode) {
725                                 /* Extract the dentry if it was not already
726                                  * extracted */
727                                 ret = maybe_apply_dentry(dentry, args);
728                                 if (ret != 0)
729                                         return ret;
730                                 if (progress_func &&
731                                     args->progress.extract.completed_bytes >= next_progress)
732                                 {
733                                         progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS,
734                                                       &args->progress);
735                                         if (args->progress.extract.completed_bytes >=
736                                             args->progress.extract.total_bytes)
737                                         {
738                                                 next_progress = ~0ULL;
739                                         } else {
740                                                 next_progress =
741                                                         min (args->progress.extract.completed_bytes +
742                                                              bytes_per_progress,
743                                                              args->progress.extract.total_bytes);
744                                         }
745                                 }
746                         }
747                 }
748         }
749         return 0;
750 }
751
752 static int
753 sort_stream_list_by_wim_position(struct list_head *stream_list)
754 {
755         struct list_head *cur;
756         size_t num_streams;
757         struct wim_lookup_table_entry **array;
758         size_t i;
759         size_t array_size;
760
761         num_streams = 0;
762         list_for_each(cur, stream_list)
763                 num_streams++;
764         array_size = num_streams * sizeof(array[0]);
765         array = MALLOC(array_size);
766         if (!array) {
767                 ERROR("Failed to allocate %zu bytes to sort stream entries",
768                       array_size);
769                 return WIMLIB_ERR_NOMEM;
770         }
771         cur = stream_list->next;
772         for (i = 0; i < num_streams; i++) {
773                 array[i] = container_of(cur, struct wim_lookup_table_entry, extraction_list);
774                 cur = cur->next;
775         }
776
777         qsort(array, num_streams, sizeof(array[0]), cmp_streams_by_wim_position);
778
779         INIT_LIST_HEAD(stream_list);
780         for (i = 0; i < num_streams; i++)
781                 list_add_tail(&array[i]->extraction_list, stream_list);
782         FREE(array);
783         return 0;
784 }
785
786
787 /* Extracts the image @image from the WIM @w to the directory or NTFS volume
788  * @target. */
789 static int
790 extract_single_image(WIMStruct *w, int image,
791                      const tchar *target, int extract_flags,
792                      wimlib_progress_func_t progress_func)
793 {
794         int ret;
795         struct list_head stream_list;
796
797         struct apply_args args;
798         const struct apply_operations *ops;
799         tchar *target_realpath;
800
801         memset(&args, 0, sizeof(args));
802
803         args.w                  = w;
804         args.target             = target;
805         args.extract_flags      = extract_flags;
806         args.progress_func      = progress_func;
807
808         if (progress_func) {
809                 args.progress.extract.wimfile_name = w->filename;
810                 args.progress.extract.image = image;
811                 args.progress.extract.extract_flags = (extract_flags &
812                                                        WIMLIB_EXTRACT_MASK_PUBLIC);
813                 args.progress.extract.image_name = wimlib_get_image_name(w, image);
814                 args.progress.extract.target = target;
815         }
816
817 #ifdef WITH_NTFS_3G
818         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
819                 args.vol = ntfs_mount(target, 0);
820                 if (!args.vol) {
821                         ERROR_WITH_ERRNO("Failed to mount NTFS volume `%"TS"'",
822                                          target);
823                         return WIMLIB_ERR_NTFS_3G;
824                 }
825                 ops = &ntfs_apply_operations;
826         } else
827 #endif
828                 ops = &normal_apply_operations;
829
830         ret = select_wim_image(w, image);
831         if (ret)
832                 goto out;
833
834         /* Build a list of the streams that need to be extracted */
835         find_streams_for_extraction(wim_get_current_image_metadata(w),
836                                     &stream_list,
837                                     w->lookup_table, extract_flags);
838
839         /* Calculate the number of bytes of data that will be extracted */
840         calculate_bytes_to_extract(&stream_list, extract_flags,
841                                    &args.progress);
842
843         if (progress_func) {
844                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN,
845                               &args.progress);
846         }
847
848         /* If a sequential extraction was specified, sort the streams to be
849          * extracted by their position in the WIM file, so that the WIM file can
850          * be read sequentially. */
851         if (extract_flags & WIMLIB_EXTRACT_FLAG_SEQUENTIAL) {
852                 ret = sort_stream_list_by_wim_position(&stream_list);
853                 if (ret != 0) {
854                         WARNING("Falling back to non-sequential extraction");
855                         extract_flags &= ~WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
856                 }
857         }
858
859         if (progress_func) {
860                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN,
861                               &args.progress);
862         }
863
864         ret = calculate_dentry_tree_full_paths(wim_root_dentry(w));
865         if (ret)
866                 goto out;
867
868         /* Make the directory structure and extract empty files */
869         args.extract_flags |= WIMLIB_EXTRACT_FLAG_NO_STREAMS;
870         args.apply_dentry = ops->apply_dentry;
871         ret = for_dentry_in_tree(wim_root_dentry(w), maybe_apply_dentry, &args);
872         args.extract_flags &= ~WIMLIB_EXTRACT_FLAG_NO_STREAMS;
873         if (ret)
874                 goto out;
875
876         if (progress_func) {
877                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_END,
878                               &args.progress);
879         }
880
881         if (extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX) {
882                 args.target_realpath = realpath(target, NULL);
883                 if (!args.target_realpath)
884                         return WIMLIB_ERR_NOMEM;
885                 args.target_realpath_len = tstrlen(args.target_realpath);
886         }
887
888         /* Extract non-empty files */
889         ret = apply_stream_list(&stream_list, &args, ops, progress_func);
890         if (ret)
891                 goto out_free_target_realpath;
892
893         if (progress_func) {
894                 progress_func(WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS,
895                               &args.progress);
896         }
897
898         /* Apply timestamps */
899         ret = for_dentry_in_tree_depth(wim_root_dentry(w),
900                                        ops->apply_dentry_timestamps, &args);
901         if (ret)
902                 goto out_free_target_realpath;
903
904         if (progress_func) {
905                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END,
906                               &args.progress);
907         }
908 out_free_target_realpath:
909         FREE(args.target_realpath);
910 out:
911 #ifdef WITH_NTFS_3G
912         /* Unmount the NTFS volume */
913         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
914                 if (ntfs_umount(args.vol, FALSE) != 0) {
915                         ERROR_WITH_ERRNO("Failed to unmount NTFS volume `%"TS"'",
916                                          args.target);
917                         if (ret == 0)
918                                 ret = WIMLIB_ERR_NTFS_3G;
919                 }
920         }
921 #endif
922         return ret;
923 }
924
925 static const tchar * const filename_forbidden_chars =
926 T(
927 #ifdef __WIN32__
928 "<>:\"/\\|?*"
929 #else
930 "/"
931 #endif
932 );
933
934 /* This function checks if it is okay to use a WIM image's name as a directory
935  * name.  */
936 static bool
937 image_name_ok_as_dir(const tchar *image_name)
938 {
939         return image_name && *image_name &&
940                 !tstrpbrk(image_name, filename_forbidden_chars);
941 }
942
943 /* Extracts all images from the WIM to the directory @target, with the images
944  * placed in subdirectories named by their image names. */
945 static int
946 extract_all_images(WIMStruct *w,
947                    const tchar *target,
948                    int extract_flags,
949                    wimlib_progress_func_t progress_func)
950 {
951         size_t image_name_max_len = max(xml_get_max_image_name_len(w), 20);
952         size_t output_path_len = tstrlen(target);
953         tchar buf[output_path_len + 1 + image_name_max_len + 1];
954         int ret;
955         int image;
956         const tchar *image_name;
957
958         ret = extract_directory(NULL, target, true);
959         if (ret)
960                 return ret;
961
962         tmemcpy(buf, target, output_path_len);
963         buf[output_path_len] = T('/');
964         for (image = 1; image <= w->hdr.image_count; image++) {
965                 image_name = wimlib_get_image_name(w, image);
966                 if (image_name_ok_as_dir(image_name)) {
967                         tstrcpy(buf + output_path_len + 1, image_name);
968                 } else {
969                         /* Image name is empty, or contains forbidden
970                          * characters. */
971                         tsprintf(buf + output_path_len + 1, T("%d"), image);
972                 }
973                 ret = extract_single_image(w, image, buf, extract_flags,
974                                            progress_func);
975                 if (ret != 0)
976                         return ret;
977         }
978         return 0;
979 }
980
981 /* Extracts a single image or all images from a WIM file to a directory or NTFS
982  * volume. */
983 WIMLIBAPI int
984 wimlib_extract_image(WIMStruct *w,
985                      int image,
986                      const tchar *target,
987                      int extract_flags,
988                      WIMStruct **additional_swms,
989                      unsigned num_additional_swms,
990                      wimlib_progress_func_t progress_func)
991 {
992         struct wim_lookup_table *joined_tab, *w_tab_save;
993         int ret;
994
995         if (!target)
996                 return WIMLIB_ERR_INVALID_PARAM;
997
998         extract_flags &= WIMLIB_EXTRACT_MASK_PUBLIC;
999
1000         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
1001                         == (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
1002                 return WIMLIB_ERR_INVALID_PARAM;
1003
1004 #ifdef __WIN32__
1005         if (extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
1006                 ERROR("Extracting UNIX data is not supported on Windows");
1007                 return WIMLIB_ERR_INVALID_PARAM;
1008         }
1009         if (extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK)) {
1010                 ERROR("Linked extraction modes are not supported on Windows");
1011                 return WIMLIB_ERR_INVALID_PARAM;
1012         }
1013 #endif
1014
1015         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1016 #ifdef WITH_NTFS_3G
1017                 if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))) {
1018                         ERROR("Cannot specify symlink or hardlink flags when applying\n"
1019                               "        directly to a NTFS volume");
1020                         return WIMLIB_ERR_INVALID_PARAM;
1021                 }
1022                 if (image == WIMLIB_ALL_IMAGES) {
1023                         ERROR("Can only apply a single image when applying "
1024                               "directly to a NTFS volume");
1025                         return WIMLIB_ERR_INVALID_PARAM;
1026                 }
1027                 if (extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
1028                         ERROR("Cannot restore UNIX-specific data in the NTFS extraction mode");
1029                         return WIMLIB_ERR_INVALID_PARAM;
1030                 }
1031 #else
1032                 ERROR("wimlib was compiled without support for NTFS-3g, so");
1033                 ERROR("we cannot apply a WIM image directly to a NTFS volume");
1034                 return WIMLIB_ERR_UNSUPPORTED;
1035 #endif
1036         }
1037
1038         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_RPFIX |
1039                               WIMLIB_EXTRACT_FLAG_RPFIX)) ==
1040                 (WIMLIB_EXTRACT_FLAG_RPFIX | WIMLIB_EXTRACT_FLAG_NORPFIX))
1041         {
1042                 ERROR("Cannot specify RPFIX and NORPFIX flags at the same time!");
1043                 return WIMLIB_ERR_INVALID_PARAM;
1044         }
1045
1046         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_RPFIX |
1047                               WIMLIB_EXTRACT_FLAG_NORPFIX)) == 0)
1048                 if (w->hdr.flags & WIM_HDR_FLAG_RP_FIX)
1049                         extract_flags |= WIMLIB_EXTRACT_FLAG_RPFIX;
1050
1051         ret = verify_swm_set(w, additional_swms, num_additional_swms);
1052         if (ret)
1053                 return ret;
1054
1055         ret = wim_checksum_unhashed_streams(w);
1056         if (ret)
1057                 return ret;
1058
1059         if (num_additional_swms) {
1060                 ret = new_joined_lookup_table(w, additional_swms,
1061                                               num_additional_swms, &joined_tab);
1062                 if (ret)
1063                         return ret;
1064                 w_tab_save = w->lookup_table;
1065                 w->lookup_table = joined_tab;
1066         }
1067
1068         if (image == WIMLIB_ALL_IMAGES) {
1069                 extract_flags |= WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
1070                 ret = extract_all_images(w, target, extract_flags,
1071                                          progress_func);
1072         } else {
1073                 extract_flags &= ~WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
1074                 ret = extract_single_image(w, image, target, extract_flags,
1075                                            progress_func);
1076         }
1077
1078         if (extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
1079                              WIMLIB_EXTRACT_FLAG_HARDLINK))
1080         {
1081                 for_lookup_table_entry(w->lookup_table,
1082                                        lte_free_extracted_file,
1083                                        NULL);
1084         }
1085
1086         if (num_additional_swms) {
1087                 free_lookup_table(w->lookup_table);
1088                 w->lookup_table = w_tab_save;
1089         }
1090         return ret;
1091 }