]> wimlib.net Git - wimlib/blob - src/extract_image.c
Win32: minor code cleanups
[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: the '$DATA' suffix
173                  * seems to be unneeded.  Additional note: a "./" prefix needs
174                  * to be added when the path is not absolute to avoid ambiguity
175                  * 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[0] != 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; its path is just the path to the file itself.
195                  * */
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                                               stream_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 = %"PRIu64")",
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  *
328  * Returns 0 on success; nonzero on failure.
329  */
330 static int win32_set_security_data(const struct wim_inode *inode,
331                                    const wchar_t *path,
332                                    const struct wim_security_data *sd)
333 {
334         SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
335                                                    SACL_SECURITY_INFORMATION |
336                                                    OWNER_SECURITY_INFORMATION |
337                                                    GROUP_SECURITY_INFORMATION;
338         if (!SetFileSecurityW(path, securityInformation,
339                               (PSECURITY_DESCRIPTOR)sd->descriptors[inode->i_security_id]))
340         {
341                 DWORD err = GetLastError();
342                 ERROR("Can't set security descriptor on \"%ls\"", path);
343                 win32_error(err);
344                 return WIMLIB_ERR_WRITE;
345         }
346         return 0;
347 }
348
349 #else /* __CYGWIN__ || __WIN32__ */
350 static int extract_regular_file_linked(struct wim_dentry *dentry,
351                                        const char *output_path,
352                                        struct apply_args *args,
353                                        struct wim_lookup_table_entry *lte)
354 {
355         /* This mode overrides the normal hard-link extraction and
356          * instead either symlinks or hardlinks *all* identical files in
357          * the WIM, even if they are in a different image (in the case
358          * of a multi-image extraction) */
359
360         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_HARDLINK) {
361                 if (link(lte->extracted_file, output_path) != 0) {
362                         ERROR_WITH_ERRNO("Failed to hard link "
363                                          "`%s' to `%s'",
364                                          output_path, lte->extracted_file);
365                         return WIMLIB_ERR_LINK;
366                 }
367         } else {
368                 int num_path_components;
369                 int num_output_dir_path_components;
370                 size_t extracted_file_len;
371                 char *p;
372                 const char *p2;
373                 size_t i;
374
375                 num_path_components =
376                         get_num_path_components(dentry->full_path_utf8) - 1;
377                 num_output_dir_path_components =
378                         get_num_path_components(args->target);
379
380                 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_MULTI_IMAGE) {
381                         num_path_components++;
382                         num_output_dir_path_components--;
383                 }
384                 extracted_file_len = strlen(lte->extracted_file);
385
386                 char buf[extracted_file_len + 3 * num_path_components + 1];
387                 p = &buf[0];
388
389                 for (i = 0; i < num_path_components; i++) {
390                         *p++ = '.';
391                         *p++ = '.';
392                         *p++ = '/';
393                 }
394                 p2 = lte->extracted_file;
395                 while (*p2 == '/')
396                         p2++;
397                 while (num_output_dir_path_components--)
398                         p2 = path_next_part(p2, NULL);
399                 strcpy(p, p2);
400                 if (symlink(buf, output_path) != 0) {
401                         ERROR_WITH_ERRNO("Failed to symlink `%s' to "
402                                          "`%s'",
403                                          buf, lte->extracted_file);
404                         return WIMLIB_ERR_LINK;
405                 }
406         }
407         return 0;
408 }
409
410 static int symlink_apply_unix_data(const char *link,
411                                    const struct wimlib_unix_data *unix_data)
412 {
413         if (lchown(link, unix_data->uid, unix_data->gid)) {
414                 if (errno == EPERM) {
415                         /* Ignore */
416                         WARNING_WITH_ERRNO("failed to set symlink UNIX owner/group");
417                 } else {
418                         ERROR_WITH_ERRNO("failed to set symlink UNIX owner/group");
419                         return WIMLIB_ERR_INVALID_DENTRY;
420                 }
421         }
422         return 0;
423 }
424
425 static int fd_apply_unix_data(int fd, const struct wimlib_unix_data *unix_data)
426 {
427         if (fchown(fd, unix_data->uid, unix_data->gid)) {
428                 if (errno == EPERM) {
429                         WARNING_WITH_ERRNO("failed to set file UNIX owner/group");
430                         /* Ignore? */
431                 } else {
432                         ERROR_WITH_ERRNO("failed to set file UNIX owner/group");
433                         return WIMLIB_ERR_INVALID_DENTRY;
434                 }
435         }
436
437         if (fchmod(fd, unix_data->mode)) {
438                 if (errno == EPERM) {
439                         WARNING_WITH_ERRNO("failed to set UNIX file mode");
440                         /* Ignore? */
441                 } else {
442                         ERROR_WITH_ERRNO("failed to set UNIX file mode");
443                         return WIMLIB_ERR_INVALID_DENTRY;
444                 }
445         }
446         return 0;
447 }
448
449 static int dir_apply_unix_data(const char *dir,
450                                const struct wimlib_unix_data *unix_data)
451 {
452         int dfd = open(dir, O_RDONLY);
453         int ret;
454         if (dfd >= 0) {
455                 ret = fd_apply_unix_data(dfd, unix_data);
456                 if (close(dfd)) {
457                         ERROR_WITH_ERRNO("can't close directory `%s'", dir);
458                         ret = WIMLIB_ERR_MKDIR;
459                 }
460         } else {
461                 ERROR_WITH_ERRNO("can't open directory `%s'", dir);
462                 ret = WIMLIB_ERR_MKDIR;
463         }
464         return ret;
465 }
466
467 static int extract_regular_file_unlinked(struct wim_dentry *dentry,
468                                          struct apply_args *args,
469                                          const char *output_path,
470                                          struct wim_lookup_table_entry *lte)
471 {
472         /* Normal mode of extraction.  Regular files and hard links are
473          * extracted in the way that they appear in the WIM. */
474
475         int out_fd;
476         int ret;
477         struct wim_inode *inode = dentry->d_inode;
478
479         if (!((args->extract_flags & WIMLIB_EXTRACT_FLAG_MULTI_IMAGE)
480                 && (args->extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
481                                      WIMLIB_EXTRACT_FLAG_HARDLINK))))
482         {
483                 /* If the dentry is part of a hard link set of at least 2
484                  * dentries and one of the other dentries has already been
485                  * extracted, make a hard link to the file corresponding to this
486                  * already-extracted directory.  Otherwise, extract the file and
487                  * set the inode->i_extracted_file field so that other dentries
488                  * in the hard link group can link to it. */
489                 if (inode->i_nlink > 1) {
490                         if (inode->i_extracted_file) {
491                                 DEBUG("Extracting hard link `%s' => `%s'",
492                                       output_path, inode->i_extracted_file);
493                                 if (link(inode->i_extracted_file, output_path) != 0) {
494                                         ERROR_WITH_ERRNO("Failed to hard link "
495                                                          "`%s' to `%s'",
496                                                          output_path,
497                                                          inode->i_extracted_file);
498                                         return WIMLIB_ERR_LINK;
499                                 }
500                                 return 0;
501                         }
502                         FREE(inode->i_extracted_file);
503                         inode->i_extracted_file = STRDUP(output_path);
504                         if (!inode->i_extracted_file) {
505                                 ERROR("Failed to allocate memory for filename");
506                                 return WIMLIB_ERR_NOMEM;
507                         }
508                 }
509         }
510
511         /* Extract the contents of the file to @output_path. */
512
513         out_fd = open(output_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
514         if (out_fd == -1) {
515                 ERROR_WITH_ERRNO("Failed to open the file `%s' for writing",
516                                  output_path);
517                 return WIMLIB_ERR_OPEN;
518         }
519
520         if (!lte) {
521                 /* Empty file with no lookup table entry */
522                 DEBUG("Empty file `%s'.", output_path);
523                 ret = 0;
524                 goto out_extract_unix_data;
525         }
526
527         ret = extract_wim_resource_to_fd(lte, out_fd, wim_resource_size(lte));
528         if (ret != 0) {
529                 ERROR("Failed to extract resource to `%s'", output_path);
530                 goto out;
531         }
532
533 out_extract_unix_data:
534         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
535                 struct wimlib_unix_data unix_data;
536                 ret = inode_get_unix_data(inode, &unix_data, NULL);
537                 if (ret > 0)
538                         ;
539                 else if (ret < 0)
540                         ret = 0;
541                 else
542                         ret = fd_apply_unix_data(out_fd, &unix_data);
543                 if (ret != 0)
544                         goto out;
545         }
546         if (lte)
547                 args->progress.extract.completed_bytes += wim_resource_size(lte);
548 out:
549         if (close(out_fd) != 0) {
550                 ERROR_WITH_ERRNO("Failed to close file `%s'", output_path);
551                 if (ret == 0)
552                         ret = WIMLIB_ERR_WRITE;
553         }
554         return ret;
555 }
556
557 static int extract_regular_file(struct wim_dentry *dentry,
558                                 struct apply_args *args,
559                                 const char *output_path)
560 {
561         struct wim_lookup_table_entry *lte;
562         const struct wim_inode *inode = dentry->d_inode;
563
564         lte = inode_unnamed_lte_resolved(inode);
565
566         if (lte && (args->extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
567                                            WIMLIB_EXTRACT_FLAG_HARDLINK)))
568         {
569                 if (lte->extracted_file) {
570                         return extract_regular_file_linked(dentry, output_path, args, lte);
571                 } else {
572                         lte->extracted_file = STRDUP(output_path);
573                         if (!lte->extracted_file)
574                                 return WIMLIB_ERR_NOMEM;
575                 }
576         }
577         return extract_regular_file_unlinked(dentry, args, output_path, lte);
578 }
579
580 static int extract_symlink(struct wim_dentry *dentry,
581                            struct apply_args *args,
582                            const char *output_path)
583 {
584         char target[4096];
585         ssize_t ret = inode_readlink(dentry->d_inode, target,
586                                      sizeof(target), args->w, 0);
587         struct wim_lookup_table_entry *lte;
588
589         if (ret <= 0) {
590                 ERROR("Could not read the symbolic link from dentry `%s'",
591                       dentry->full_path_utf8);
592                 return WIMLIB_ERR_INVALID_DENTRY;
593         }
594         ret = symlink(target, output_path);
595         if (ret != 0) {
596                 ERROR_WITH_ERRNO("Failed to symlink `%s' to `%s'",
597                                  output_path, target);
598                 return WIMLIB_ERR_LINK;
599         }
600         lte = inode_unnamed_lte_resolved(dentry->d_inode);
601         wimlib_assert(lte != NULL);
602         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
603                 struct wimlib_unix_data unix_data;
604                 ret = inode_get_unix_data(dentry->d_inode, &unix_data, NULL);
605                 if (ret > 0)
606                         ;
607                 else if (ret < 0)
608                         ret = 0;
609                 else
610                         ret = symlink_apply_unix_data(output_path, &unix_data);
611                 if (ret != 0)
612                         return ret;
613         }
614         args->progress.extract.completed_bytes += wim_resource_size(lte);
615         return 0;
616 }
617
618 #endif /* !(__CYGWIN__ || __WIN32__) */
619
620 static int extract_directory(struct wim_dentry *dentry,
621                              const char *output_path, bool is_root)
622 {
623         int ret;
624         struct stat stbuf;
625
626         ret = stat(output_path, &stbuf);
627         if (ret == 0) {
628                 if (S_ISDIR(stbuf.st_mode)) {
629                         /*if (!is_root)*/
630                                 /*WARNING("`%s' already exists", output_path);*/
631                         goto dir_exists;
632                 } else {
633                         ERROR("`%s' is not a directory", output_path);
634                         return WIMLIB_ERR_MKDIR;
635                 }
636         } else {
637                 if (errno != ENOENT) {
638                         ERROR_WITH_ERRNO("Failed to stat `%s'", output_path);
639                         return WIMLIB_ERR_STAT;
640                 }
641         }
642         if (mkdir(output_path, S_IRWXU | S_IRGRP | S_IXGRP |
643                                S_IROTH | S_IXOTH) != 0) {
644                 ERROR_WITH_ERRNO("Cannot create directory `%s'",
645                                  output_path);
646                 return WIMLIB_ERR_MKDIR;
647         }
648 dir_exists:
649         ret = 0;
650 #if !defined(__CYGWIN__) && !defined(__WIN32__)
651         if (dentry) {
652                 struct wimlib_unix_data unix_data;
653                 ret = inode_get_unix_data(dentry->d_inode, &unix_data, NULL);
654                 if (ret > 0)
655                         ;
656                 else if (ret < 0)
657                         ret = 0;
658                 else
659                         ret = dir_apply_unix_data(output_path, &unix_data);
660         }
661 #endif
662         return ret;
663 }
664
665 /* Extracts a file, directory, or symbolic link from the WIM archive. */
666 static int apply_dentry_normal(struct wim_dentry *dentry, void *arg)
667 {
668         struct apply_args *args = arg;
669         struct wim_inode *inode = dentry->d_inode;
670         size_t len;
671         char *output_path;
672
673         len = strlen(args->target);
674         if (dentry_is_root(dentry)) {
675                 output_path = (char*)args->target;
676         } else {
677                 output_path = alloca(len + dentry->full_path_utf8_len + 1);
678                 memcpy(output_path, args->target, len);
679                 memcpy(output_path + len, dentry->full_path_utf8, dentry->full_path_utf8_len);
680                 output_path[len + dentry->full_path_utf8_len] = '\0';
681                 len += dentry->full_path_utf8_len;
682         }
683
684 #if defined(__CYGWIN__) || defined(__WIN32__)
685         char *utf16_path;
686         size_t utf16_path_len;
687         DWORD err;
688         int ret;
689         ret = utf8_to_utf16(output_path, len, &utf16_path, &utf16_path_len);
690         if (ret)
691                 return ret;
692
693         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
694                 /* Linked file, with another name already extracted.  Create a
695                  * hard link. */
696                 DEBUG("Creating hard link \"%ls => %ls\"",
697                       (const wchar_t*)utf16_path,
698                       (const wchar_t*)inode->i_extracted_file);
699                 if (!CreateHardLinkW((const wchar_t*)utf16_path,
700                                      (const wchar_t*)inode->i_extracted_file,
701                                      NULL))
702                 {
703                         err = GetLastError();
704                         ERROR("Can't create hard link \"%ls => %ls\"",
705                               (const wchar_t*)utf16_path,
706                               (const wchar_t*)inode->i_extracted_file);
707                         ret = WIMLIB_ERR_LINK;
708                         win32_error(err);
709                 }
710         } else {
711                 /* Create the file, directory, or reparse point, and extract the
712                  * data streams. */
713                 ret = win32_extract_streams(inode, (const wchar_t*)utf16_path,
714                                             &args->progress.extract.completed_bytes);
715                 if (ret)
716                         goto out_free_utf16_path;
717
718                 /* Set security descriptor if present */
719                 if (inode->i_security_id != -1) {
720                         DEBUG("Setting security descriptor %d on %s",
721                               inode->i_security_id, output_path);
722                         ret = win32_set_security_data(inode,
723                                                       (const wchar_t*)utf16_path,
724                                                       wim_const_security_data(args->w));
725                         if (ret)
726                                 goto out_free_utf16_path;
727                 }
728                 if (inode->i_nlink > 1) {
729                         /* Save extracted path for a later call to
730                          * CreateHardLinkW() if this inode has multiple links.
731                          * */
732                         inode->i_extracted_file = utf16_path;
733                         goto out;
734                 }
735         }
736 out_free_utf16_path:
737         FREE(utf16_path);
738 out:
739         return ret;
740 #else
741         if (inode_is_symlink(inode))
742                 return extract_symlink(dentry, args, output_path);
743         else if (inode_is_directory(inode))
744                 return extract_directory((args->extract_flags &
745                                            WIMLIB_EXTRACT_FLAG_UNIX_DATA) ? dentry : NULL,
746                                          output_path, false);
747         else
748                 return extract_regular_file(dentry, args, output_path);
749 #endif
750 }
751
752 /* Apply timestamps to an extracted file or directory */
753 static int apply_dentry_timestamps_normal(struct wim_dentry *dentry, void *arg)
754 {
755         struct apply_args *args = arg;
756         size_t len;
757         char *output_path;
758         int ret;
759         const struct wim_inode *inode = dentry->d_inode;
760
761         len = strlen(args->target);
762         if (dentry_is_root(dentry)) {
763                 output_path = (char*)args->target;
764         } else {
765                 output_path = alloca(len + dentry->full_path_utf8_len + 1);
766                 memcpy(output_path, args->target, len);
767                 memcpy(output_path + len, dentry->full_path_utf8, dentry->full_path_utf8_len);
768                 output_path[len + dentry->full_path_utf8_len] = '\0';
769                 len += dentry->full_path_utf8_len;
770         }
771
772 #if defined(__CYGWIN__) || defined(__WIN32__)
773         /* Win32 */
774         char *utf16_path;
775         size_t utf16_path_len;
776         DWORD err;
777         HANDLE h;
778         BOOL bret1, bret2;
779
780         ret = utf8_to_utf16(output_path, len, &utf16_path, &utf16_path_len);
781         if (ret)
782                 return ret;
783
784         DEBUG("Opening \"%s\" to set timestamps", output_path);
785         h = CreateFileW((const wchar_t*)utf16_path,
786                         GENERIC_WRITE | WRITE_OWNER | WRITE_DAC | ACCESS_SYSTEM_SECURITY,
787                         FILE_SHARE_READ,
788                         NULL,
789                         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 = inode->i_creation_time & 0xffffffff,
800                                  .dwHighDateTime = inode->i_creation_time >> 32};
801         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
802                                   .dwHighDateTime = inode->i_last_access_time >> 32};
803         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
804                                   .dwHighDateTime = 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         goto out;
818 fail:
819         /* Only warn if setting timestamps failed. */
820         WARNING("Can't set timestamps on \"%s\"", output_path);
821         win32_error(err);
822 out:
823         return 0;
824 #else
825         /* UNIX */
826
827         /* Convert the WIM timestamps, which are accurate to 100 nanoseconds,
828          * into struct timeval's. */
829         struct timeval tv[2];
830         wim_timestamp_to_timeval(inode->i_last_access_time, &tv[0]);
831         wim_timestamp_to_timeval(inode->i_last_write_time, &tv[1]);
832         #ifdef HAVE_LUTIMES
833         ret = lutimes(output_path, tv);
834         #else
835         ret = -1;
836         errno = ENOSYS;
837         #endif
838         if (ret != 0) {
839                 #ifdef HAVE_UTIME
840                 if (errno == ENOSYS) {
841                         struct utimbuf buf;
842                         buf.actime = wim_timestamp_to_unix(inode->i_last_access_time);
843                         buf.modtime = wim_timestamp_to_unix(inode->i_last_write_time);
844                         if (utime(output_path, &buf) == 0)
845                                 return 0;
846                 }
847                 #endif
848                 if (errno != ENOSYS || args->num_lutimes_warnings < 10) {
849                         /*WARNING_WITH_ERRNO("Failed to set timestamp on file `%s',*/
850                                             /*output_path");*/
851                         args->num_lutimes_warnings++;
852                 }
853         }
854         return 0;
855 #endif
856 }
857
858 /* Extract a dentry if it hasn't already been extracted, and either the dentry
859  * has no streams or WIMLIB_EXTRACT_FLAG_NO_STREAMS is not specified. */
860 static int maybe_apply_dentry(struct wim_dentry *dentry, void *arg)
861 {
862         struct apply_args *args = arg;
863         int ret;
864
865         if (dentry->is_extracted)
866                 return 0;
867
868         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_STREAMS)
869                 if (inode_unnamed_lte_resolved(dentry->d_inode))
870                         return 0;
871
872         if ((args->extract_flags & WIMLIB_EXTRACT_FLAG_VERBOSE) &&
873              args->progress_func) {
874                 args->progress.extract.cur_path = dentry->full_path_utf8;
875                 args->progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY,
876                                     &args->progress);
877         }
878         ret = args->apply_dentry(dentry, args);
879         if (ret == 0)
880                 dentry->is_extracted = 1;
881         return ret;
882 }
883
884 static int cmp_streams_by_wim_position(const void *p1, const void *p2)
885 {
886         const struct wim_lookup_table_entry *lte1, *lte2;
887         lte1 = *(const struct wim_lookup_table_entry**)p1;
888         lte2 = *(const struct wim_lookup_table_entry**)p2;
889         if (lte1->resource_entry.offset < lte2->resource_entry.offset)
890                 return -1;
891         else if (lte1->resource_entry.offset > lte2->resource_entry.offset)
892                 return 1;
893         else
894                 return 0;
895 }
896
897 static int sort_stream_list_by_wim_position(struct list_head *stream_list)
898 {
899         struct list_head *cur;
900         size_t num_streams;
901         struct wim_lookup_table_entry **array;
902         size_t i;
903         size_t array_size;
904
905         num_streams = 0;
906         list_for_each(cur, stream_list)
907                 num_streams++;
908         array_size = num_streams * sizeof(array[0]);
909         array = MALLOC(array_size);
910         if (!array) {
911                 ERROR("Failed to allocate %zu bytes to sort stream entries",
912                       array_size);
913                 return WIMLIB_ERR_NOMEM;
914         }
915         cur = stream_list->next;
916         for (i = 0; i < num_streams; i++) {
917                 array[i] = container_of(cur, struct wim_lookup_table_entry, staging_list);
918                 cur = cur->next;
919         }
920
921         qsort(array, num_streams, sizeof(array[0]), cmp_streams_by_wim_position);
922
923         INIT_LIST_HEAD(stream_list);
924         for (i = 0; i < num_streams; i++)
925                 list_add_tail(&array[i]->staging_list, stream_list);
926         FREE(array);
927         return 0;
928 }
929
930 static void calculate_bytes_to_extract(struct list_head *stream_list,
931                                        int extract_flags,
932                                        union wimlib_progress_info *progress)
933 {
934         struct wim_lookup_table_entry *lte;
935         u64 total_bytes = 0;
936         u64 num_streams = 0;
937
938         /* For each stream to be extracted... */
939         list_for_each_entry(lte, stream_list, staging_list) {
940                 if (extract_flags &
941                     (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
942                 {
943                         /* In the symlink or hard link extraction mode, each
944                          * stream will be extracted one time regardless of how
945                          * many dentries share the stream. */
946                         wimlib_assert(!(extract_flags & WIMLIB_EXTRACT_FLAG_NTFS));
947                         if (!lte->extracted_file) {
948                                 num_streams++;
949                                 total_bytes += wim_resource_size(lte);
950                         }
951                 } else {
952                         num_streams += lte->out_refcnt;
953                         total_bytes += lte->out_refcnt * wim_resource_size(lte);
954                 }
955         }
956         progress->extract.num_streams = num_streams;
957         progress->extract.total_bytes = total_bytes;
958         progress->extract.completed_bytes = 0;
959 }
960
961 static void maybe_add_stream_for_extraction(struct wim_lookup_table_entry *lte,
962                                             struct list_head *stream_list)
963 {
964         if (++lte->out_refcnt == 1) {
965                 INIT_LIST_HEAD(&lte->inode_list);
966                 list_add_tail(&lte->staging_list, stream_list);
967         }
968 }
969
970 static void inode_find_streams_for_extraction(struct wim_inode *inode,
971                                               struct list_head *stream_list,
972                                               int extract_flags)
973 {
974         struct wim_lookup_table_entry *lte;
975         bool inode_added = false;
976
977         lte = inode_unnamed_lte_resolved(inode);
978         if (lte) {
979                 maybe_add_stream_for_extraction(lte, stream_list);
980                 list_add_tail(&inode->i_lte_inode_list, &lte->inode_list);
981                 inode_added = true;
982         }
983 #ifdef WITH_NTFS_3G
984         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
985                 for (unsigned i = 0; i < inode->i_num_ads; i++) {
986                         if (inode->i_ads_entries[i].stream_name_len != 0) {
987                                 lte = inode->i_ads_entries[i].lte;
988                                 if (lte) {
989                                         maybe_add_stream_for_extraction(lte,
990                                                                         stream_list);
991                                         if (!inode_added) {
992                                                 list_add_tail(&inode->i_lte_inode_list,
993                                                               &lte->inode_list);
994                                                 inode_added = true;
995                                         }
996                                 }
997                         }
998                 }
999         }
1000 #endif
1001 }
1002
1003 static void find_streams_for_extraction(struct hlist_head *inode_list,
1004                                         struct list_head *stream_list,
1005                                         struct wim_lookup_table *lookup_table,
1006                                         int extract_flags)
1007 {
1008         struct wim_inode *inode;
1009         struct hlist_node *cur;
1010         struct wim_dentry *dentry;
1011
1012         for_lookup_table_entry(lookup_table, lte_zero_out_refcnt, NULL);
1013         INIT_LIST_HEAD(stream_list);
1014         hlist_for_each_entry(inode, cur, inode_list, i_hlist) {
1015                 if (!inode->i_resolved)
1016                         inode_resolve_ltes(inode, lookup_table);
1017                 inode_for_each_dentry(dentry, inode)
1018                         dentry->is_extracted = 0;
1019                 inode_find_streams_for_extraction(inode, stream_list,
1020                                                   extract_flags);
1021         }
1022 }
1023
1024 struct apply_operations {
1025         int (*apply_dentry)(struct wim_dentry *dentry, void *arg);
1026         int (*apply_dentry_timestamps)(struct wim_dentry *dentry, void *arg);
1027 };
1028
1029 static const struct apply_operations normal_apply_operations = {
1030         .apply_dentry = apply_dentry_normal,
1031         .apply_dentry_timestamps = apply_dentry_timestamps_normal,
1032 };
1033
1034 #ifdef WITH_NTFS_3G
1035 static const struct apply_operations ntfs_apply_operations = {
1036         .apply_dentry = apply_dentry_ntfs,
1037         .apply_dentry_timestamps = apply_dentry_timestamps_ntfs,
1038 };
1039 #endif
1040
1041 static int apply_stream_list(struct list_head *stream_list,
1042                              struct apply_args *args,
1043                              const struct apply_operations *ops,
1044                              wimlib_progress_func_t progress_func)
1045 {
1046         uint64_t bytes_per_progress = args->progress.extract.total_bytes / 100;
1047         uint64_t next_progress = bytes_per_progress;
1048         struct wim_lookup_table_entry *lte;
1049         struct wim_inode *inode;
1050         struct wim_dentry *dentry;
1051         int ret;
1052
1053         /* This complicated loop is essentially looping through the dentries,
1054          * although dentries may be visited more than once (if a dentry contains
1055          * two different nonempty streams) or not at all (if a dentry contains
1056          * no non-empty streams).
1057          *
1058          * The outer loop is over the distinct streams to be extracted so that
1059          * sequential reading of the WIM can be implemented. */
1060
1061         /* For each distinct stream to be extracted */
1062         list_for_each_entry(lte, stream_list, staging_list) {
1063                 /* For each inode that contains the stream */
1064                 list_for_each_entry(inode, &lte->inode_list, i_lte_inode_list) {
1065                         /* For each dentry that points to the inode */
1066                         inode_for_each_dentry(dentry, inode) {
1067                                 /* Extract the dentry if it was not already
1068                                  * extracted */
1069                                 ret = maybe_apply_dentry(dentry, args);
1070                                 if (ret != 0)
1071                                         return ret;
1072                                 if (progress_func &&
1073                                     args->progress.extract.completed_bytes >= next_progress)
1074                                 {
1075                                         progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS,
1076                                                       &args->progress);
1077                                         if (args->progress.extract.completed_bytes >=
1078                                             args->progress.extract.total_bytes)
1079                                         {
1080                                                 next_progress = ~0ULL;
1081                                         } else {
1082                                                 next_progress =
1083                                                         min (args->progress.extract.completed_bytes +
1084                                                              bytes_per_progress,
1085                                                              args->progress.extract.total_bytes);
1086                                         }
1087                                 }
1088                         }
1089                 }
1090         }
1091         return 0;
1092 }
1093
1094 /* Extracts the image @image from the WIM @w to the directory or NTFS volume
1095  * @target. */
1096 static int extract_single_image(WIMStruct *w, int image,
1097                                 const char *target, int extract_flags,
1098                                 wimlib_progress_func_t progress_func)
1099 {
1100         int ret;
1101         struct list_head stream_list;
1102         struct hlist_head *inode_list;
1103
1104         struct apply_args args;
1105         const struct apply_operations *ops;
1106
1107         args.w                    = w;
1108         args.target               = target;
1109         args.extract_flags        = extract_flags;
1110         args.num_lutimes_warnings = 0;
1111         args.stream_list          = &stream_list;
1112         args.progress_func        = progress_func;
1113
1114         if (progress_func) {
1115                 args.progress.extract.wimfile_name = w->filename;
1116                 args.progress.extract.image = image;
1117                 args.progress.extract.extract_flags = (extract_flags &
1118                                                        WIMLIB_EXTRACT_MASK_PUBLIC);
1119                 args.progress.extract.image_name = wimlib_get_image_name(w, image);
1120                 args.progress.extract.target = target;
1121         }
1122
1123 #ifdef WITH_NTFS_3G
1124         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1125                 args.vol = ntfs_mount(target, 0);
1126                 if (!args.vol) {
1127                         ERROR_WITH_ERRNO("Failed to mount NTFS volume `%s'", target);
1128                         return WIMLIB_ERR_NTFS_3G;
1129                 }
1130                 ops = &ntfs_apply_operations;
1131         } else
1132 #endif
1133                 ops = &normal_apply_operations;
1134
1135         ret = select_wim_image(w, image);
1136         if (ret != 0)
1137                 goto out;
1138
1139         inode_list = &w->image_metadata[image - 1].inode_list;
1140
1141         /* Build a list of the streams that need to be extracted */
1142         find_streams_for_extraction(inode_list, &stream_list,
1143                                     w->lookup_table, extract_flags);
1144
1145         /* Calculate the number of bytes of data that will be extracted */
1146         calculate_bytes_to_extract(&stream_list, extract_flags,
1147                                    &args.progress);
1148
1149         if (progress_func) {
1150                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN,
1151                               &args.progress);
1152         }
1153
1154         /* If a sequential extraction was specified, sort the streams to be
1155          * extracted by their position in the WIM file, so that the WIM file can
1156          * be read sequentially. */
1157         if (extract_flags & WIMLIB_EXTRACT_FLAG_SEQUENTIAL) {
1158                 ret = sort_stream_list_by_wim_position(&stream_list);
1159                 if (ret != 0) {
1160                         WARNING("Falling back to non-sequential extraction");
1161                         extract_flags &= ~WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
1162                 }
1163         }
1164
1165         if (progress_func) {
1166                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN,
1167                               &args.progress);
1168         }
1169
1170         /* Make the directory structure and extract empty files */
1171         args.extract_flags |= WIMLIB_EXTRACT_FLAG_NO_STREAMS;
1172         args.apply_dentry = ops->apply_dentry;
1173         ret = for_dentry_in_tree(wim_root_dentry(w), maybe_apply_dentry, &args);
1174         args.extract_flags &= ~WIMLIB_EXTRACT_FLAG_NO_STREAMS;
1175         if (ret != 0)
1176                 goto out;
1177
1178         if (progress_func) {
1179                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_END,
1180                               &args.progress);
1181         }
1182
1183         /* Extract non-empty files */
1184         ret = apply_stream_list(&stream_list, &args, ops, progress_func);
1185         if (ret != 0)
1186                 goto out;
1187
1188         if (progress_func) {
1189                 progress_func(WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS,
1190                               &args.progress);
1191         }
1192
1193         /* Apply timestamps */
1194         ret = for_dentry_in_tree_depth(wim_root_dentry(w),
1195                                        ops->apply_dentry_timestamps, &args);
1196         if (ret != 0)
1197                 goto out;
1198
1199         if (progress_func) {
1200                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END,
1201                               &args.progress);
1202         }
1203 out:
1204 #ifdef WITH_NTFS_3G
1205         /* Unmount the NTFS volume */
1206         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1207                 if (ntfs_umount(args.vol, FALSE) != 0) {
1208                         ERROR_WITH_ERRNO("Failed to unmount NTFS volume `%s'", args.target);
1209                         if (ret == 0)
1210                                 ret = WIMLIB_ERR_NTFS_3G;
1211                 }
1212         }
1213 #endif
1214         return ret;
1215 }
1216
1217
1218 /* Extracts all images from the WIM to the directory @target, with the images
1219  * placed in subdirectories named by their image names. */
1220 static int extract_all_images(WIMStruct *w, const char *target,
1221                               int extract_flags,
1222                               wimlib_progress_func_t progress_func)
1223 {
1224         size_t image_name_max_len = max(xml_get_max_image_name_len(w), 20);
1225         size_t output_path_len = strlen(target);
1226         char buf[output_path_len + 1 + image_name_max_len + 1];
1227         int ret;
1228         int image;
1229         const char *image_name;
1230
1231         ret = extract_directory(NULL, target, true);
1232         if (ret != 0)
1233                 return ret;
1234
1235         memcpy(buf, target, output_path_len);
1236         buf[output_path_len] = '/';
1237         for (image = 1; image <= w->hdr.image_count; image++) {
1238                 image_name = wimlib_get_image_name(w, image);
1239                 if (image_name && *image_name) {
1240                         strcpy(buf + output_path_len + 1, image_name);
1241                 } else {
1242                         /* Image name is empty. Use image number instead */
1243                         sprintf(buf + output_path_len + 1, "%d", image);
1244                 }
1245                 ret = extract_single_image(w, image, buf, extract_flags,
1246                                            progress_func);
1247                 if (ret != 0)
1248                         return ret;
1249         }
1250         return 0;
1251 }
1252
1253 /* Extracts a single image or all images from a WIM file to a directory or NTFS
1254  * volume. */
1255 WIMLIBAPI int wimlib_extract_image(WIMStruct *w,
1256                                    int image,
1257                                    const char *target,
1258                                    int extract_flags,
1259                                    WIMStruct **additional_swms,
1260                                    unsigned num_additional_swms,
1261                                    wimlib_progress_func_t progress_func)
1262 {
1263         struct wim_lookup_table *joined_tab, *w_tab_save;
1264         int ret;
1265
1266         if (!target)
1267                 return WIMLIB_ERR_INVALID_PARAM;
1268
1269         extract_flags &= WIMLIB_EXTRACT_MASK_PUBLIC;
1270
1271         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
1272                         == (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
1273                 return WIMLIB_ERR_INVALID_PARAM;
1274
1275 #if defined(__CYGWIN__) || defined(__WIN32__)
1276         if (extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
1277                 ERROR("Extracting UNIX data is not supported on Windows");
1278                 return WIMLIB_ERR_INVALID_PARAM;
1279         }
1280         if (extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK)) {
1281                 ERROR("Linked extraction modes are not supported on Windows");
1282                 return WIMLIB_ERR_INVALID_PARAM;
1283         }
1284 #endif
1285
1286         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1287 #ifdef WITH_NTFS_3G
1288                 if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))) {
1289                         ERROR("Cannot specify symlink or hardlink flags when applying\n"
1290                               "        directly to a NTFS volume");
1291                         return WIMLIB_ERR_INVALID_PARAM;
1292                 }
1293                 if (image == WIMLIB_ALL_IMAGES) {
1294                         ERROR("Can only apply a single image when applying "
1295                               "directly to a NTFS volume");
1296                         return WIMLIB_ERR_INVALID_PARAM;
1297                 }
1298                 if (extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
1299                         ERROR("Cannot restore UNIX-specific data in the NTFS extraction mode");
1300                         return WIMLIB_ERR_INVALID_PARAM;
1301                 }
1302 #else
1303                 ERROR("wimlib was compiled without support for NTFS-3g, so");
1304                 ERROR("we cannot apply a WIM image directly to a NTFS volume");
1305                 return WIMLIB_ERR_UNSUPPORTED;
1306 #endif
1307         }
1308
1309         ret = verify_swm_set(w, additional_swms, num_additional_swms);
1310         if (ret != 0)
1311                 return ret;
1312
1313         if (num_additional_swms) {
1314                 ret = new_joined_lookup_table(w, additional_swms,
1315                                               num_additional_swms, &joined_tab);
1316                 if (ret != 0)
1317                         return ret;
1318                 w_tab_save = w->lookup_table;
1319                 w->lookup_table = joined_tab;
1320         }
1321
1322         if (image == WIMLIB_ALL_IMAGES) {
1323                 extract_flags |= WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
1324                 ret = extract_all_images(w, target, extract_flags,
1325                                          progress_func);
1326         } else {
1327                 extract_flags &= ~WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
1328                 ret = extract_single_image(w, image, target, extract_flags,
1329                                            progress_func);
1330         }
1331
1332         if (extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
1333                              WIMLIB_EXTRACT_FLAG_HARDLINK))
1334         {
1335                 for_lookup_table_entry(w->lookup_table,
1336                                        lte_free_extracted_file,
1337                                        NULL);
1338         }
1339
1340         if (num_additional_swms) {
1341                 free_lookup_table(w->lookup_table);
1342                 w->lookup_table = w_tab_save;
1343         }
1344         return ret;
1345 }