]> wimlib.net Git - wimlib/blob - src/extract_image.c
Win32: Acquire/release appropriate privileges
[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
779         ret = utf8_to_utf16(output_path, len, &utf16_path, &utf16_path_len);
780         if (ret)
781                 return ret;
782
783         DEBUG("Opening \"%s\" to set timestamps", output_path);
784         h = CreateFileW((const wchar_t*)utf16_path,
785                         GENERIC_WRITE | WRITE_OWNER | WRITE_DAC | ACCESS_SYSTEM_SECURITY,
786                         FILE_SHARE_READ,
787                         NULL,
788                         OPEN_EXISTING,
789                         FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
790                         NULL);
791
792         if (h == INVALID_HANDLE_VALUE)
793                 err = GetLastError();
794         FREE(utf16_path);
795         if (h == INVALID_HANDLE_VALUE)
796                 goto fail;
797
798         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
799                                  .dwHighDateTime = inode->i_creation_time >> 32};
800         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
801                                   .dwHighDateTime = inode->i_last_access_time >> 32};
802         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
803                                   .dwHighDateTime = inode->i_last_write_time >> 32};
804
805         DEBUG("Calling SetFileTime() on \"%s\"", output_path);
806         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
807                 err = GetLastError();
808                 CloseHandle(h);
809                 goto fail;
810         }
811         DEBUG("Closing \"%s\"", output_path);
812         if (!CloseHandle(h)) {
813                 err = GetLastError();
814                 goto fail;
815         }
816         goto out;
817 fail:
818         /* Only warn if setting timestamps failed. */
819         WARNING("Can't set timestamps on \"%s\"", output_path);
820         win32_error(err);
821 out:
822         return 0;
823 #else
824         /* UNIX */
825
826         /* Convert the WIM timestamps, which are accurate to 100 nanoseconds,
827          * into struct timeval's. */
828         struct timeval tv[2];
829         wim_timestamp_to_timeval(inode->i_last_access_time, &tv[0]);
830         wim_timestamp_to_timeval(inode->i_last_write_time, &tv[1]);
831         #ifdef HAVE_LUTIMES
832         ret = lutimes(output_path, tv);
833         #else
834         ret = -1;
835         errno = ENOSYS;
836         #endif
837         if (ret != 0) {
838                 #ifdef HAVE_UTIME
839                 if (errno == ENOSYS) {
840                         struct utimbuf buf;
841                         buf.actime = wim_timestamp_to_unix(inode->i_last_access_time);
842                         buf.modtime = wim_timestamp_to_unix(inode->i_last_write_time);
843                         if (utime(output_path, &buf) == 0)
844                                 return 0;
845                 }
846                 #endif
847                 if (errno != ENOSYS || args->num_lutimes_warnings < 10) {
848                         /*WARNING_WITH_ERRNO("Failed to set timestamp on file `%s',*/
849                                             /*output_path");*/
850                         args->num_lutimes_warnings++;
851                 }
852         }
853         return 0;
854 #endif
855 }
856
857 /* Extract a dentry if it hasn't already been extracted, and either the dentry
858  * has no streams or WIMLIB_EXTRACT_FLAG_NO_STREAMS is not specified. */
859 static int maybe_apply_dentry(struct wim_dentry *dentry, void *arg)
860 {
861         struct apply_args *args = arg;
862         int ret;
863
864         if (dentry->is_extracted)
865                 return 0;
866
867         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_STREAMS)
868                 if (inode_unnamed_lte_resolved(dentry->d_inode))
869                         return 0;
870
871         if ((args->extract_flags & WIMLIB_EXTRACT_FLAG_VERBOSE) &&
872              args->progress_func) {
873                 args->progress.extract.cur_path = dentry->full_path_utf8;
874                 args->progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY,
875                                     &args->progress);
876         }
877         ret = args->apply_dentry(dentry, args);
878         if (ret == 0)
879                 dentry->is_extracted = 1;
880         return ret;
881 }
882
883 static int cmp_streams_by_wim_position(const void *p1, const void *p2)
884 {
885         const struct wim_lookup_table_entry *lte1, *lte2;
886         lte1 = *(const struct wim_lookup_table_entry**)p1;
887         lte2 = *(const struct wim_lookup_table_entry**)p2;
888         if (lte1->resource_entry.offset < lte2->resource_entry.offset)
889                 return -1;
890         else if (lte1->resource_entry.offset > lte2->resource_entry.offset)
891                 return 1;
892         else
893                 return 0;
894 }
895
896 static int sort_stream_list_by_wim_position(struct list_head *stream_list)
897 {
898         struct list_head *cur;
899         size_t num_streams;
900         struct wim_lookup_table_entry **array;
901         size_t i;
902         size_t array_size;
903
904         num_streams = 0;
905         list_for_each(cur, stream_list)
906                 num_streams++;
907         array_size = num_streams * sizeof(array[0]);
908         array = MALLOC(array_size);
909         if (!array) {
910                 ERROR("Failed to allocate %zu bytes to sort stream entries",
911                       array_size);
912                 return WIMLIB_ERR_NOMEM;
913         }
914         cur = stream_list->next;
915         for (i = 0; i < num_streams; i++) {
916                 array[i] = container_of(cur, struct wim_lookup_table_entry, staging_list);
917                 cur = cur->next;
918         }
919
920         qsort(array, num_streams, sizeof(array[0]), cmp_streams_by_wim_position);
921
922         INIT_LIST_HEAD(stream_list);
923         for (i = 0; i < num_streams; i++)
924                 list_add_tail(&array[i]->staging_list, stream_list);
925         FREE(array);
926         return 0;
927 }
928
929 static void calculate_bytes_to_extract(struct list_head *stream_list,
930                                        int extract_flags,
931                                        union wimlib_progress_info *progress)
932 {
933         struct wim_lookup_table_entry *lte;
934         u64 total_bytes = 0;
935         u64 num_streams = 0;
936
937         /* For each stream to be extracted... */
938         list_for_each_entry(lte, stream_list, staging_list) {
939                 if (extract_flags &
940                     (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
941                 {
942                         /* In the symlink or hard link extraction mode, each
943                          * stream will be extracted one time regardless of how
944                          * many dentries share the stream. */
945                         wimlib_assert(!(extract_flags & WIMLIB_EXTRACT_FLAG_NTFS));
946                         if (!lte->extracted_file) {
947                                 num_streams++;
948                                 total_bytes += wim_resource_size(lte);
949                         }
950                 } else {
951                         num_streams += lte->out_refcnt;
952                         total_bytes += lte->out_refcnt * wim_resource_size(lte);
953                 }
954         }
955         progress->extract.num_streams = num_streams;
956         progress->extract.total_bytes = total_bytes;
957         progress->extract.completed_bytes = 0;
958 }
959
960 static void maybe_add_stream_for_extraction(struct wim_lookup_table_entry *lte,
961                                             struct list_head *stream_list)
962 {
963         if (++lte->out_refcnt == 1) {
964                 INIT_LIST_HEAD(&lte->inode_list);
965                 list_add_tail(&lte->staging_list, stream_list);
966         }
967 }
968
969 static void inode_find_streams_for_extraction(struct wim_inode *inode,
970                                               struct list_head *stream_list,
971                                               int extract_flags)
972 {
973         struct wim_lookup_table_entry *lte;
974         bool inode_added = false;
975
976         lte = inode_unnamed_lte_resolved(inode);
977         if (lte) {
978                 maybe_add_stream_for_extraction(lte, stream_list);
979                 list_add_tail(&inode->i_lte_inode_list, &lte->inode_list);
980                 inode_added = true;
981         }
982 #ifdef WITH_NTFS_3G
983         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
984                 for (unsigned i = 0; i < inode->i_num_ads; i++) {
985                         if (inode->i_ads_entries[i].stream_name_len != 0) {
986                                 lte = inode->i_ads_entries[i].lte;
987                                 if (lte) {
988                                         maybe_add_stream_for_extraction(lte,
989                                                                         stream_list);
990                                         if (!inode_added) {
991                                                 list_add_tail(&inode->i_lte_inode_list,
992                                                               &lte->inode_list);
993                                                 inode_added = true;
994                                         }
995                                 }
996                         }
997                 }
998         }
999 #endif
1000 }
1001
1002 static void find_streams_for_extraction(struct hlist_head *inode_list,
1003                                         struct list_head *stream_list,
1004                                         struct wim_lookup_table *lookup_table,
1005                                         int extract_flags)
1006 {
1007         struct wim_inode *inode;
1008         struct hlist_node *cur;
1009         struct wim_dentry *dentry;
1010
1011         for_lookup_table_entry(lookup_table, lte_zero_out_refcnt, NULL);
1012         INIT_LIST_HEAD(stream_list);
1013         hlist_for_each_entry(inode, cur, inode_list, i_hlist) {
1014                 if (!inode->i_resolved)
1015                         inode_resolve_ltes(inode, lookup_table);
1016                 inode_for_each_dentry(dentry, inode)
1017                         dentry->is_extracted = 0;
1018                 inode_find_streams_for_extraction(inode, stream_list,
1019                                                   extract_flags);
1020         }
1021 }
1022
1023 struct apply_operations {
1024         int (*apply_dentry)(struct wim_dentry *dentry, void *arg);
1025         int (*apply_dentry_timestamps)(struct wim_dentry *dentry, void *arg);
1026 };
1027
1028 static const struct apply_operations normal_apply_operations = {
1029         .apply_dentry = apply_dentry_normal,
1030         .apply_dentry_timestamps = apply_dentry_timestamps_normal,
1031 };
1032
1033 #ifdef WITH_NTFS_3G
1034 static const struct apply_operations ntfs_apply_operations = {
1035         .apply_dentry = apply_dentry_ntfs,
1036         .apply_dentry_timestamps = apply_dentry_timestamps_ntfs,
1037 };
1038 #endif
1039
1040 static int apply_stream_list(struct list_head *stream_list,
1041                              struct apply_args *args,
1042                              const struct apply_operations *ops,
1043                              wimlib_progress_func_t progress_func)
1044 {
1045         uint64_t bytes_per_progress = args->progress.extract.total_bytes / 100;
1046         uint64_t next_progress = bytes_per_progress;
1047         struct wim_lookup_table_entry *lte;
1048         struct wim_inode *inode;
1049         struct wim_dentry *dentry;
1050         int ret;
1051
1052         /* This complicated loop is essentially looping through the dentries,
1053          * although dentries may be visited more than once (if a dentry contains
1054          * two different nonempty streams) or not at all (if a dentry contains
1055          * no non-empty streams).
1056          *
1057          * The outer loop is over the distinct streams to be extracted so that
1058          * sequential reading of the WIM can be implemented. */
1059
1060         /* For each distinct stream to be extracted */
1061         list_for_each_entry(lte, stream_list, staging_list) {
1062                 /* For each inode that contains the stream */
1063                 list_for_each_entry(inode, &lte->inode_list, i_lte_inode_list) {
1064                         /* For each dentry that points to the inode */
1065                         inode_for_each_dentry(dentry, inode) {
1066                                 /* Extract the dentry if it was not already
1067                                  * extracted */
1068                                 ret = maybe_apply_dentry(dentry, args);
1069                                 if (ret != 0)
1070                                         return ret;
1071                                 if (progress_func &&
1072                                     args->progress.extract.completed_bytes >= next_progress)
1073                                 {
1074                                         progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS,
1075                                                       &args->progress);
1076                                         if (args->progress.extract.completed_bytes >=
1077                                             args->progress.extract.total_bytes)
1078                                         {
1079                                                 next_progress = ~0ULL;
1080                                         } else {
1081                                                 next_progress =
1082                                                         min (args->progress.extract.completed_bytes +
1083                                                              bytes_per_progress,
1084                                                              args->progress.extract.total_bytes);
1085                                         }
1086                                 }
1087                         }
1088                 }
1089         }
1090         return 0;
1091 }
1092
1093 /* Extracts the image @image from the WIM @w to the directory or NTFS volume
1094  * @target. */
1095 static int extract_single_image(WIMStruct *w, int image,
1096                                 const char *target, int extract_flags,
1097                                 wimlib_progress_func_t progress_func)
1098 {
1099         int ret;
1100         struct list_head stream_list;
1101         struct hlist_head *inode_list;
1102
1103         struct apply_args args;
1104         const struct apply_operations *ops;
1105
1106         args.w                    = w;
1107         args.target               = target;
1108         args.extract_flags        = extract_flags;
1109         args.num_lutimes_warnings = 0;
1110         args.stream_list          = &stream_list;
1111         args.progress_func        = progress_func;
1112
1113         if (progress_func) {
1114                 args.progress.extract.wimfile_name = w->filename;
1115                 args.progress.extract.image = image;
1116                 args.progress.extract.extract_flags = (extract_flags &
1117                                                        WIMLIB_EXTRACT_MASK_PUBLIC);
1118                 args.progress.extract.image_name = wimlib_get_image_name(w, image);
1119                 args.progress.extract.target = target;
1120         }
1121
1122 #ifdef WITH_NTFS_3G
1123         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1124                 args.vol = ntfs_mount(target, 0);
1125                 if (!args.vol) {
1126                         ERROR_WITH_ERRNO("Failed to mount NTFS volume `%s'", target);
1127                         return WIMLIB_ERR_NTFS_3G;
1128                 }
1129                 ops = &ntfs_apply_operations;
1130         } else
1131 #endif
1132                 ops = &normal_apply_operations;
1133
1134         ret = select_wim_image(w, image);
1135         if (ret != 0)
1136                 goto out;
1137
1138         inode_list = &w->image_metadata[image - 1].inode_list;
1139
1140         /* Build a list of the streams that need to be extracted */
1141         find_streams_for_extraction(inode_list, &stream_list,
1142                                     w->lookup_table, extract_flags);
1143
1144         /* Calculate the number of bytes of data that will be extracted */
1145         calculate_bytes_to_extract(&stream_list, extract_flags,
1146                                    &args.progress);
1147
1148         if (progress_func) {
1149                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN,
1150                               &args.progress);
1151         }
1152
1153         /* If a sequential extraction was specified, sort the streams to be
1154          * extracted by their position in the WIM file, so that the WIM file can
1155          * be read sequentially. */
1156         if (extract_flags & WIMLIB_EXTRACT_FLAG_SEQUENTIAL) {
1157                 ret = sort_stream_list_by_wim_position(&stream_list);
1158                 if (ret != 0) {
1159                         WARNING("Falling back to non-sequential extraction");
1160                         extract_flags &= ~WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
1161                 }
1162         }
1163
1164         if (progress_func) {
1165                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN,
1166                               &args.progress);
1167         }
1168
1169         /* Make the directory structure and extract empty files */
1170         args.extract_flags |= WIMLIB_EXTRACT_FLAG_NO_STREAMS;
1171         args.apply_dentry = ops->apply_dentry;
1172         ret = for_dentry_in_tree(wim_root_dentry(w), maybe_apply_dentry, &args);
1173         args.extract_flags &= ~WIMLIB_EXTRACT_FLAG_NO_STREAMS;
1174         if (ret != 0)
1175                 goto out;
1176
1177         if (progress_func) {
1178                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_END,
1179                               &args.progress);
1180         }
1181
1182         /* Extract non-empty files */
1183         ret = apply_stream_list(&stream_list, &args, ops, progress_func);
1184         if (ret != 0)
1185                 goto out;
1186
1187         if (progress_func) {
1188                 progress_func(WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS,
1189                               &args.progress);
1190         }
1191
1192         /* Apply timestamps */
1193         ret = for_dentry_in_tree_depth(wim_root_dentry(w),
1194                                        ops->apply_dentry_timestamps, &args);
1195         if (ret != 0)
1196                 goto out;
1197
1198         if (progress_func) {
1199                 progress_func(WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END,
1200                               &args.progress);
1201         }
1202 out:
1203 #ifdef WITH_NTFS_3G
1204         /* Unmount the NTFS volume */
1205         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1206                 if (ntfs_umount(args.vol, FALSE) != 0) {
1207                         ERROR_WITH_ERRNO("Failed to unmount NTFS volume `%s'", args.target);
1208                         if (ret == 0)
1209                                 ret = WIMLIB_ERR_NTFS_3G;
1210                 }
1211         }
1212 #endif
1213         return ret;
1214 }
1215
1216
1217 /* Extracts all images from the WIM to the directory @target, with the images
1218  * placed in subdirectories named by their image names. */
1219 static int extract_all_images(WIMStruct *w, const char *target,
1220                               int extract_flags,
1221                               wimlib_progress_func_t progress_func)
1222 {
1223         size_t image_name_max_len = max(xml_get_max_image_name_len(w), 20);
1224         size_t output_path_len = strlen(target);
1225         char buf[output_path_len + 1 + image_name_max_len + 1];
1226         int ret;
1227         int image;
1228         const char *image_name;
1229
1230         ret = extract_directory(NULL, target, true);
1231         if (ret != 0)
1232                 return ret;
1233
1234         memcpy(buf, target, output_path_len);
1235         buf[output_path_len] = '/';
1236         for (image = 1; image <= w->hdr.image_count; image++) {
1237                 image_name = wimlib_get_image_name(w, image);
1238                 if (image_name && *image_name) {
1239                         strcpy(buf + output_path_len + 1, image_name);
1240                 } else {
1241                         /* Image name is empty. Use image number instead */
1242                         sprintf(buf + output_path_len + 1, "%d", image);
1243                 }
1244                 ret = extract_single_image(w, image, buf, extract_flags,
1245                                            progress_func);
1246                 if (ret != 0)
1247                         return ret;
1248         }
1249         return 0;
1250 }
1251
1252 /* Extracts a single image or all images from a WIM file to a directory or NTFS
1253  * volume. */
1254 WIMLIBAPI int wimlib_extract_image(WIMStruct *w,
1255                                    int image,
1256                                    const char *target,
1257                                    int extract_flags,
1258                                    WIMStruct **additional_swms,
1259                                    unsigned num_additional_swms,
1260                                    wimlib_progress_func_t progress_func)
1261 {
1262         struct wim_lookup_table *joined_tab, *w_tab_save;
1263         int ret;
1264
1265         if (!target)
1266                 return WIMLIB_ERR_INVALID_PARAM;
1267
1268         extract_flags &= WIMLIB_EXTRACT_MASK_PUBLIC;
1269
1270         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
1271                         == (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
1272                 return WIMLIB_ERR_INVALID_PARAM;
1273
1274 #if defined(__CYGWIN__) || defined(__WIN32__)
1275         if (extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
1276                 ERROR("Extracting UNIX data is not supported on Windows");
1277                 return WIMLIB_ERR_INVALID_PARAM;
1278         }
1279         if (extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK)) {
1280                 ERROR("Linked extraction modes are not supported on Windows");
1281                 return WIMLIB_ERR_INVALID_PARAM;
1282         }
1283 #endif
1284
1285         if (extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1286 #ifdef WITH_NTFS_3G
1287                 if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))) {
1288                         ERROR("Cannot specify symlink or hardlink flags when applying\n"
1289                               "        directly to a NTFS volume");
1290                         return WIMLIB_ERR_INVALID_PARAM;
1291                 }
1292                 if (image == WIMLIB_ALL_IMAGES) {
1293                         ERROR("Can only apply a single image when applying "
1294                               "directly to a NTFS volume");
1295                         return WIMLIB_ERR_INVALID_PARAM;
1296                 }
1297                 if (extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
1298                         ERROR("Cannot restore UNIX-specific data in the NTFS extraction mode");
1299                         return WIMLIB_ERR_INVALID_PARAM;
1300                 }
1301 #else
1302                 ERROR("wimlib was compiled without support for NTFS-3g, so");
1303                 ERROR("we cannot apply a WIM image directly to a NTFS volume");
1304                 return WIMLIB_ERR_UNSUPPORTED;
1305 #endif
1306         }
1307
1308         ret = verify_swm_set(w, additional_swms, num_additional_swms);
1309         if (ret != 0)
1310                 return ret;
1311
1312         if (num_additional_swms) {
1313                 ret = new_joined_lookup_table(w, additional_swms,
1314                                               num_additional_swms, &joined_tab);
1315                 if (ret != 0)
1316                         return ret;
1317                 w_tab_save = w->lookup_table;
1318                 w->lookup_table = joined_tab;
1319         }
1320
1321 #if defined(__CYGWIN__) || defined(__WIN32__)
1322         win32_acquire_privilege(SE_RESTORE_NAME);
1323         win32_acquire_privilege(SE_SECURITY_NAME);
1324         win32_acquire_privilege(SE_TAKE_OWNERSHIP_NAME);
1325 #endif
1326         if (image == WIMLIB_ALL_IMAGES) {
1327                 extract_flags |= WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
1328                 ret = extract_all_images(w, target, extract_flags,
1329                                          progress_func);
1330         } else {
1331                 extract_flags &= ~WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
1332                 ret = extract_single_image(w, image, target, extract_flags,
1333                                            progress_func);
1334         }
1335 #if defined(__CYGWIN__) || defined(__WIN32__)
1336         win32_release_privilege(SE_RESTORE_NAME);
1337         win32_release_privilege(SE_SECURITY_NAME);
1338         win32_release_privilege(SE_TAKE_OWNERSHIP_NAME);
1339 #endif
1340
1341         if (extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
1342                              WIMLIB_EXTRACT_FLAG_HARDLINK))
1343         {
1344                 for_lookup_table_entry(w->lookup_table,
1345                                        lte_free_extracted_file,
1346                                        NULL);
1347         }
1348
1349         if (num_additional_swms) {
1350                 free_lookup_table(w->lookup_table);
1351                 w->lookup_table = w_tab_save;
1352         }
1353         return ret;
1354 }