]> wimlib.net Git - wimlib/blob - src/extract_image.c
6735602f495d489a545598bddd85a3efe6060265
[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 #if defined(__CYGWIN__) || defined(__WIN32__)
34 #include <windows.h>
35 #ifdef ERROR
36 #undef ERROR
37 #endif
38 #include <wchar.h>
39 #endif
40
41 #include <dirent.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <string.h>
45 #include <sys/stat.h>
46 #include <stdlib.h>
47 #include <sys/time.h>
48
49 #ifdef HAVE_UTIME_H
50 #include <utime.h>
51 #endif
52
53 #include <unistd.h>
54
55 #include "dentry.h"
56 #include "lookup_table.h"
57 #include "timestamp.h"
58 #include "wimlib_internal.h"
59 #include "xml.h"
60
61 #ifdef WITH_NTFS_3G
62 #include <ntfs-3g/volume.h>
63 #endif
64
65 #ifdef HAVE_ALLOCA_H
66 #include <alloca.h>
67 #else
68 #include <stdlib.h>
69 #endif
70
71 #if defined(__CYGWIN__) || defined(__WIN32__)
72
73 static int win32_set_reparse_data(HANDLE h,
74                                   u32 reparse_tag,
75                                   const struct wim_lookup_table_entry *lte,
76                                   const wchar_t *path)
77 {
78         int ret;
79         u8 *buf;
80         size_t len;
81
82         if (!lte) {
83                 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
84                         path);
85                 return 0;
86         }
87         len = wim_resource_size(lte);
88         if (len > 16 * 1024 - 8) {
89                 WARNING("\"%ls\": reparse data too long!", path);
90                 return 0;
91         }
92
93         /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
94          * leave 8 bytes of space for them at the beginning of the buffer, then
95          * set them manually. */
96         buf = alloca(len + 8);
97         ret = read_full_wim_resource(lte, buf + 8, 0);
98         if (ret)
99                 return ret;
100         *(u32*)(buf + 0) = reparse_tag;
101         *(u16*)(buf + 4) = len;
102         *(u16*)(buf + 6) = 0;
103
104         /* Set the reparse data on the open file using the
105          * FSCTL_SET_REPARSE_POINT ioctl.
106          *
107          * There are contradictions in Microsoft's documentation for this:
108          *
109          * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
110          * lpOverlapped is ignored."
111          *
112          * --- So setting lpOverlapped to NULL is okay since it's ignored.
113          *
114          * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
115          * operation returns no output data and lpOutBuffer is NULL,
116          * DeviceIoControl makes use of lpBytesReturned. After such an
117          * operation, the value of lpBytesReturned is meaningless."
118          *
119          * --- So lpOverlapped not really ignored, as it affects another
120          *  parameter.  This is the actual behavior: lpBytesReturned must be
121          *  specified, even though lpBytesReturned is documented as:
122          *
123          *  "Not used with this operation; set to NULL."
124          */
125         DWORD bytesReturned;
126         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
127                              NULL, 0,
128                              &bytesReturned /* lpBytesReturned */,
129                              NULL /* lpOverlapped */))
130         {
131                 DWORD err = GetLastError();
132                 ERROR("Failed to set reparse data on \"%ls\"", path);
133                 win32_error(err);
134                 return WIMLIB_ERR_WRITE;
135         }
136         return 0;
137 }
138
139
140 static int win32_extract_chunk(const u8 *buf, size_t len, u64 offset, void *arg)
141 {
142         HANDLE hStream = arg;
143
144         DWORD nbytes_written;
145         wimlib_assert(len <= 0xffffffff);
146
147         if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
148             nbytes_written != len)
149         {
150                 DWORD err = GetLastError();
151                 ERROR("WriteFile(): write error");
152                 win32_error(err);
153                 return WIMLIB_ERR_WRITE;
154         }
155         return 0;
156 }
157
158 static int do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
159 {
160         return extract_wim_resource(lte, wim_resource_size(lte),
161                                     win32_extract_chunk, hStream);
162 }
163
164 static int win32_extract_stream(const struct wim_inode *inode,
165                                 const wchar_t *path,
166                                 const wchar_t *stream_name_utf16,
167                                 struct wim_lookup_table_entry *lte)
168 {
169         wchar_t *stream_path;
170         HANDLE h;
171         int ret;
172         DWORD err;
173         DWORD creationDisposition = CREATE_ALWAYS;
174
175         if (stream_name_utf16) {
176                 /* Named stream.  Create a buffer that contains the UTF-16LE
177                  * string [./]@path:@stream_name_utf16.  This is needed to
178                  * create and open the stream using CreateFileW().  I'm not
179                  * aware of any other APIs to do this.  Note: note that the
180                  * '$DATA' suffix seems to be unneeded; Additional note: a "./"
181                  * prefix needs to be added when the path is not absolute to
182                  * avoid ambiguity with drive letters. */
183                 size_t stream_path_nchars;
184                 size_t path_nchars;
185                 size_t stream_name_nchars;
186                 const wchar_t *prefix;
187
188                 path_nchars = wcslen(path);
189                 stream_name_nchars = wcslen(stream_name_utf16);
190                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
191                 if (path[0] != L'/' && path[1] != L'\\') {
192                         prefix = L"./";
193                         stream_path_nchars += 2;
194                 } else {
195                         prefix = L"";
196                 }
197                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
198                 swprintf(stream_path, stream_path_nchars + 1, L"%ls%ls:%ls",
199                          prefix, path, stream_name_utf16);
200         } else {
201                 /* Unnamed stream; it's path is just the path to the file
202                  * itself. */
203                 stream_path = (wchar_t*)path;
204
205                 /* Directories must be created with CreateDirectoryW().  Then
206                  * the call to CreateFileW() will merely open the directory that
207                  * was already created rather than creating a new file. */
208                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
209                         if (!CreateDirectoryW(stream_path, NULL)) {
210                                 err = GetLastError();
211                                 if (err != ERROR_ALREADY_EXISTS) {
212                                         ERROR("Failed to create directory \"%ls\"",
213                                               path);
214                                         win32_error(err);
215                                         ret = WIMLIB_ERR_MKDIR;
216                                         goto fail;
217                                 }
218                         }
219                         DEBUG("Created directory \"%ls\"", stream_path);
220                         if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
221                                 ret = 0;
222                                 goto out;
223                         }
224                         creationDisposition = OPEN_EXISTING;
225                 }
226         }
227
228         DEBUG("Opening \"%ls\"", stream_path);
229         h = CreateFileW(stream_path,
230                         GENERIC_WRITE | WRITE_OWNER | WRITE_DAC,
231                         0,
232                         NULL,
233                         creationDisposition,
234                         FILE_FLAG_OPEN_REPARSE_POINT |
235                             FILE_FLAG_BACKUP_SEMANTICS |
236                             inode->i_attributes,
237                         NULL);
238         if (h == INVALID_HANDLE_VALUE) {
239                 err = GetLastError();
240                 ERROR("Failed to create \"%ls\"", stream_path);
241                 win32_error(err);
242                 ret = WIMLIB_ERR_OPEN;
243                 goto fail;
244         }
245
246         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
247             stream_name_utf16 == NULL)
248         {
249                 DEBUG("Setting reparse data on \"%ls\"", path);
250                 ret = win32_set_reparse_data(h, inode->i_reparse_tag, lte, path);
251                 if (ret)
252                         goto fail_close_handle;
253         } else {
254                 if (lte) {
255                         DEBUG("Extracting \"%ls\" (len = %zu)",
256                               stream_path, wim_resource_size(lte));
257                         ret = do_win32_extract_stream(h, lte);
258                         if (ret)
259                                 goto fail_close_handle;
260                 }
261         }
262
263         DEBUG("Closing \"%ls\"", stream_path);
264         if (!CloseHandle(h)) {
265                 err = GetLastError();
266                 ERROR("Failed to close \"%ls\"", stream_path);
267                 win32_error(err);
268                 ret = WIMLIB_ERR_WRITE;
269                 goto fail;
270         }
271         ret = 0;
272         goto out;
273 fail_close_handle:
274         CloseHandle(h);
275 fail:
276         ERROR("Error extracting %ls", stream_path);
277 out:
278         return ret;
279 }
280
281 /*
282  * Creates a file, directory, or reparse point and extracts all streams to it
283  * (unnamed data stream and/or reparse point stream, plus any alternate data
284  * streams).  This in Win32-specific code.
285  *
286  * @inode:      WIM inode for this file or directory.
287  * @path:       UTF-16LE external path to extract the inode to.
288  *
289  * Returns 0 on success; nonzero on failure.
290  */
291 static int win32_extract_streams(struct wim_inode *inode,
292                                  const wchar_t *path)
293 {
294         struct wim_lookup_table_entry *unnamed_lte;
295         int ret;
296
297         unnamed_lte = inode_unnamed_lte_resolved(inode);
298         ret = win32_extract_stream(inode, path, NULL, unnamed_lte);
299         if (ret)
300                 goto out;
301         for (u16 i = 0; i < inode->i_num_ads; i++) {
302                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
303                 if (ads_entry->stream_name_len != 0) {
304                         /* Skip special UNIX data entries (see documentation for
305                          * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
306                         if (ads_entry->stream_name_len == WIMLIB_UNIX_DATA_TAG_LEN
307                             && !memcmp(ads_entry->stream_name_utf8,
308                                        WIMLIB_UNIX_DATA_TAG,
309                                        WIMLIB_UNIX_DATA_TAG_LEN))
310                                 continue;
311                         ret = win32_extract_stream(inode,
312                                                    path,
313                                                    (const wchar_t*)ads_entry->stream_name,
314                                                    ads_entry->lte);
315                         if (ret)
316                                 break;
317                 }
318         }
319 out:
320         return ret;
321 }
322
323 /*
324  * Sets the security descriptor on an extracted file.  This is Win32-specific
325  * code.
326  *
327  * @inode:      The WIM inode that was extracted and has a security descriptor.
328  * @path:       UTF-16LE external path that the inode was extracted to.
329  * @sd:         Security data for the WIM image.
330  * @path_utf8:  @path in UTF-8 for error messages only.
331  *
332  * Returns 0 on success; nonzero on failure.
333  */
334 static int win32_set_security_data(const struct wim_inode *inode,
335                                    const wchar_t *path,
336                                    const struct wim_security_data *sd)
337 {
338         SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
339                                                    SACL_SECURITY_INFORMATION |
340                                                    OWNER_SECURITY_INFORMATION |
341                                                    GROUP_SECURITY_INFORMATION;
342         if (!SetFileSecurityW(path, securityInformation,
343                               (PSECURITY_DESCRIPTOR)sd->descriptors[inode->i_security_id]))
344         {
345                 DWORD err = GetLastError();
346                 ERROR("Can't set security descriptor on \"%ls\"", path);
347                 win32_error(err);
348                 return WIMLIB_ERR_WRITE;
349         }
350         return 0;
351 }
352
353 #else
354 static int extract_regular_file_linked(struct wim_dentry *dentry,
355                                        const char *output_path,
356                                        struct apply_args *args,
357                                        struct wim_lookup_table_entry *lte)
358 {
359         /* This mode overrides the normal hard-link extraction and
360          * instead either symlinks or hardlinks *all* identical files in
361          * the WIM, even if they are in a different image (in the case
362          * of a multi-image extraction) */
363
364         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_HARDLINK) {
365                 if (link(lte->extracted_file, output_path) != 0) {
366                         ERROR_WITH_ERRNO("Failed to hard link "
367                                          "`%s' to `%s'",
368                                          output_path, lte->extracted_file);
369                         return WIMLIB_ERR_LINK;
370                 }
371         } else {
372                 int num_path_components;
373                 int num_output_dir_path_components;
374                 size_t extracted_file_len;
375                 char *p;
376                 const char *p2;
377                 size_t i;
378
379                 num_path_components =
380                         get_num_path_components(dentry->full_path_utf8) - 1;
381                 num_output_dir_path_components =
382                         get_num_path_components(args->target);
383
384                 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_MULTI_IMAGE) {
385                         num_path_components++;
386                         num_output_dir_path_components--;
387                 }
388                 extracted_file_len = strlen(lte->extracted_file);
389
390                 char buf[extracted_file_len + 3 * num_path_components + 1];
391                 p = &buf[0];
392
393                 for (i = 0; i < num_path_components; i++) {
394                         *p++ = '.';
395                         *p++ = '.';
396                         *p++ = '/';
397                 }
398                 p2 = lte->extracted_file;
399                 while (*p2 == '/')
400                         p2++;
401                 while (num_output_dir_path_components--)
402                         p2 = path_next_part(p2, NULL);
403                 strcpy(p, p2);
404                 if (symlink(buf, output_path) != 0) {
405                         ERROR_WITH_ERRNO("Failed to symlink `%s' to "
406                                          "`%s'",
407                                          buf, lte->extracted_file);
408                         return WIMLIB_ERR_LINK;
409                 }
410         }
411         return 0;
412 }
413
414 static int symlink_apply_unix_data(const char *link,
415                                    const struct wimlib_unix_data *unix_data)
416 {
417         if (lchown(link, unix_data->uid, unix_data->gid)) {
418                 if (errno == EPERM) {
419                         /* Ignore */
420                         WARNING_WITH_ERRNO("failed to set symlink UNIX owner/group");
421                 } else {
422                         ERROR_WITH_ERRNO("failed to set symlink UNIX owner/group");
423                         return WIMLIB_ERR_INVALID_DENTRY;
424                 }
425         }
426         return 0;
427 }
428
429 static int fd_apply_unix_data(int fd, const struct wimlib_unix_data *unix_data)
430 {
431         if (fchown(fd, unix_data->uid, unix_data->gid)) {
432                 if (errno == EPERM) {
433                         WARNING_WITH_ERRNO("failed to set file UNIX owner/group");
434                         /* Ignore? */
435                 } else {
436                         ERROR_WITH_ERRNO("failed to set file UNIX owner/group");
437                         return WIMLIB_ERR_INVALID_DENTRY;
438                 }
439         }
440
441         if (fchmod(fd, unix_data->mode)) {
442                 if (errno == EPERM) {
443                         WARNING_WITH_ERRNO("failed to set UNIX file mode");
444                         /* Ignore? */
445                 } else {
446                         ERROR_WITH_ERRNO("failed to set UNIX file mode");
447                         return WIMLIB_ERR_INVALID_DENTRY;
448                 }
449         }
450         return 0;
451 }
452
453 static int dir_apply_unix_data(const char *dir,
454                                const struct wimlib_unix_data *unix_data)
455 {
456         int dfd = open(dir, O_RDONLY);
457         int ret;
458         if (dfd >= 0) {
459                 ret = fd_apply_unix_data(dfd, unix_data);
460                 if (close(dfd)) {
461                         ERROR_WITH_ERRNO("can't close directory `%s'", dir);
462                         ret = WIMLIB_ERR_MKDIR;
463                 }
464         } else {
465                 ERROR_WITH_ERRNO("can't open directory `%s'", dir);
466                 ret = WIMLIB_ERR_MKDIR;
467         }
468         return ret;
469 }
470
471 static int extract_regular_file_unlinked(struct wim_dentry *dentry,
472                                          struct apply_args *args,
473                                          const char *output_path,
474                                          struct wim_lookup_table_entry *lte)
475 {
476         /* Normal mode of extraction.  Regular files and hard links are
477          * extracted in the way that they appear in the WIM. */
478
479         int out_fd;
480         int ret;
481         struct wim_inode *inode = dentry->d_inode;
482
483         if (!((args->extract_flags & WIMLIB_EXTRACT_FLAG_MULTI_IMAGE)
484                 && (args->extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
485                                      WIMLIB_EXTRACT_FLAG_HARDLINK))))
486         {
487                 /* If the dentry is part of a hard link set of at least 2
488                  * dentries and one of the other dentries has already been
489                  * extracted, make a hard link to the file corresponding to this
490                  * already-extracted directory.  Otherwise, extract the file and
491                  * set the inode->i_extracted_file field so that other dentries
492                  * in the hard link group can link to it. */
493                 if (inode->i_nlink > 1) {
494                         if (inode->i_extracted_file) {
495                                 DEBUG("Extracting hard link `%s' => `%s'",
496                                       output_path, inode->i_extracted_file);
497                                 if (link(inode->i_extracted_file, output_path) != 0) {
498                                         ERROR_WITH_ERRNO("Failed to hard link "
499                                                          "`%s' to `%s'",
500                                                          output_path,
501                                                          inode->i_extracted_file);
502                                         return WIMLIB_ERR_LINK;
503                                 }
504                                 return 0;
505                         }
506                         FREE(inode->i_extracted_file);
507                         inode->i_extracted_file = STRDUP(output_path);
508                         if (!inode->i_extracted_file) {
509                                 ERROR("Failed to allocate memory for filename");
510                                 return WIMLIB_ERR_NOMEM;
511                         }
512                 }
513         }
514
515         /* Extract the contents of the file to @output_path. */
516
517         out_fd = open(output_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
518         if (out_fd == -1) {
519                 ERROR_WITH_ERRNO("Failed to open the file `%s' for writing",
520                                  output_path);
521                 return WIMLIB_ERR_OPEN;
522         }
523
524         if (!lte) {
525                 /* Empty file with no lookup table entry */
526                 DEBUG("Empty file `%s'.", output_path);
527                 ret = 0;
528                 goto out_extract_unix_data;
529         }
530
531         ret = extract_wim_resource_to_fd(lte, out_fd, wim_resource_size(lte));
532         if (ret != 0) {
533                 ERROR("Failed to extract resource to `%s'", output_path);
534                 goto out;
535         }
536
537 out_extract_unix_data:
538         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
539                 struct wimlib_unix_data unix_data;
540                 ret = inode_get_unix_data(inode, &unix_data, NULL);
541                 if (ret > 0)
542                         ;
543                 else if (ret < 0)
544                         ret = 0;
545                 else
546                         ret = fd_apply_unix_data(out_fd, &unix_data);
547                 if (ret != 0)
548                         goto out;
549         }
550         if (lte)
551                 args->progress.extract.completed_bytes += wim_resource_size(lte);
552 out:
553         if (close(out_fd) != 0) {
554                 ERROR_WITH_ERRNO("Failed to close file `%s'", output_path);
555                 if (ret == 0)
556                         ret = WIMLIB_ERR_WRITE;
557         }
558         return ret;
559 }
560
561 static int extract_regular_file(struct wim_dentry *dentry,
562                                 struct apply_args *args,
563                                 const char *output_path)
564 {
565         struct wim_lookup_table_entry *lte;
566         const struct wim_inode *inode = dentry->d_inode;
567
568         lte = inode_unnamed_lte_resolved(inode);
569
570         if (lte && (args->extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
571                                            WIMLIB_EXTRACT_FLAG_HARDLINK)))
572         {
573                 if (lte->extracted_file) {
574                         return extract_regular_file_linked(dentry, output_path, args, lte);
575                 } else {
576                         lte->extracted_file = STRDUP(output_path);
577                         if (!lte->extracted_file)
578                                 return WIMLIB_ERR_NOMEM;
579                 }
580         }
581         return extract_regular_file_unlinked(dentry, args, output_path, lte);
582 }
583
584 static int extract_symlink(struct wim_dentry *dentry,
585                            struct apply_args *args,
586                            const char *output_path)
587 {
588         char target[4096];
589         ssize_t ret = inode_readlink(dentry->d_inode, target,
590                                      sizeof(target), args->w, 0);
591         struct wim_lookup_table_entry *lte;
592
593         if (ret <= 0) {
594                 ERROR("Could not read the symbolic link from dentry `%s'",
595                       dentry->full_path_utf8);
596                 return WIMLIB_ERR_INVALID_DENTRY;
597         }
598         ret = symlink(target, output_path);
599         if (ret != 0) {
600                 ERROR_WITH_ERRNO("Failed to symlink `%s' to `%s'",
601                                  output_path, target);
602                 return WIMLIB_ERR_LINK;
603         }
604         lte = inode_unnamed_lte_resolved(dentry->d_inode);
605         wimlib_assert(lte != NULL);
606         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
607                 struct wimlib_unix_data unix_data;
608                 ret = inode_get_unix_data(dentry->d_inode, &unix_data, NULL);
609                 if (ret > 0)
610                         ;
611                 else if (ret < 0)
612                         ret = 0;
613                 else
614                         ret = symlink_apply_unix_data(output_path, &unix_data);
615                 if (ret != 0)
616                         return ret;
617         }
618         args->progress.extract.completed_bytes += wim_resource_size(lte);
619         return 0;
620 }
621
622 #endif /* !__CYGWIN__ && !__WIN32__ */
623
624 static int extract_directory(struct wim_dentry *dentry,
625                              const char *output_path, bool is_root)
626 {
627         int ret;
628         struct stat stbuf;
629
630         ret = stat(output_path, &stbuf);
631         if (ret == 0) {
632                 if (S_ISDIR(stbuf.st_mode)) {
633                         /*if (!is_root)*/
634                                 /*WARNING("`%s' already exists", output_path);*/
635                         goto dir_exists;
636                 } else {
637                         ERROR("`%s' is not a directory", output_path);
638                         return WIMLIB_ERR_MKDIR;
639                 }
640         } else {
641                 if (errno != ENOENT) {
642                         ERROR_WITH_ERRNO("Failed to stat `%s'", output_path);
643                         return WIMLIB_ERR_STAT;
644                 }
645         }
646         if (mkdir(output_path, S_IRWXU | S_IRGRP | S_IXGRP |
647                                S_IROTH | S_IXOTH) != 0) {
648                 ERROR_WITH_ERRNO("Cannot create directory `%s'",
649                                  output_path);
650                 return WIMLIB_ERR_MKDIR;
651         }
652 dir_exists:
653         ret = 0;
654 #if !defined(__CYGWIN__) && !defined(__WIN32__)
655         if (dentry) {
656                 struct wimlib_unix_data unix_data;
657                 ret = inode_get_unix_data(dentry->d_inode, &unix_data, NULL);
658                 if (ret > 0)
659                         ;
660                 else if (ret < 0)
661                         ret = 0;
662                 else
663                         ret = dir_apply_unix_data(output_path, &unix_data);
664         }
665 #endif
666         return ret;
667 }
668
669 /* Extracts a file, directory, or symbolic link from the WIM archive. */
670 static int apply_dentry_normal(struct wim_dentry *dentry, void *arg)
671 {
672         struct apply_args *args = arg;
673         struct wim_inode *inode = dentry->d_inode;
674         size_t len;
675         char *output_path;
676
677         len = strlen(args->target);
678         if (dentry_is_root(dentry)) {
679                 output_path = (char*)args->target;
680         } else {
681                 output_path = alloca(len + dentry->full_path_utf8_len + 1);
682                 memcpy(output_path, args->target, len);
683                 memcpy(output_path + len, dentry->full_path_utf8, dentry->full_path_utf8_len);
684                 output_path[len + dentry->full_path_utf8_len] = '\0';
685                 len += dentry->full_path_utf8_len;
686         }
687
688 #if defined(__CYGWIN__) || defined(__WIN32__)
689         char *utf16_path;
690         size_t utf16_path_len;
691         DWORD err;
692         int ret;
693         ret = utf8_to_utf16(output_path, len, &utf16_path, &utf16_path_len);
694         if (ret)
695                 return ret;
696
697         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
698                 /* Linked file, with another name already extracted.  Create a
699                  * hard link. */
700                 DEBUG("Creating hard link \"%ls => %ls\"",
701                       (const wchar_t*)utf16_path,
702                       (const wchar_t*)inode->i_extracted_file);
703                 if (!CreateHardLinkW((const wchar_t*)utf16_path,
704                                      (const wchar_t*)inode->i_extracted_file,
705                                      NULL))
706                 {
707                         err = GetLastError();
708                         ERROR("Can't create hard link \"%ls => %ls\"",
709                               (const wchar_t*)utf16_path,
710                               (const wchar_t*)inode->i_extracted_file);
711                         ret = WIMLIB_ERR_LINK;
712                         win32_error(err);
713                 }
714         } else {
715                 /* Create the file, directory, or reparse point, and extract the
716                  * data streams. */
717                 ret = win32_extract_streams(inode, (const wchar_t*)utf16_path);
718                 if (ret)
719                         goto out_free_utf16_path;
720
721                 /* Set security descriptor if present */
722                 if (inode->i_security_id != -1) {
723                         DEBUG("Setting security descriptor %d on %s",
724                               inode->i_security_id, output_path);
725                         ret = win32_set_security_data(inode,
726                                                       (const wchar_t*)utf16_path,
727                                                       wim_const_security_data(args->w));
728                         if (ret)
729                                 goto out_free_utf16_path;
730                 }
731                 if (inode->i_nlink > 1) {
732                         /* Save extracted path for a later call to
733                          * CreateHardLinkW() if this inode has multiple links.
734                          * */
735                         inode->i_extracted_file = utf16_path;
736                         goto out;
737                 }
738         }
739 out_free_utf16_path:
740         FREE(utf16_path);
741 out:
742         return ret;
743 #else
744         if (inode_is_symlink(inode))
745                 return extract_symlink(dentry, args, output_path);
746         else if (inode_is_directory(inode))
747                 return extract_directory((args->extract_flags &
748                                            WIMLIB_EXTRACT_FLAG_UNIX_DATA) ? dentry : NULL,
749                                          output_path, false);
750         else
751                 return extract_regular_file(dentry, args, output_path);
752 #endif
753 }
754
755 /* Apply timestamps to an extracted file or directory */
756 static int apply_dentry_timestamps_normal(struct wim_dentry *dentry, void *arg)
757 {
758         struct apply_args *args = arg;
759         size_t len;
760         char *output_path;
761         int ret;
762         const struct wim_inode *inode = dentry->d_inode;
763
764         len = strlen(args->target);
765         if (dentry_is_root(dentry)) {
766                 output_path = (char*)args->target;
767         } else {
768                 output_path = alloca(len + dentry->full_path_utf8_len + 1);
769                 memcpy(output_path, args->target, len);
770                 memcpy(output_path + len, dentry->full_path_utf8, dentry->full_path_utf8_len);
771                 output_path[len + dentry->full_path_utf8_len] = '\0';
772                 len += dentry->full_path_utf8_len;
773         }
774
775 #if defined(__CYGWIN__) || defined(__WIN32__)
776         /* Win32 */
777         char *utf16_path;
778         size_t utf16_path_len;
779         DWORD err;
780         HANDLE h;
781         BOOL bret1, bret2;
782
783         ret = utf8_to_utf16(output_path, len, &utf16_path, &utf16_path_len);
784         if (ret)
785                 return ret;
786
787         DEBUG("Opening \"%ls\" to set timestamps", utf16_path);
788         h = CreateFileW(utf16_path, GENERIC_WRITE, FILE_SHARE_READ,
789                         NULL, OPEN_EXISTING,
790                         FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
791                         NULL);
792
793         if (h == INVALID_HANDLE_VALUE)
794                 err = GetLastError();
795         FREE(utf16_path);
796         if (h == INVALID_HANDLE_VALUE)
797                 goto fail;
798
799         FILETIME creationTime = {.dwLowDateTime = dentry->d_inode->i_creation_time & 0xffffffff,
800                                  .dwHighDateTime = dentry->d_inode->i_creation_time >> 32};
801         FILETIME lastAccessTime = {.dwLowDateTime = dentry->d_inode->i_last_access_time & 0xffffffff,
802                                   .dwHighDateTime = dentry->d_inode->i_last_access_time >> 32};
803         FILETIME lastWriteTime = {.dwLowDateTime = dentry->d_inode->i_last_write_time & 0xffffffff,
804                                   .dwHighDateTime = dentry->d_inode->i_last_write_time >> 32};
805
806         DEBUG("Calling SetFileTime() on \"%s\"", output_path);
807         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
808                 err = GetLastError();
809                 CloseHandle(h);
810                 goto fail;
811         }
812         DEBUG("Closing \"%s\"", output_path);
813         if (!CloseHandle(h)) {
814                 err = GetLastError();
815                 goto fail;
816         }
817         return 0;
818 fail:
819         ERROR("Can't set timestamps on \"%s\"", output_path);
820         win32_error(err);
821         return WIMLIB_ERR_WRITE;
822 #else
823         /* UNIX */
824
825         /* Convert the WIM timestamps, which are accurate to 100 nanoseconds,
826          * into struct timeval's. */
827         struct timeval tv[2];
828         wim_timestamp_to_timeval(inode->i_last_access_time, &tv[0]);
829         wim_timestamp_to_timeval(inode->i_last_write_time, &tv[1]);
830         #ifdef HAVE_LUTIMES
831         ret = lutimes(output_path, tv);
832         #else
833         ret = -1;
834         errno = ENOSYS;
835         #endif
836         if (ret != 0) {
837                 #ifdef HAVE_UTIME
838                 if (errno == ENOSYS) {
839                         struct utimbuf buf;
840                         buf.actime = wim_timestamp_to_unix(inode->i_last_access_time);
841                         buf.modtime = wim_timestamp_to_unix(inode->i_last_write_time);
842                         if (utime(output_path, &buf) == 0)
843                                 return 0;
844                 }
845                 #endif
846                 if (errno != ENOSYS || args->num_lutimes_warnings < 10) {
847                         /*WARNING_WITH_ERRNO("Failed to set timestamp on file `%s',*/
848                                             /*output_path");*/
849                         args->num_lutimes_warnings++;
850                 }
851         }
852         return 0;
853 #endif
854 }
855
856 /* Extract a dentry if it hasn't already been extracted, and either the dentry
857  * has no streams or WIMLIB_EXTRACT_FLAG_NO_STREAMS is not specified. */
858 static int maybe_apply_dentry(struct wim_dentry *dentry, void *arg)
859 {
860         struct apply_args *args = arg;
861         int ret;
862
863         if (dentry->is_extracted)
864                 return 0;
865
866         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_STREAMS)
867                 if (inode_unnamed_lte_resolved(dentry->d_inode))
868                         return 0;
869
870         if ((args->extract_flags & WIMLIB_EXTRACT_FLAG_VERBOSE) &&
871              args->progress_func) {
872                 args->progress.extract.cur_path = dentry->full_path_utf8;
873                 args->progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY,
874                                     &args->progress);
875         }
876         ret = args->apply_dentry(dentry, args);
877         if (ret == 0)
878                 dentry->is_extracted = 1;
879         return ret;
880 }
881
882 static int cmp_streams_by_wim_position(const void *p1, const void *p2)
883 {
884         const struct wim_lookup_table_entry *lte1, *lte2;
885         lte1 = *(const struct wim_lookup_table_entry**)p1;
886         lte2 = *(const struct wim_lookup_table_entry**)p2;
887         if (lte1->resource_entry.offset < lte2->resource_entry.offset)
888                 return -1;
889         else if (lte1->resource_entry.offset > lte2->resource_entry.offset)
890                 return 1;
891         else
892                 return 0;
893 }
894
895 static int sort_stream_list_by_wim_position(struct list_head *stream_list)
896 {
897         struct list_head *cur;
898         size_t num_streams;
899         struct wim_lookup_table_entry **array;
900         size_t i;
901         size_t array_size;
902
903         num_streams = 0;
904         list_for_each(cur, stream_list)
905                 num_streams++;
906         array_size = num_streams * sizeof(array[0]);
907         array = MALLOC(array_size);
908         if (!array) {
909                 ERROR("Failed to allocate %zu bytes to sort stream entries",
910                       array_size);
911                 return WIMLIB_ERR_NOMEM;
912         }
913         cur = stream_list->next;
914         for (i = 0; i < num_streams; i++) {
915                 array[i] = container_of(cur, struct wim_lookup_table_entry, staging_list);
916                 cur = cur->next;
917         }
918
919         qsort(array, num_streams, sizeof(array[0]), cmp_streams_by_wim_position);
920
921         INIT_LIST_HEAD(stream_list);
922         for (i = 0; i < num_streams; i++)
923                 list_add_tail(&array[i]->staging_list, stream_list);
924         FREE(array);
925         return 0;
926 }
927
928 static void calculate_bytes_to_extract(struct list_head *stream_list,
929                                        int extract_flags,
930                                        union wimlib_progress_info *progress)
931 {
932         struct wim_lookup_table_entry *lte;
933         u64 total_bytes = 0;
934         u64 num_streams = 0;
935
936         /* For each stream to be extracted... */
937         list_for_each_entry(lte, stream_list, staging_list) {
938                 if (extract_flags &
939                     (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
940                 {
941                         /* In the symlink or hard link extraction mode, each
942                          * stream will be extracted one time regardless of how
943                          * many dentries share the stream. */
944                         wimlib_assert(!(extract_flags & WIMLIB_EXTRACT_FLAG_NTFS));
945                         if (!lte->extracted_file) {
946                                 num_streams++;
947                                 total_bytes += wim_resource_size(lte);
948                         }
949                 } else {
950                         num_streams += lte->out_refcnt;
951                         total_bytes += lte->out_refcnt * wim_resource_size(lte);
952                 }
953         }
954         progress->extract.num_streams = num_streams;
955         progress->extract.total_bytes = total_bytes;
956         progress->extract.completed_bytes = 0;
957 }
958
959 static void maybe_add_stream_for_extraction(struct wim_lookup_table_entry *lte,
960                                             struct list_head *stream_list)
961 {
962         if (++lte->out_refcnt == 1) {
963                 INIT_LIST_HEAD(&lte->inode_list);
964                 list_add_tail(&lte->staging_list, stream_list);
965         }
966 }
967
968 static void inode_find_streams_for_extraction(struct wim_inode *inode,
969                                               struct list_head *stream_list,
970                                               int extract_flags)
971 {
972         struct wim_lookup_table_entry *lte;
973         bool inode_added = false;
974
975         lte = inode_unnamed_lte_resolved(inode);
976         if (lte) {
977                 maybe_add_stream_for_extraction(lte, stream_list);
978                 list_add_tail(&inode->i_lte_inode_list, &lte->inode_list);
979                 inode_added = true;
980         }
981 #ifdef WITH_NTFS_3G
982         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
983                 for (unsigned i = 0; i < inode->i_num_ads; i++) {
984                         if (inode->i_ads_entries[i].stream_name_len != 0) {
985                                 lte = inode->i_ads_entries[i].lte;
986                                 if (lte) {
987                                         maybe_add_stream_for_extraction(lte,
988                                                                         stream_list);
989                                         if (!inode_added) {
990                                                 list_add_tail(&inode->i_lte_inode_list,
991                                                               &lte->inode_list);
992                                                 inode_added = true;
993                                         }
994                                 }
995                         }
996                 }
997         }
998 #endif
999 }
1000
1001 static void find_streams_for_extraction(struct hlist_head *inode_list,
1002                                         struct list_head *stream_list,
1003                                         struct wim_lookup_table *lookup_table,
1004                                         int extract_flags)
1005 {
1006         struct wim_inode *inode;
1007         struct hlist_node *cur;
1008         struct wim_dentry *dentry;
1009
1010         for_lookup_table_entry(lookup_table, lte_zero_out_refcnt, NULL);
1011         INIT_LIST_HEAD(stream_list);
1012         hlist_for_each_entry(inode, cur, inode_list, i_hlist) {
1013                 if (!inode->i_resolved)
1014                         inode_resolve_ltes(inode, lookup_table);
1015                 inode_for_each_dentry(dentry, inode)
1016                         dentry->is_extracted = 0;
1017                 inode_find_streams_for_extraction(inode, stream_list,
1018                                                   extract_flags);
1019         }
1020 }
1021
1022 struct apply_operations {
1023         int (*apply_dentry)(struct wim_dentry *dentry, void *arg);
1024         int (*apply_dentry_timestamps)(struct wim_dentry *dentry, void *arg);
1025 };
1026
1027 static const struct apply_operations normal_apply_operations = {
1028         .apply_dentry = apply_dentry_normal,
1029         .apply_dentry_timestamps = apply_dentry_timestamps_normal,
1030 };
1031
1032 #ifdef WITH_NTFS_3G
1033 static const struct apply_operations ntfs_apply_operations = {
1034         .apply_dentry = apply_dentry_ntfs,
1035         .apply_dentry_timestamps = apply_dentry_timestamps_ntfs,
1036 };
1037 #endif
1038
1039 static int apply_stream_list(struct list_head *stream_list,
1040                              struct apply_args *args,
1041                              const struct apply_operations *ops,
1042                              wimlib_progress_func_t progress_func)
1043 {
1044         uint64_t bytes_per_progress = args->progress.extract.total_bytes / 100;
1045         uint64_t next_progress = bytes_per_progress;
1046         struct wim_lookup_table_entry *lte;
1047         struct wim_inode *inode;
1048         struct wim_dentry *dentry;
1049         int ret;
1050
1051         /* This complicated loop is essentially looping through the dentries,
1052          * although dentries may be visited more than once (if a dentry contains
1053          * two different nonempty streams) or not at all (if a dentry contains
1054          * no non-empty streams).
1055          *
1056          * The outer loop is over the distinct streams to be extracted so that
1057          * sequential reading of the WIM can be implemented. */
1058
1059         /* For each distinct stream to be extracted */
1060         list_for_each_entry(lte, stream_list, staging_list) {
1061                 /* For each inode that contains the stream */
1062                 list_for_each_entry(inode, &lte->inode_list, i_lte_inode_list) {
1063                         /* For each dentry that points to the inode */
1064                         inode_for_each_dentry(dentry, inode) {
1065                                 /* Extract the dentry if it was not already
1066                                  * extracted */
1067                                 ret = maybe_apply_dentry(dentry, args);
1068                                 if (ret != 0)
1069                                         return ret;
1070                                 if (progress_func &&
1071                                     args->progress.extract.completed_bytes >= next_progress)
1072                                 {
1073                                         progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS,
1074                                                       &args->progress);
1075                                         if (args->progress.extract.completed_bytes >=
1076                                             args->progress.extract.total_bytes)
1077                                         {
1078                                                 next_progress = ~0ULL;
1079                                         } else {
1080                                                 next_progress =
1081                                                         min (args->progress.extract.completed_bytes +
1082                                                              bytes_per_progress,
1083                                                              args->progress.extract.total_bytes);
1084                                         }
1085                                 }
1086                         }
1087                 }
1088         }
1089         return 0;
1090 }
1091
1092 /* Extracts the image @image from the WIM @w to the directory or NTFS volume
1093  * @target. */
1094 static int extract_single_image(WIMStruct *w, int image,
1095                                 const char *target, int extract_flags,
1096                                 wimlib_progress_func_t progress_func)
1097 {
1098         int ret;
1099         struct list_head stream_list;
1100         struct hlist_head *inode_list;
1101
1102         struct apply_args args;
1103         const struct apply_operations *ops;
1104
1105         args.w                    = w;
1106         args.target               = target;
1107         args.extract_flags        = extract_flags;
1108         args.num_lutimes_warnings = 0;
1109         args.stream_list          = &stream_list;
1110         args.progress_func        = progress_func;
1111
1112         if (progress_func) {
1113                 args.progress.extract.wimfile_name = w->filename;
1114                 args.progress.extract.image = image;
1115                 args.progress.extract.extract_flags = (extract_flags &
1116                                                        WIMLIB_EXTRACT_MASK_PUBLIC);
1117                 args.progress.extract.image_name = wimlib_get_image_name(w, image);
1118                 args.progress.extract.target = target;
1119         }
1120
1121 #ifdef WITH_NTFS_3G
1122         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1123                 args.vol = ntfs_mount(target, 0);
1124                 if (!args.vol) {
1125                         ERROR_WITH_ERRNO("Failed to mount NTFS volume `%s'", target);
1126                         return WIMLIB_ERR_NTFS_3G;
1127                 }
1128                 ops = &ntfs_apply_operations;
1129         } else
1130 #endif
1131                 ops = &normal_apply_operations;
1132
1133         ret = select_wim_image(w, image);
1134         if (ret != 0)
1135                 goto out;
1136
1137         inode_list = &w->image_metadata[image - 1].inode_list;
1138
1139         /* Build a list of the streams that need to be extracted */
1140         find_streams_for_extraction(inode_list, &stream_list,
1141                                     w->lookup_table, extract_flags);
1142
1143         /* Calculate the number of bytes of data that will be extracted */
1144         calculate_bytes_to_extract(&stream_list, extract_flags,
1145                                    &args.progress);
1146
1147         if (progress_func) {
1148                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN,
1149                               &args.progress);
1150         }
1151
1152         /* If a sequential extraction was specified, sort the streams to be
1153          * extracted by their position in the WIM file, so that the WIM file can
1154          * be read sequentially. */
1155         if (extract_flags & WIMLIB_EXTRACT_FLAG_SEQUENTIAL) {
1156                 ret = sort_stream_list_by_wim_position(&stream_list);
1157                 if (ret != 0) {
1158                         WARNING("Falling back to non-sequential extraction");
1159                         extract_flags &= ~WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
1160                 }
1161         }
1162
1163         if (progress_func) {
1164                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN,
1165                               &args.progress);
1166         }
1167
1168         /* Make the directory structure and extract empty files */
1169         args.extract_flags |= WIMLIB_EXTRACT_FLAG_NO_STREAMS;
1170         args.apply_dentry = ops->apply_dentry;
1171         ret = for_dentry_in_tree(wim_root_dentry(w), maybe_apply_dentry, &args);
1172         args.extract_flags &= ~WIMLIB_EXTRACT_FLAG_NO_STREAMS;
1173         if (ret != 0)
1174                 goto out;
1175
1176         if (progress_func) {
1177                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_END,
1178                               &args.progress);
1179         }
1180
1181         /* Extract non-empty files */
1182         ret = apply_stream_list(&stream_list, &args, ops, progress_func);
1183         if (ret != 0)
1184                 goto out;
1185
1186         if (progress_func) {
1187                 progress_func(WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS,
1188                               &args.progress);
1189         }
1190
1191         /* Apply timestamps */
1192         ret = for_dentry_in_tree_depth(wim_root_dentry(w),
1193                                        ops->apply_dentry_timestamps, &args);
1194         if (ret != 0)
1195                 goto out;
1196
1197         if (progress_func) {
1198                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END,
1199                               &args.progress);
1200         }
1201 out:
1202 #ifdef WITH_NTFS_3G
1203         /* Unmount the NTFS volume */
1204         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1205                 if (ntfs_umount(args.vol, FALSE) != 0) {
1206                         ERROR_WITH_ERRNO("Failed to unmount NTFS volume `%s'", args.target);
1207                         if (ret == 0)
1208                                 ret = WIMLIB_ERR_NTFS_3G;
1209                 }
1210         }
1211 #endif
1212         return ret;
1213 }
1214
1215
1216 /* Extracts all images from the WIM to the directory @target, with the images
1217  * placed in subdirectories named by their image names. */
1218 static int extract_all_images(WIMStruct *w, const char *target,
1219                               int extract_flags,
1220                               wimlib_progress_func_t progress_func)
1221 {
1222         size_t image_name_max_len = max(xml_get_max_image_name_len(w), 20);
1223         size_t output_path_len = strlen(target);
1224         char buf[output_path_len + 1 + image_name_max_len + 1];
1225         int ret;
1226         int image;
1227         const char *image_name;
1228
1229         ret = extract_directory(NULL, target, true);
1230         if (ret != 0)
1231                 return ret;
1232
1233         memcpy(buf, target, output_path_len);
1234         buf[output_path_len] = '/';
1235         for (image = 1; image <= w->hdr.image_count; image++) {
1236                 image_name = wimlib_get_image_name(w, image);
1237                 if (image_name && *image_name) {
1238                         strcpy(buf + output_path_len + 1, image_name);
1239                 } else {
1240                         /* Image name is empty. Use image number instead */
1241                         sprintf(buf + output_path_len + 1, "%d", image);
1242                 }
1243                 ret = extract_single_image(w, image, buf, extract_flags,
1244                                            progress_func);
1245                 if (ret != 0)
1246                         return ret;
1247         }
1248         return 0;
1249 }
1250
1251 /* Extracts a single image or all images from a WIM file to a directory or NTFS
1252  * volume. */
1253 WIMLIBAPI int wimlib_extract_image(WIMStruct *w,
1254                                    int image,
1255                                    const char *target,
1256                                    int extract_flags,
1257                                    WIMStruct **additional_swms,
1258                                    unsigned num_additional_swms,
1259                                    wimlib_progress_func_t progress_func)
1260 {
1261         struct wim_lookup_table *joined_tab, *w_tab_save;
1262         int ret;
1263
1264         if (!target)
1265                 return WIMLIB_ERR_INVALID_PARAM;
1266
1267         extract_flags &= WIMLIB_EXTRACT_MASK_PUBLIC;
1268
1269         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
1270                         == (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
1271                 return WIMLIB_ERR_INVALID_PARAM;
1272
1273 #if defined(__CYGWIN__) || defined(__WIN32__)
1274         if (extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
1275                 ERROR("Extracting UNIX data is not supported on Windows");
1276                 return WIMLIB_ERR_INVALID_PARAM;
1277         }
1278         if (extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK)) {
1279                 ERROR("Linked extraction modes are not supported on Windows");
1280                 return WIMLIB_ERR_INVALID_PARAM;
1281         }
1282 #endif
1283
1284         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1285 #ifdef WITH_NTFS_3G
1286                 if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))) {
1287                         ERROR("Cannot specify symlink or hardlink flags when applying\n"
1288                               "        directly to a NTFS volume");
1289                         return WIMLIB_ERR_INVALID_PARAM;
1290                 }
1291                 if (image == WIMLIB_ALL_IMAGES) {
1292                         ERROR("Can only apply a single image when applying "
1293                               "directly to a NTFS volume");
1294                         return WIMLIB_ERR_INVALID_PARAM;
1295                 }
1296                 if (extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
1297                         ERROR("Cannot restore UNIX-specific data in the NTFS extraction mode");
1298                         return WIMLIB_ERR_INVALID_PARAM;
1299                 }
1300 #else
1301                 ERROR("wimlib was compiled without support for NTFS-3g, so");
1302                 ERROR("we cannot apply a WIM image directly to a NTFS volume");
1303                 return WIMLIB_ERR_UNSUPPORTED;
1304 #endif
1305         }
1306
1307         ret = verify_swm_set(w, additional_swms, num_additional_swms);
1308         if (ret != 0)
1309                 return ret;
1310
1311         if (num_additional_swms) {
1312                 ret = new_joined_lookup_table(w, additional_swms,
1313                                               num_additional_swms, &joined_tab);
1314                 if (ret != 0)
1315                         return ret;
1316                 w_tab_save = w->lookup_table;
1317                 w->lookup_table = joined_tab;
1318         }
1319
1320         if (image == WIMLIB_ALL_IMAGES) {
1321                 extract_flags |= WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
1322                 ret = extract_all_images(w, target, extract_flags,
1323                                          progress_func);
1324         } else {
1325                 extract_flags &= ~WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
1326                 ret = extract_single_image(w, image, target, extract_flags,
1327                                            progress_func);
1328         }
1329
1330         if (extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
1331                              WIMLIB_EXTRACT_FLAG_HARDLINK))
1332         {
1333                 for_lookup_table_entry(w->lookup_table,
1334                                        lte_free_extracted_file,
1335                                        NULL);
1336         }
1337
1338         if (num_additional_swms) {
1339                 free_lookup_table(w->lookup_table);
1340                 w->lookup_table = w_tab_save;
1341         }
1342         return ret;
1343 }