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