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