Win32: Fix reparse point fixup bugs
[wimlib] / src / win32_apply.c
1 /*
2  * win32_apply.c - Windows-specific code for applying files from a WIM image.
3  */
4
5 /*
6  * Copyright (C) 2013 Eric Biggers
7  *
8  * This file is part of wimlib, a library for working with WIM files.
9  *
10  * wimlib is free software; you can redistribute it and/or modify it under the
11  * terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option)
13  * any later version.
14  *
15  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17  * A PARTICULAR PURPOSE. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with wimlib; if not, see http://www.gnu.org/licenses/.
22  */
23
24 #ifdef __WIN32__
25
26 #ifdef HAVE_CONFIG_H
27 #  include "config.h"
28 #endif
29
30 #include <aclapi.h> /* for SetSecurityInfo() */
31
32 #include "wimlib/win32_common.h"
33
34 #include "wimlib/apply.h"
35 #include "wimlib/dentry.h"
36 #include "wimlib/endianness.h"
37 #include "wimlib/error.h"
38 #include "wimlib/lookup_table.h"
39 #include "wimlib/metadata.h"
40 #include "wimlib/reparse.h"
41 #include "wimlib/security.h"
42
43 #define MAX_CREATE_HARD_LINK_WARNINGS 5
44 #define MAX_CREATE_SOFT_LINK_WARNINGS 5
45
46 #define MAX_SET_SD_ACCESS_DENIED_WARNINGS 1
47 #define MAX_SET_SACL_PRIV_NOTHELD_WARNINGS 1
48
49 static const wchar_t *apply_access_denied_msg =
50 L"If you are not running this program as the administrator, you may\n"
51  "          need to do so, so that all data and metadata can be extracted\n"
52  "          exactly as the origignal copy.  However, if you do not care that\n"
53  "          the security descriptors are extracted correctly, you could run\n"
54  "          `wimlib-imagex apply' with the --no-acls flag instead.\n"
55  ;
56
57
58 static int
59 win32_extract_try_rpfix(u8 *rpbuf,
60                         u16 *rpbuflen_p,
61                         const wchar_t *extract_root_realpath,
62                         unsigned extract_root_realpath_nchars)
63 {
64         struct reparse_data rpdata;
65         wchar_t *target;
66         size_t target_nchars;
67         size_t stripped_nchars;
68         wchar_t *stripped_target;
69         wchar_t stripped_target_nchars;
70         int ret;
71
72         utf16lechar *new_target;
73         utf16lechar *new_print_name;
74         size_t new_target_nchars;
75         size_t new_print_name_nchars;
76         utf16lechar *p;
77
78         ret = parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata);
79         if (ret)
80                 return ret;
81
82         if (extract_root_realpath[0] == L'\0' ||
83             extract_root_realpath[1] != L':' ||
84             extract_root_realpath[2] != L'\\')
85         {
86                 ERROR("Can't understand full path format \"%ls\".  "
87                       "Try turning reparse point fixups off...",
88                       extract_root_realpath);
89                 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
90         }
91
92         ret = parse_substitute_name(rpdata.substitute_name,
93                                     rpdata.substitute_name_nbytes,
94                                     rpdata.rptag);
95         if (ret < 0)
96                 return 0;
97         stripped_nchars = ret;
98         target = rpdata.substitute_name;
99         target_nchars = rpdata.substitute_name_nbytes / sizeof(utf16lechar);
100         stripped_target = target + 6;
101         stripped_target_nchars = target_nchars - stripped_nchars;
102
103         new_target = alloca((6 + extract_root_realpath_nchars +
104                              stripped_target_nchars) * sizeof(utf16lechar));
105
106         p = new_target;
107         if (stripped_nchars == 6) {
108                 /* Include \??\ prefix if it was present before */
109                 wmemcpy(p, L"\\??\\", 4);
110                 p += 4;
111         }
112
113         /* Print name excludes the \??\ if present. */
114         new_print_name = p;
115         if (stripped_nchars != 0) {
116                 /* Get drive letter from real path to extract root, if a drive
117                  * letter was present before. */
118                 *p++ = extract_root_realpath[0];
119                 *p++ = extract_root_realpath[1];
120         }
121         /* Copy the rest of the extract root */
122         p = wmempcpy(p, extract_root_realpath + 2, extract_root_realpath_nchars - 2);
123
124         /* Append the stripped target */
125         p = wmempcpy(p, stripped_target, stripped_target_nchars);
126         new_target_nchars = p - new_target;
127         new_print_name_nchars = p - new_print_name;
128
129         if (new_target_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE ||
130             new_print_name_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE)
131         {
132                 ERROR("Path names too long to do reparse point fixup!");
133                 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
134         }
135         rpdata.substitute_name = new_target;
136         rpdata.substitute_name_nbytes = new_target_nchars * sizeof(utf16lechar);
137         rpdata.print_name = new_print_name;
138         rpdata.print_name_nbytes = new_print_name_nchars * sizeof(utf16lechar);
139         return make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
140 }
141
142 /* Wrapper around the FSCTL_SET_REPARSE_POINT ioctl to set the reparse data on
143  * an extracted reparse point. */
144 static int
145 win32_set_reparse_data(HANDLE h,
146                        const struct wim_inode *inode,
147                        const struct wim_lookup_table_entry *lte,
148                        const wchar_t *path,
149                        struct apply_args *args)
150 {
151         int ret;
152         u8 rpbuf[REPARSE_POINT_MAX_SIZE] _aligned_attribute(8);
153         DWORD bytesReturned;
154         u16 rpbuflen;
155
156         DEBUG("Setting reparse data on \"%ls\"", path);
157
158         ret = wim_inode_get_reparse_data(inode, rpbuf, &rpbuflen);
159         if (ret)
160                 return ret;
161
162         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX &&
163             (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
164              inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT) &&
165             !inode->i_not_rpfixed)
166         {
167                 ret = win32_extract_try_rpfix(rpbuf,
168                                               &rpbuflen,
169                                               args->target_realpath,
170                                               args->target_realpath_len);
171                 if (ret)
172                         return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
173         }
174
175         /* Set the reparse data on the open file using the
176          * FSCTL_SET_REPARSE_POINT ioctl.
177          *
178          * There are contradictions in Microsoft's documentation for this:
179          *
180          * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
181          * lpOverlapped is ignored."
182          *
183          * --- So setting lpOverlapped to NULL is okay since it's ignored.
184          *
185          * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
186          * operation returns no output data and lpOutBuffer is NULL,
187          * DeviceIoControl makes use of lpBytesReturned. After such an
188          * operation, the value of lpBytesReturned is meaningless."
189          *
190          * --- So lpOverlapped not really ignored, as it affects another
191          *  parameter.  This is the actual behavior: lpBytesReturned must be
192          *  specified, even though lpBytesReturned is documented as:
193          *
194          *  "Not used with this operation; set to NULL."
195          */
196         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, rpbuf,
197                              rpbuflen,
198                              NULL, 0,
199                              &bytesReturned /* lpBytesReturned */,
200                              NULL /* lpOverlapped */))
201         {
202                 DWORD err = GetLastError();
203                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
204                 {
205                         args->num_soft_links_failed++;
206                         if (args->num_soft_links_failed <= MAX_CREATE_SOFT_LINK_WARNINGS) {
207                                 WARNING("Can't set reparse data on \"%ls\": Access denied!\n"
208                                         "          You may be trying to extract a symbolic "
209                                         "link without the\n"
210                                         "          SeCreateSymbolicLink privilege, which by "
211                                         "default non-Administrator\n"
212                                         "          accounts do not have.", path);
213                         }
214                         if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
215                                 WARNING("Suppressing further warnings regarding failure to extract\n"
216                                         "          reparse points due to insufficient privileges...");
217                         }
218                 } else {
219                         ERROR("Failed to set reparse data on \"%ls\"", path);
220                         win32_error(err);
221                         if (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
222                             inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT)
223                                 return WIMLIB_ERR_LINK;
224                         else
225                                 return WIMLIB_ERR_WRITE;
226                 }
227         }
228         return 0;
229 }
230
231 /* Wrapper around the FSCTL_SET_COMPRESSION ioctl to change the
232  * FILE_ATTRIBUTE_COMPRESSED flag of a file or directory. */
233 static int
234 win32_set_compression_state(HANDLE hFile, USHORT format, const wchar_t *path)
235 {
236         DWORD bytesReturned;
237         if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
238                              &format, sizeof(USHORT),
239                              NULL, 0,
240                              &bytesReturned, NULL))
241         {
242                 /* Could be a warning only, but we only call this if the volume
243                  * supports compression.  So I'm calling this an error. */
244                 DWORD err = GetLastError();
245                 ERROR("Failed to set compression flag on \"%ls\"", path);
246                 win32_error(err);
247                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
248                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
249                 else
250                         return WIMLIB_ERR_WRITE;
251         }
252         return 0;
253 }
254
255 /* Wrapper around FSCTL_SET_SPARSE ioctl to set a file as sparse. */
256 static int
257 win32_set_sparse(HANDLE hFile, const wchar_t *path)
258 {
259         DWORD bytesReturned;
260         if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
261                              NULL, 0,
262                              NULL, 0,
263                              &bytesReturned, NULL))
264         {
265                 /* Could be a warning only, but we only call this if the volume
266                  * supports sparse files.  So I'm calling this an error. */
267                 DWORD err = GetLastError();
268                 WARNING("Failed to set sparse flag on \"%ls\"", path);
269                 win32_error(err);
270                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
271                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
272                 else
273                         return WIMLIB_ERR_WRITE;
274         }
275         return 0;
276 }
277
278 /*
279  * Sets the security descriptor on an extracted file.
280  */
281 static int
282 win32_set_security_data(const struct wim_inode *inode,
283                         HANDLE hFile,
284                         const wchar_t *path,
285                         struct apply_args *args)
286 {
287         PSECURITY_DESCRIPTOR descriptor;
288         unsigned long n;
289         DWORD err;
290         const struct wim_security_data *sd;
291
292         SECURITY_INFORMATION securityInformation = 0;
293
294         void *owner = NULL;
295         void *group = NULL;
296         ACL *dacl = NULL;
297         ACL *sacl = NULL;
298
299         BOOL owner_defaulted;
300         BOOL group_defaulted;
301         BOOL dacl_present;
302         BOOL dacl_defaulted;
303         BOOL sacl_present;
304         BOOL sacl_defaulted;
305
306         sd = wim_const_security_data(args->w);
307         descriptor = sd->descriptors[inode->i_security_id];
308
309         GetSecurityDescriptorOwner(descriptor, &owner, &owner_defaulted);
310         if (owner)
311                 securityInformation |= OWNER_SECURITY_INFORMATION;
312
313         GetSecurityDescriptorGroup(descriptor, &group, &group_defaulted);
314         if (group)
315                 securityInformation |= GROUP_SECURITY_INFORMATION;
316
317         GetSecurityDescriptorDacl(descriptor, &dacl_present,
318                                   &dacl, &dacl_defaulted);
319         if (dacl)
320                 securityInformation |= DACL_SECURITY_INFORMATION;
321
322         GetSecurityDescriptorSacl(descriptor, &sacl_present,
323                                   &sacl, &sacl_defaulted);
324         if (sacl)
325                 securityInformation |= SACL_SECURITY_INFORMATION;
326
327 again:
328         if (securityInformation == 0)
329                 return 0;
330         if (SetSecurityInfo(hFile, SE_FILE_OBJECT,
331                             securityInformation, owner, group, dacl, sacl))
332                 return 0;
333         err = GetLastError();
334         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
335                 goto fail;
336         switch (err) {
337         case ERROR_PRIVILEGE_NOT_HELD:
338                 if (securityInformation & SACL_SECURITY_INFORMATION) {
339                         n = args->num_set_sacl_priv_notheld++;
340                         securityInformation &= ~SACL_SECURITY_INFORMATION;
341                         sacl = NULL;
342                         if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
343                                 WARNING(
344 "We don't have enough privileges to set the full security\n"
345 "          descriptor on \"%ls\"!\n", path);
346                                 if (args->num_set_sd_access_denied +
347                                     args->num_set_sacl_priv_notheld == 1)
348                                 {
349                                         WARNING("%ls", apply_access_denied_msg);
350                                 }
351                                 WARNING("Re-trying with SACL omitted.\n", path);
352                         } else if (n == MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
353                                 WARNING(
354 "Suppressing further 'privileges not held' error messages when setting\n"
355 "          security descriptors.");
356                         }
357                         goto again;
358                 }
359                 /* Fall through */
360         case ERROR_INVALID_OWNER:
361         case ERROR_ACCESS_DENIED:
362                 n = args->num_set_sd_access_denied++;
363                 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
364                         WARNING("Failed to set security descriptor on \"%ls\": "
365                                 "Access denied!\n", path);
366                         if (args->num_set_sd_access_denied +
367                             args->num_set_sacl_priv_notheld == 1)
368                         {
369                                 WARNING("%ls", apply_access_denied_msg);
370                         }
371                 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
372                         WARNING(
373 "Suppressing further access denied error messages when setting\n"
374 "          security descriptors");
375                 }
376                 return 0;
377         default:
378 fail:
379                 ERROR("Failed to set security descriptor on \"%ls\"", path);
380                 win32_error(err);
381                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
382                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
383                 else
384                         return WIMLIB_ERR_WRITE;
385         }
386 }
387
388
389 static int
390 win32_extract_chunk(const void *buf, size_t len, void *arg)
391 {
392         HANDLE hStream = arg;
393
394         DWORD nbytes_written;
395         wimlib_assert(len <= 0xffffffff);
396
397         if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
398             nbytes_written != len)
399         {
400                 DWORD err = GetLastError();
401                 ERROR("WriteFile(): write error");
402                 win32_error(err);
403                 return WIMLIB_ERR_WRITE;
404         }
405         return 0;
406 }
407
408 static int
409 do_win32_extract_stream(HANDLE hStream, const struct wim_lookup_table_entry *lte)
410 {
411         return extract_wim_resource(lte, wim_resource_size(lte),
412                                     win32_extract_chunk, hStream);
413 }
414
415 struct win32_encrypted_extract_ctx {
416         const struct wim_lookup_table_entry *lte;
417         u64 offset;
418 };
419
420 static DWORD WINAPI
421 win32_encrypted_import_cb(unsigned char *data, void *_ctx,
422                           unsigned long *len_p)
423 {
424         struct win32_encrypted_extract_ctx *ctx = _ctx;
425         unsigned long len = *len_p;
426         const struct wim_lookup_table_entry *lte = ctx->lte;
427
428         len = min(len, wim_resource_size(lte) - ctx->offset);
429
430         if (read_partial_wim_resource_into_buf(lte, len, ctx->offset, data))
431                 return ERROR_READ_FAULT;
432
433         ctx->offset += len;
434         *len_p = len;
435         return ERROR_SUCCESS;
436 }
437
438 /* Create an encrypted file and extract the raw encrypted data to it.
439  *
440  * @path:  Path to encrypted file to create.
441  * @lte:   WIM lookup_table entry for the raw encrypted data.
442  *
443  * This is separate from do_win32_extract_stream() because the WIM is supposed
444  * to contain the *raw* encrypted data, which needs to be extracted ("imported")
445  * using the special APIs OpenEncryptedFileRawW(), WriteEncryptedFileRaw(), and
446  * CloseEncryptedFileRaw().
447  *
448  * Returns 0 on success; nonzero on failure.
449  */
450 static int
451 do_win32_extract_encrypted_stream(const wchar_t *path,
452                                   const struct wim_lookup_table_entry *lte)
453 {
454         void *file_ctx;
455         int ret;
456
457         DEBUG("Opening file \"%ls\" to extract raw encrypted data", path);
458
459         ret = OpenEncryptedFileRawW(path, CREATE_FOR_IMPORT, &file_ctx);
460         if (ret) {
461                 ERROR("Failed to open \"%ls\" to write raw encrypted data", path);
462                 win32_error(ret);
463                 return WIMLIB_ERR_OPEN;
464         }
465
466         if (lte) {
467                 struct win32_encrypted_extract_ctx ctx;
468
469                 ctx.lte = lte;
470                 ctx.offset = 0;
471                 ret = WriteEncryptedFileRaw(win32_encrypted_import_cb, &ctx, file_ctx);
472                 if (ret == ERROR_SUCCESS) {
473                         ret = 0;
474                 } else {
475                         ret = WIMLIB_ERR_WRITE;
476                         ERROR("Failed to extract encrypted file \"%ls\"", path);
477                 }
478         }
479         CloseEncryptedFileRaw(file_ctx);
480         return ret;
481 }
482
483 static bool
484 path_is_root_of_drive(const wchar_t *path)
485 {
486         if (!*path)
487                 return false;
488
489         if (*path != L'/' && *path != L'\\') {
490                 if (*(path + 1) == L':')
491                         path += 2;
492                 else
493                         return false;
494         }
495         while (*path == L'/' || *path == L'\\')
496                 path++;
497         return (*path == L'\0');
498 }
499
500 static inline DWORD
501 win32_mask_attributes(DWORD i_attributes)
502 {
503         return i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
504                                 FILE_ATTRIBUTE_COMPRESSED |
505                                 FILE_ATTRIBUTE_REPARSE_POINT |
506                                 FILE_ATTRIBUTE_DIRECTORY |
507                                 FILE_ATTRIBUTE_ENCRYPTED |
508                                 FILE_FLAG_DELETE_ON_CLOSE |
509                                 FILE_FLAG_NO_BUFFERING |
510                                 FILE_FLAG_OPEN_NO_RECALL |
511                                 FILE_FLAG_OVERLAPPED |
512                                 FILE_FLAG_RANDOM_ACCESS |
513                                 /*FILE_FLAG_SESSION_AWARE |*/
514                                 FILE_FLAG_SEQUENTIAL_SCAN |
515                                 FILE_FLAG_WRITE_THROUGH);
516 }
517
518 static inline DWORD
519 win32_get_create_flags_and_attributes(DWORD i_attributes)
520 {
521         /*
522          * Some attributes cannot be set by passing them to CreateFile().  In
523          * particular:
524          *
525          * FILE_ATTRIBUTE_DIRECTORY:
526          *   CreateDirectory() must be called instead of CreateFile().
527          *
528          * FILE_ATTRIBUTE_SPARSE_FILE:
529          *   Needs an ioctl.
530          *   See: win32_set_sparse().
531          *
532          * FILE_ATTRIBUTE_COMPRESSED:
533          *   Not clear from the documentation, but apparently this needs an
534          *   ioctl as well.
535          *   See: win32_set_compressed().
536          *
537          * FILE_ATTRIBUTE_REPARSE_POINT:
538          *   Needs an ioctl, with the reparse data specified.
539          *   See: win32_set_reparse_data().
540          *
541          * In addition, clear any file flags in the attributes that we don't
542          * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
543          * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
544          */
545         return win32_mask_attributes(i_attributes) |
546                 FILE_FLAG_OPEN_REPARSE_POINT |
547                 FILE_FLAG_BACKUP_SEMANTICS;
548 }
549
550 /* Set compression and/or sparse attributes on a stream, if supported by the
551  * volume. */
552 static int
553 win32_set_special_stream_attributes(HANDLE hFile, const struct wim_inode *inode,
554                                     struct wim_lookup_table_entry *unnamed_stream_lte,
555                                     const wchar_t *path, unsigned vol_flags)
556 {
557         int ret;
558
559         if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
560                 if (vol_flags & FILE_FILE_COMPRESSION) {
561                         ret = win32_set_compression_state(hFile,
562                                                           COMPRESSION_FORMAT_DEFAULT,
563                                                           path);
564                         if (ret)
565                                 return ret;
566                 } else {
567                         DEBUG("Cannot set compression attribute on \"%ls\": "
568                               "volume does not support transparent compression",
569                               path);
570                 }
571         }
572
573         if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
574                 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
575                         DEBUG("Setting sparse flag on \"%ls\"", path);
576                         ret = win32_set_sparse(hFile, path);
577                         if (ret)
578                                 return ret;
579                 } else {
580                         DEBUG("Cannot set sparse attribute on \"%ls\": "
581                               "volume does not support sparse files",
582                               path);
583                 }
584         }
585         return 0;
586 }
587
588 /* Pre-create directories; extract encrypted streams */
589 static int
590 win32_begin_extract_unnamed_stream(const struct wim_inode *inode,
591                                    const struct wim_lookup_table_entry *lte,
592                                    const wchar_t *path,
593                                    DWORD *creationDisposition_ret,
594                                    unsigned int vol_flags)
595 {
596         DWORD err;
597         int ret;
598
599         /* Directories must be created with CreateDirectoryW().  Then the call
600          * to CreateFileW() will merely open the directory that was already
601          * created rather than creating a new file. */
602         if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY &&
603             !path_is_root_of_drive(path)) {
604                 if (!CreateDirectoryW(path, NULL)) {
605                         err = GetLastError();
606                         if (err != ERROR_ALREADY_EXISTS) {
607                                 ERROR("Failed to create directory \"%ls\"",
608                                       path);
609                                 win32_error(err);
610                                 return WIMLIB_ERR_MKDIR;
611                         }
612                 }
613                 DEBUG("Created directory \"%ls\"", path);
614                 *creationDisposition_ret = OPEN_EXISTING;
615         }
616         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED &&
617             vol_flags & FILE_SUPPORTS_ENCRYPTION)
618         {
619                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
620                         unsigned remaining_sharing_violations = 100;
621                         while (!EncryptFile(path)) {
622                                 if (remaining_sharing_violations &&
623                                     err == ERROR_SHARING_VIOLATION)
624                                 {
625                                         WARNING("Couldn't encrypt directory \"%ls\" "
626                                                 "due to sharing violation; re-trying "
627                                                 "after 100 ms", path);
628                                         Sleep(100);
629                                         remaining_sharing_violations--;
630                                 } else {
631                                         err = GetLastError();
632                                         ERROR("Failed to encrypt directory \"%ls\"",
633                                               path);
634                                         win32_error(err);
635                                         return WIMLIB_ERR_WRITE;
636                                 }
637                         }
638                 } else {
639                         ret = do_win32_extract_encrypted_stream(path, lte);
640                         if (ret)
641                                 return ret;
642                         DEBUG("Extracted encrypted file \"%ls\"", path);
643                 }
644                 *creationDisposition_ret = OPEN_EXISTING;
645         }
646
647         /* Set file attributes if we created the file.  Otherwise, we haven't
648          * created the file set and we will set the attributes in the call to
649          * CreateFileW().
650          *
651          * The FAT filesystem does not let you change the attributes of the root
652          * directory, so treat that as a special case and do not set attributes.
653          * */
654         if (*creationDisposition_ret == OPEN_EXISTING &&
655             !path_is_root_of_drive(path))
656         {
657                 if (!SetFileAttributesW(path,
658                                         win32_mask_attributes(inode->i_attributes)))
659                 {
660                         err = GetLastError();
661                         ERROR("Failed to set attributes on \"%ls\"", path);
662                         win32_error(err);
663                         return WIMLIB_ERR_WRITE;
664                 }
665         }
666         return 0;
667 }
668
669 /* Set security descriptor and extract stream data or reparse data (skip the
670  * unnamed data stream of encrypted files, which was already extracted). */
671 static int
672 win32_finish_extract_stream(HANDLE h, const struct wim_dentry *dentry,
673                             const struct wim_lookup_table_entry *lte,
674                             const wchar_t *stream_path,
675                             const wchar_t *stream_name_utf16,
676                             struct apply_args *args)
677 {
678         int ret = 0;
679         const struct wim_inode *inode = dentry->d_inode;
680         if (stream_name_utf16 == NULL) {
681                 /* Unnamed stream. */
682
683                 /* Set security descriptor, unless the extract_flags indicate
684                  * not to or the volume does not supported it.  Note that this
685                  * is only done when the unnamed stream is being extracted, as
686                  * security descriptors are per-file and not per-stream. */
687                 if (inode->i_security_id >= 0 &&
688                     !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
689                     && (args->vol_flags & FILE_PERSISTENT_ACLS))
690                 {
691                         ret = win32_set_security_data(inode, h, stream_path, args);
692                         if (ret)
693                                 return ret;
694                 }
695
696                 /* Handle reparse points.  The data for them needs to be set
697                  * using a special ioctl.  Note that the reparse point may have
698                  * been created using CreateFileW() in the case of
699                  * non-directories or CreateDirectoryW() in the case of
700                  * directories; but the ioctl works either way.  Also, it is
701                  * only this step that actually sets the
702                  * FILE_ATTRIBUTE_REPARSE_POINT, as it is not valid to set it
703                  * using SetFileAttributesW() or CreateFileW().
704                  *
705                  * If the volume does not support reparse points we simply
706                  * ignore the reparse data.  (N.B. the code currently doesn't
707                  * actually reach this case because reparse points are skipped
708                  * entirely on such volumes.) */
709                 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
710                         if (args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
711                                 ret = win32_set_reparse_data(h, inode,
712                                                              lte, stream_path,
713                                                              args);
714                                 if (ret)
715                                         return ret;
716                         } else {
717                                 DEBUG("Cannot set reparse data on \"%ls\": volume "
718                                       "does not support reparse points", stream_path);
719                         }
720                 } else if (lte != NULL &&
721                            !(args->vol_flags & FILE_SUPPORTS_ENCRYPTION &&
722                              inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
723                 {
724                         /* Extract the data of the unnamed stream, unless the
725                          * lookup table entry is NULL (indicating an empty
726                          * stream for which no data needs to be extracted), or
727                          * the stream is encrypted and therefore was already
728                          * extracted as a special case. */
729                         ret = do_win32_extract_stream(h, lte);
730                         if (ret)
731                                 return ret;
732                 }
733
734                 if (dentry_has_short_name(dentry))
735                         SetFileShortNameW(h, dentry->short_name);
736                 else if (running_on_windows_7_or_later())
737                         SetFileShortNameW(h, L"");
738         } else {
739                 /* Extract the data for a named data stream. */
740                 if (lte != NULL) {
741                         DEBUG("Extracting named data stream \"%ls\" (len = %"PRIu64")",
742                               stream_path, wim_resource_size(lte));
743                         ret = do_win32_extract_stream(h, lte);
744                 }
745         }
746         return ret;
747 }
748
749 static int
750 win32_decrypt_file(HANDLE open_handle, const wchar_t *path)
751 {
752         DWORD err;
753         /* We cannot call DecryptFileW() while there is an open handle to the
754          * file.  So close it first. */
755         if (!CloseHandle(open_handle)) {
756                 err = GetLastError();
757                 ERROR("Failed to close handle for \"%ls\"", path);
758                 win32_error(err);
759                 return WIMLIB_ERR_WRITE;
760         }
761         if (!DecryptFileW(path, 0 /* reserved parameter; set to 0 */)) {
762                 err = GetLastError();
763                 ERROR("Failed to decrypt file \"%ls\"", path);
764                 win32_error(err);
765                 return WIMLIB_ERR_WRITE;
766         }
767         return 0;
768 }
769
770 /*
771  * Create and extract a stream to a file, or create a directory, using the
772  * Windows API.
773  *
774  * This handles reparse points, directories, alternate data streams, encrypted
775  * files, compressed files, etc.
776  *
777  * @dentry: WIM dentry for the file or directory being extracted.
778  *
779  * @path:  Path to extract the file to.
780  *
781  * @stream_name_utf16:
782  *         Name of the stream, or NULL if the stream is unnamed.  This will
783  *         be called with a NULL stream_name_utf16 before any non-NULL
784  *         stream_name_utf16's.
785  *
786  * @lte:   WIM lookup table entry for the stream.  May be NULL to indicate
787  *         a stream of length 0.
788  *
789  * @args:  Additional apply context, including flags indicating supported
790  *         volume features.
791  *
792  * Returns 0 on success; nonzero on failure.
793  */
794 static int
795 win32_extract_stream(const struct wim_dentry *dentry,
796                      const wchar_t *path,
797                      const wchar_t *stream_name_utf16,
798                      struct wim_lookup_table_entry *lte,
799                      struct apply_args *args)
800 {
801         wchar_t *stream_path;
802         HANDLE h;
803         int ret;
804         DWORD err;
805         DWORD creationDisposition = CREATE_ALWAYS;
806         DWORD requestedAccess;
807         BY_HANDLE_FILE_INFORMATION file_info;
808         unsigned remaining_sharing_violations = 1000;
809         const struct wim_inode *inode = dentry->d_inode;
810
811         if (stream_name_utf16) {
812                 /* Named stream.  Create a buffer that contains the UTF-16LE
813                  * string [./]path:stream_name_utf16.  This is needed to
814                  * create and open the stream using CreateFileW().  I'm not
815                  * aware of any other APIs to do this.  Note: the '$DATA' suffix
816                  * seems to be unneeded.  Additional note: a "./" prefix needs
817                  * to be added when the path is not absolute to avoid ambiguity
818                  * with drive letters. */
819                 size_t stream_path_nchars;
820                 size_t path_nchars;
821                 size_t stream_name_nchars;
822                 const wchar_t *prefix;
823
824                 path_nchars = wcslen(path);
825                 stream_name_nchars = wcslen(stream_name_utf16);
826                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
827                 if (path[0] != cpu_to_le16(L'\0') &&
828                     path[0] != cpu_to_le16(L'/') &&
829                     path[0] != cpu_to_le16(L'\\') &&
830                     path[1] != cpu_to_le16(L':'))
831                 {
832                         prefix = L"./";
833                         stream_path_nchars += 2;
834                 } else {
835                         prefix = L"";
836                 }
837                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
838                 swprintf(stream_path, L"%ls%ls:%ls",
839                          prefix, path, stream_name_utf16);
840         } else {
841                 /* Unnamed stream; its path is just the path to the file itself.
842                  * */
843                 stream_path = (wchar_t*)path;
844
845                 ret = win32_begin_extract_unnamed_stream(inode, lte, path,
846                                                          &creationDisposition,
847                                                          args->vol_flags);
848                 if (ret)
849                         goto fail;
850         }
851
852         DEBUG("Opening \"%ls\"", stream_path);
853         /* DELETE access is needed for SetFileShortNameW(), for some reason. */
854         requestedAccess = GENERIC_READ | GENERIC_WRITE | DELETE |
855                           ACCESS_SYSTEM_SECURITY;
856 try_open_again:
857         /* Open the stream to be extracted.  Depending on what we have set
858          * creationDisposition to, we may be creating this for the first time,
859          * or we may be opening on existing stream we already created using
860          * CreateDirectoryW() or OpenEncryptedFileRawW(). */
861         h = CreateFileW(stream_path,
862                         requestedAccess,
863                         FILE_SHARE_READ,
864                         NULL,
865                         creationDisposition,
866                         win32_get_create_flags_and_attributes(inode->i_attributes),
867                         NULL);
868         if (h == INVALID_HANDLE_VALUE) {
869                 err = GetLastError();
870                 if (err == ERROR_ACCESS_DENIED &&
871                     path_is_root_of_drive(stream_path))
872                 {
873                         ret = 0;
874                         goto out;
875                 }
876                 if ((err == ERROR_PRIVILEGE_NOT_HELD ||
877                      err == ERROR_ACCESS_DENIED) &&
878                     (requestedAccess & ACCESS_SYSTEM_SECURITY))
879                 {
880                         /* Try opening the file again without privilege to
881                          * modify SACL. */
882                         requestedAccess &= ~ACCESS_SYSTEM_SECURITY;
883                         goto try_open_again;
884                 }
885                 if (err == ERROR_SHARING_VIOLATION) {
886                         if (remaining_sharing_violations) {
887                                 --remaining_sharing_violations;
888                                 /* This can happen when restoring encrypted directories
889                                  * for some reason.  Probably a bug in EncryptFile(). */
890                                 WARNING("Couldn't open \"%ls\" due to sharing violation; "
891                                         "re-trying after 100ms", stream_path);
892                                 Sleep(100);
893                                 goto try_open_again;
894                         } else {
895                                 ERROR("Too many sharing violations; giving up...");
896                         }
897                 } else {
898                         if (creationDisposition == OPEN_EXISTING)
899                                 ERROR("Failed to open \"%ls\"", stream_path);
900                         else
901                                 ERROR("Failed to create \"%ls\"", stream_path);
902                         win32_error(err);
903                 }
904                 ret = WIMLIB_ERR_OPEN;
905                 goto fail;
906         }
907
908         /* Check the attributes of the file we just opened, and remove
909          * encryption or compression if either was set by default but is not
910          * supposed to be set based on the WIM inode attributes. */
911         if (!GetFileInformationByHandle(h, &file_info)) {
912                 err = GetLastError();
913                 ERROR("Failed to get attributes of \"%ls\"", stream_path);
914                 win32_error(err);
915                 ret = WIMLIB_ERR_STAT;
916                 goto fail_close_handle;
917         }
918
919         /* Remove encryption? */
920         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED &&
921             !(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
922         {
923                 /* File defaulted to encrypted due to being in an encrypted
924                  * directory, but is not actually supposed to be encrypted.
925                  *
926                  * This is a workaround, because I'm not aware of any way to
927                  * directly (e.g. with CreateFileW()) create an unencrypted file
928                  * in a directory with FILE_ATTRIBUTE_ENCRYPTED set. */
929                 ret = win32_decrypt_file(h, stream_path);
930                 if (ret)
931                         goto fail; /* win32_decrypt_file() closed the handle. */
932                 creationDisposition = OPEN_EXISTING;
933                 goto try_open_again;
934         }
935
936         /* Remove compression? */
937         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED &&
938             !(inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED))
939         {
940                 /* Similar to the encrypted case, above, if the file defaulted
941                  * to compressed due to being in an compressed directory, but is
942                  * not actually supposed to be compressed, explicitly set the
943                  * compression format to COMPRESSION_FORMAT_NONE. */
944                 ret = win32_set_compression_state(h, COMPRESSION_FORMAT_NONE,
945                                                   stream_path);
946                 if (ret)
947                         goto fail_close_handle;
948         }
949
950         /* Set compression and/or sparse attributes if needed */
951         ret = win32_set_special_stream_attributes(h, inode, lte, path,
952                                                   args->vol_flags);
953
954         if (ret)
955                 goto fail_close_handle;
956
957         /* At this point we have at least created the needed stream with the
958          * appropriate attributes.  We have yet to set the appropriate security
959          * descriptor and actually extract the stream data (other than for
960          * extracted files, which were already extracted).
961          * win32_finish_extract_stream() handles these additional steps. */
962         ret = win32_finish_extract_stream(h, dentry, lte, stream_path,
963                                           stream_name_utf16, args);
964         if (ret)
965                 goto fail_close_handle;
966
967         /* Done extracting the stream.  Close the handle and return. */
968         DEBUG("Closing \"%ls\"", stream_path);
969         if (!CloseHandle(h)) {
970                 err = GetLastError();
971                 ERROR("Failed to close \"%ls\"", stream_path);
972                 win32_error(err);
973                 ret = WIMLIB_ERR_WRITE;
974                 goto fail;
975         }
976         ret = 0;
977         goto out;
978 fail_close_handle:
979         CloseHandle(h);
980 fail:
981         ERROR("Error extracting \"%ls\"", stream_path);
982 out:
983         return ret;
984 }
985
986 /*
987  * Creates a file, directory, or reparse point and extracts all streams to it
988  * (unnamed data stream and/or reparse point stream, plus any alternate data
989  * streams).  Handles sparse, compressed, and/or encrypted files.
990  *
991  * @dentry:     WIM dentry for this file or directory.
992  * @path:       UTF-16LE external path to extract the inode to.
993  * @args:       Additional extraction context.
994  *
995  * Returns 0 on success; nonzero on failure.
996  */
997 static int
998 win32_extract_streams(const struct wim_dentry *dentry,
999                       const wchar_t *path, struct apply_args *args)
1000 {
1001         struct wim_lookup_table_entry *unnamed_lte;
1002         int ret;
1003         const struct wim_inode *inode = dentry->d_inode;
1004
1005         /* First extract the unnamed stream. */
1006
1007         unnamed_lte = inode_unnamed_lte_resolved(inode);
1008         ret = win32_extract_stream(dentry, path, NULL, unnamed_lte, args);
1009         if (ret)
1010                 goto out;
1011
1012         /* Extract any named streams, if supported by the volume. */
1013
1014         if (!(args->vol_flags & FILE_NAMED_STREAMS))
1015                 goto out;
1016         for (u16 i = 0; i < inode->i_num_ads; i++) {
1017                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1018
1019                 /* Skip the unnamed stream if it's in the ADS entries (we
1020                  * already extracted it...) */
1021                 if (ads_entry->stream_name_nbytes == 0)
1022                         continue;
1023
1024                 /* Skip special UNIX data entries (see documentation for
1025                  * WIMLIB_ADD_FLAG_UNIX_DATA) */
1026                 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1027                     && !memcmp(ads_entry->stream_name,
1028                                WIMLIB_UNIX_DATA_TAG_UTF16LE,
1029                                WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1030                         continue;
1031
1032                 /* Extract the named stream */
1033                 ret = win32_extract_stream(dentry,
1034                                            path,
1035                                            ads_entry->stream_name,
1036                                            ads_entry->lte,
1037                                            args);
1038                 if (ret)
1039                         break;
1040         }
1041 out:
1042         return ret;
1043 }
1044
1045 static int
1046 dentry_clear_inode_visited(struct wim_dentry *dentry, void *_ignore)
1047 {
1048         dentry->d_inode->i_visited = 0;
1049         return 0;
1050 }
1051
1052 static int
1053 dentry_get_features(struct wim_dentry *dentry, void *_features_p)
1054 {
1055         DWORD features = 0;
1056         DWORD *features_p = _features_p;
1057         struct wim_inode *inode = dentry->d_inode;
1058
1059         if (inode->i_visited) {
1060                 features |= FILE_SUPPORTS_HARD_LINKS;
1061         } else {
1062                 inode->i_visited = 1;
1063                 if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE)
1064                         features |= FILE_SUPPORTS_SPARSE_FILES;
1065                 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1066                         features |= FILE_SUPPORTS_REPARSE_POINTS;
1067                 for (unsigned i = 0; i < inode->i_num_ads; i++)
1068                         if (inode->i_ads_entries[i].stream_name_nbytes)
1069                                 features |= FILE_NAMED_STREAMS;
1070                 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)
1071                         features |= FILE_SUPPORTS_ENCRYPTION;
1072                 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED)
1073                         features |= FILE_FILE_COMPRESSION;
1074                 if (inode->i_security_id != -1)
1075                         features |= FILE_PERSISTENT_ACLS;
1076         }
1077         *features_p |= features;
1078         return 0;
1079 }
1080
1081 /* If not done already, load the supported feature flags for the volume onto
1082  * which the image is being extracted, and warn the user about any missing
1083  * features that could be important. */
1084 static int
1085 win32_check_vol_flags(const wchar_t *output_path,
1086                       struct wim_dentry *root, struct apply_args *args)
1087 {
1088         DWORD dentry_features = 0;
1089         DWORD missing_features;
1090
1091         if (args->have_vol_flags)
1092                 return 0;
1093
1094         for_dentry_in_tree(root, dentry_clear_inode_visited, NULL);
1095         for_dentry_in_tree(root, dentry_get_features, &dentry_features);
1096
1097         win32_get_vol_flags(output_path, &args->vol_flags);
1098         args->have_vol_flags = true;
1099
1100         missing_features = dentry_features & ~args->vol_flags;
1101
1102         /* Warn the user about data that may not be extracted. */
1103         if (missing_features & FILE_SUPPORTS_SPARSE_FILES)
1104                 WARNING("Volume does not support sparse files!\n"
1105                         "          Sparse files will be extracted as non-sparse.");
1106         if (missing_features & FILE_SUPPORTS_REPARSE_POINTS)
1107                 WARNING("Volume does not support reparse points!\n"
1108                         "          Reparse point data will not be extracted.");
1109         if (missing_features & FILE_NAMED_STREAMS) {
1110                 WARNING("Volume does not support named data streams!\n"
1111                         "          Named data streams will not be extracted.");
1112         }
1113         if (missing_features & FILE_SUPPORTS_ENCRYPTION) {
1114                 WARNING("Volume does not support encryption!\n"
1115                         "          Encrypted files will be extracted as raw data.");
1116         }
1117         if (missing_features & FILE_FILE_COMPRESSION) {
1118                 WARNING("Volume does not support transparent compression!\n"
1119                         "          Compressed files will be extracted as non-compressed.");
1120         }
1121         if (missing_features & FILE_PERSISTENT_ACLS) {
1122                 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
1123                         ERROR("Strict ACLs requested, but the volume does not "
1124                               "support ACLs!");
1125                         return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
1126                 } else {
1127                         WARNING("Volume does not support persistent ACLS!\n"
1128                                 "          File permissions will not be extracted.");
1129                 }
1130         }
1131         if (running_on_windows_7_or_later() &&
1132             (missing_features & FILE_SUPPORTS_HARD_LINKS))
1133         {
1134                 WARNING("Volume does not support hard links!\n"
1135                         "          Hard links will be extracted as duplicate files.");
1136         }
1137         return 0;
1138 }
1139
1140 /*
1141  * Try extracting a hard link.
1142  *
1143  * @output_path:  Path to link to be extracted.
1144  *
1145  * @inode:        WIM inode that the link is to; inode->i_extracted_file
1146  *                the path to a name of the file that has already been
1147  *                extracted (we use this to create the hard link).
1148  *
1149  * @args:         Additional apply context, used here to keep track of
1150  *                the number of times creating a hard link failed due to
1151  *                ERROR_INVALID_FUNCTION.  This error should indicate that hard
1152  *                links are not supported by the volume, and we would like to
1153  *                warn the user a few times, but not too many times.
1154  *
1155  * Returns 0 if the hard link was successfully extracted.  Returns
1156  * WIMLIB_ERR_LINK (> 0) if an error occurred, other than hard links possibly
1157  * being unsupported by the volume.  Returns a negative value if creating the
1158  * hard link failed due to ERROR_INVALID_FUNCTION.
1159  */
1160 static int
1161 win32_try_hard_link(const wchar_t *output_path, const struct wim_inode *inode,
1162                     struct apply_args *args)
1163 {
1164         DWORD err;
1165
1166         /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
1167          * but it's only available on Windows 7 and later.
1168          *
1169          * Otherwise, CreateHardLinkW() will apparently return
1170          * ERROR_INVALID_FUNCTION if the volume does not support hard links. */
1171
1172         DEBUG("Creating hard link \"%ls => %ls\"",
1173               output_path, inode->i_extracted_file);
1174
1175         if (running_on_windows_7_or_later() &&
1176             !(args->vol_flags & FILE_SUPPORTS_HARD_LINKS))
1177                 goto hard_links_unsupported;
1178
1179         if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
1180                 return 0;
1181
1182         err = GetLastError();
1183         if (err != ERROR_INVALID_FUNCTION) {
1184                 ERROR("Can't create hard link \"%ls => %ls\"",
1185                       output_path, inode->i_extracted_file);
1186                 win32_error(err);
1187                 return WIMLIB_ERR_LINK;
1188         }
1189 hard_links_unsupported:
1190         args->num_hard_links_failed++;
1191         if (args->num_hard_links_failed <= MAX_CREATE_HARD_LINK_WARNINGS) {
1192                 if (running_on_windows_7_or_later())
1193                 {
1194                         WARNING("Extracting duplicate copy of \"%ls\" "
1195                                 "rather than hard link", output_path);
1196                 } else {
1197                         WARNING("Can't create hard link \"%ls\" => \"%ls\":\n"
1198                                 "          Volume does not support hard links!\n"
1199                                 "          Falling back to extracting a copy of the file.",
1200                                 output_path, inode->i_extracted_file);
1201                 }
1202         }
1203         if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS)
1204                 WARNING("Suppressing further hard linking warnings...");
1205         return -1;
1206 }
1207
1208 /* Extract a file, directory, reparse point, or hard link to an
1209  * already-extracted file using the Win32 API */
1210 int
1211 win32_do_apply_dentry(const wchar_t *output_path,
1212                       size_t output_path_num_chars,
1213                       struct wim_dentry *dentry,
1214                       struct apply_args *args)
1215 {
1216         int ret;
1217         struct wim_inode *inode = dentry->d_inode;
1218
1219         ret = win32_check_vol_flags(output_path, dentry, args);
1220         if (ret)
1221                 return ret;
1222         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1223                 /* Linked file, with another name already extracted.  Create a
1224                  * hard link. */
1225                 ret = win32_try_hard_link(output_path, inode, args);
1226                 if (ret >= 0)
1227                         return ret;
1228                 /* Negative return value from win32_try_hard_link() indicates
1229                  * that hard links are probably not supported by the volume.
1230                  * Fall back to extracting a copy of the file. */
1231         }
1232
1233         /* If this is a reparse point and the volume does not support reparse
1234          * points, just skip it completely. */
1235         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1236             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1237         {
1238                 WARNING("Not extracting reparse point \"%ls\"", output_path);
1239         } else {
1240                 /* Create the file, directory, or reparse point, and extract the
1241                  * data streams. */
1242                 ret = win32_extract_streams(dentry, output_path, args);
1243                 if (ret)
1244                         return ret;
1245         }
1246         if (inode->i_extracted_file == NULL) {
1247                 const struct wim_lookup_table_entry *lte;
1248
1249                 /* Tally bytes extracted, including all alternate data streams,
1250                  * unless we extracted a hard link (or, at least extracted a
1251                  * name that was supposed to be a hard link) */
1252                 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1253                         lte = inode_stream_lte_resolved(inode, i);
1254                         if (lte)
1255                                 args->progress.extract.completed_bytes +=
1256                                                         wim_resource_size(lte);
1257                 }
1258                 if (inode->i_nlink > 1) {
1259                         /* Save extracted path for a later call to
1260                          * CreateHardLinkW() if this inode has multiple links.
1261                          * */
1262                         inode->i_extracted_file = WSTRDUP(output_path);
1263                         if (!inode->i_extracted_file)
1264                                 return WIMLIB_ERR_NOMEM;
1265                 }
1266         }
1267         return 0;
1268 }
1269
1270 /* Set timestamps on an extracted file using the Win32 API */
1271 int
1272 win32_do_apply_dentry_timestamps(const wchar_t *path,
1273                                  size_t path_num_chars,
1274                                  struct wim_dentry *dentry,
1275                                  struct apply_args *args)
1276 {
1277         DWORD err;
1278         HANDLE h;
1279         const struct wim_inode *inode = dentry->d_inode;
1280
1281         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1282             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1283         {
1284                 /* Skip reparse points not extracted */
1285                 return 0;
1286         }
1287
1288         /* Windows doesn't let you change the timestamps of the root directory
1289          * (at least on FAT, which is dumb but expected since FAT doesn't store
1290          * any metadata about the root directory...) */
1291         if (path_is_root_of_drive(path))
1292                 return 0;
1293
1294         DEBUG("Opening \"%ls\" to set timestamps", path);
1295         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1296         if (h == INVALID_HANDLE_VALUE) {
1297                 err = GetLastError();
1298                 goto fail;
1299         }
1300
1301         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1302                                  .dwHighDateTime = inode->i_creation_time >> 32};
1303         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1304                                   .dwHighDateTime = inode->i_last_access_time >> 32};
1305         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1306                                   .dwHighDateTime = inode->i_last_write_time >> 32};
1307
1308         DEBUG("Calling SetFileTime() on \"%ls\"", path);
1309         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1310                 err = GetLastError();
1311                 CloseHandle(h);
1312                 goto fail;
1313         }
1314         DEBUG("Closing \"%ls\"", path);
1315         if (!CloseHandle(h)) {
1316                 err = GetLastError();
1317                 goto fail;
1318         }
1319         goto out;
1320 fail:
1321         /* Only warn if setting timestamps failed; still return 0. */
1322         WARNING("Can't set timestamps on \"%ls\"", path);
1323         win32_error(err);
1324 out:
1325         return 0;
1326 }
1327
1328 #endif /* __WIN32__ */