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