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