11104f24bc88404d2ba2b5cbc94b8a1b593fa140
[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 bool
483 path_is_root_of_drive(const wchar_t *path)
484 {
485         if (*path == L'\0')
486                 return false;
487
488         if (!wcsncmp(path, L"\\\\?\\", 4))
489                 path += 4;
490
491         if (*path != L'/' && *path != L'\\') {
492                 if (*(path + 1) == L':')
493                         path += 2;
494                 else
495                         return false;
496         }
497         while (*path == L'/' || *path == L'\\')
498                 path++;
499         return (*path == L'\0');
500 }
501
502 static inline DWORD
503 win32_mask_attributes(DWORD i_attributes)
504 {
505         return i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
506                                 FILE_ATTRIBUTE_COMPRESSED |
507                                 FILE_ATTRIBUTE_REPARSE_POINT |
508                                 FILE_ATTRIBUTE_DIRECTORY |
509                                 FILE_ATTRIBUTE_ENCRYPTED |
510                                 FILE_FLAG_DELETE_ON_CLOSE |
511                                 FILE_FLAG_NO_BUFFERING |
512                                 FILE_FLAG_OPEN_NO_RECALL |
513                                 FILE_FLAG_OVERLAPPED |
514                                 FILE_FLAG_RANDOM_ACCESS |
515                                 /*FILE_FLAG_SESSION_AWARE |*/
516                                 FILE_FLAG_SEQUENTIAL_SCAN |
517                                 FILE_FLAG_WRITE_THROUGH);
518 }
519
520 static inline DWORD
521 win32_get_create_flags_and_attributes(DWORD i_attributes)
522 {
523         /*
524          * Some attributes cannot be set by passing them to CreateFile().  In
525          * particular:
526          *
527          * FILE_ATTRIBUTE_DIRECTORY:
528          *   CreateDirectory() must be called instead of CreateFile().
529          *
530          * FILE_ATTRIBUTE_SPARSE_FILE:
531          *   Needs an ioctl.
532          *   See: win32_set_sparse().
533          *
534          * FILE_ATTRIBUTE_COMPRESSED:
535          *   Not clear from the documentation, but apparently this needs an
536          *   ioctl as well.
537          *   See: win32_set_compressed().
538          *
539          * FILE_ATTRIBUTE_REPARSE_POINT:
540          *   Needs an ioctl, with the reparse data specified.
541          *   See: win32_set_reparse_data().
542          *
543          * In addition, clear any file flags in the attributes that we don't
544          * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
545          * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
546          */
547         return win32_mask_attributes(i_attributes) |
548                 FILE_FLAG_OPEN_REPARSE_POINT |
549                 FILE_FLAG_BACKUP_SEMANTICS;
550 }
551
552 /* Set compression and/or sparse attributes on a stream, if supported by the
553  * volume. */
554 static int
555 win32_set_special_stream_attributes(HANDLE hFile, const struct wim_inode *inode,
556                                     struct wim_lookup_table_entry *unnamed_stream_lte,
557                                     const wchar_t *path, unsigned vol_flags)
558 {
559         int ret;
560
561         if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
562                 if (vol_flags & FILE_FILE_COMPRESSION) {
563                         ret = win32_set_compression_state(hFile,
564                                                           COMPRESSION_FORMAT_DEFAULT,
565                                                           path);
566                         if (ret)
567                                 return ret;
568                 } else {
569                         DEBUG("Cannot set compression attribute on \"%ls\": "
570                               "volume does not support transparent compression",
571                               path);
572                 }
573         }
574
575         if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
576                 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
577                         DEBUG("Setting sparse flag on \"%ls\"", path);
578                         ret = win32_set_sparse(hFile, path);
579                         if (ret)
580                                 return ret;
581                 } else {
582                         DEBUG("Cannot set sparse attribute on \"%ls\": "
583                               "volume does not support sparse files",
584                               path);
585                 }
586         }
587         return 0;
588 }
589
590 /* Pre-create directories; extract encrypted streams */
591 static int
592 win32_begin_extract_unnamed_stream(const struct wim_inode *inode,
593                                    const struct wim_lookup_table_entry *lte,
594                                    const wchar_t *path,
595                                    DWORD *creationDisposition_ret,
596                                    unsigned int vol_flags)
597 {
598         DWORD err;
599         int ret;
600
601         /* Directories must be created with CreateDirectoryW().  Then the call
602          * to CreateFileW() will merely open the directory that was already
603          * created rather than creating a new file. */
604         if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY &&
605             !path_is_root_of_drive(path)) {
606                 if (!CreateDirectoryW(path, NULL)) {
607                         err = GetLastError();
608                         if (err != ERROR_ALREADY_EXISTS) {
609                                 ERROR("Failed to create directory \"%ls\"",
610                                       path);
611                                 win32_error(err);
612                                 return WIMLIB_ERR_MKDIR;
613                         }
614                 }
615                 DEBUG("Created directory \"%ls\"", path);
616                 *creationDisposition_ret = OPEN_EXISTING;
617         }
618         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED &&
619             vol_flags & FILE_SUPPORTS_ENCRYPTION)
620         {
621                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
622                         unsigned remaining_sharing_violations = 100;
623                         while (!EncryptFile(path)) {
624                                 if (remaining_sharing_violations &&
625                                     err == ERROR_SHARING_VIOLATION)
626                                 {
627                                         WARNING("Couldn't encrypt directory \"%ls\" "
628                                                 "due to sharing violation; re-trying "
629                                                 "after 100 ms", path);
630                                         Sleep(100);
631                                         remaining_sharing_violations--;
632                                 } else {
633                                         err = GetLastError();
634                                         ERROR("Failed to encrypt directory \"%ls\"",
635                                               path);
636                                         win32_error(err);
637                                         return WIMLIB_ERR_WRITE;
638                                 }
639                         }
640                 } else {
641                         ret = do_win32_extract_encrypted_stream(path, lte);
642                         if (ret)
643                                 return ret;
644                         DEBUG("Extracted encrypted file \"%ls\"", path);
645                 }
646                 *creationDisposition_ret = OPEN_EXISTING;
647         }
648
649         /* Set file attributes if we created the file.  Otherwise, we haven't
650          * created the file set and we will set the attributes in the call to
651          * CreateFileW().
652          *
653          * The FAT filesystem does not let you change the attributes of the root
654          * directory, so treat that as a special case and do not set attributes.
655          * */
656         if (*creationDisposition_ret == OPEN_EXISTING &&
657             !path_is_root_of_drive(path))
658         {
659                 if (!SetFileAttributesW(path,
660                                         win32_mask_attributes(inode->i_attributes)))
661                 {
662                         err = GetLastError();
663                         ERROR("Failed to set attributes on \"%ls\"", path);
664                         win32_error(err);
665                         return WIMLIB_ERR_WRITE;
666                 }
667         }
668         return 0;
669 }
670
671 /* Set security descriptor and extract stream data or reparse data (skip the
672  * unnamed data stream of encrypted files, which was already extracted). */
673 static int
674 win32_finish_extract_stream(HANDLE h, const struct wim_dentry *dentry,
675                             const struct wim_lookup_table_entry *lte,
676                             const wchar_t *stream_path,
677                             const wchar_t *stream_name_utf16,
678                             struct apply_args *args)
679 {
680         int ret = 0;
681         const struct wim_inode *inode = dentry->d_inode;
682         if (stream_name_utf16 == NULL) {
683                 /* Unnamed stream. */
684
685                 /* Set security descriptor, unless the extract_flags indicate
686                  * not to or the volume does not supported it.  Note that this
687                  * is only done when the unnamed stream is being extracted, as
688                  * security descriptors are per-file and not per-stream. */
689                 if (inode->i_security_id >= 0 &&
690                     !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
691                     && (args->vol_flags & FILE_PERSISTENT_ACLS))
692                 {
693                         ret = win32_set_security_data(inode, h, stream_path, args);
694                         if (ret)
695                                 return ret;
696                 }
697
698                 /* Handle reparse points.  The data for them needs to be set
699                  * using a special ioctl.  Note that the reparse point may have
700                  * been created using CreateFileW() in the case of
701                  * non-directories or CreateDirectoryW() in the case of
702                  * directories; but the ioctl works either way.  Also, it is
703                  * only this step that actually sets the
704                  * FILE_ATTRIBUTE_REPARSE_POINT, as it is not valid to set it
705                  * using SetFileAttributesW() or CreateFileW().
706                  *
707                  * If the volume does not support reparse points we simply
708                  * ignore the reparse data.  (N.B. the code currently doesn't
709                  * actually reach this case because reparse points are skipped
710                  * entirely on such volumes.) */
711                 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
712                         if (args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
713                                 ret = win32_set_reparse_data(h, inode,
714                                                              lte, stream_path,
715                                                              args);
716                                 if (ret)
717                                         return ret;
718                         } else {
719                                 DEBUG("Cannot set reparse data on \"%ls\": volume "
720                                       "does not support reparse points", stream_path);
721                         }
722                 } else if (lte != NULL &&
723                            !(args->vol_flags & FILE_SUPPORTS_ENCRYPTION &&
724                              inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
725                 {
726                         /* Extract the data of the unnamed stream, unless the
727                          * lookup table entry is NULL (indicating an empty
728                          * stream for which no data needs to be extracted), or
729                          * the stream is encrypted and therefore was already
730                          * extracted as a special case. */
731                         ret = do_win32_extract_stream(h, lte);
732                         if (ret)
733                                 return ret;
734                 }
735
736                 if (dentry_has_short_name(dentry))
737                         SetFileShortNameW(h, dentry->short_name);
738                 else if (running_on_windows_7_or_later())
739                         SetFileShortNameW(h, L"");
740         } else {
741                 /* Extract the data for a named data stream. */
742                 if (lte != NULL) {
743                         DEBUG("Extracting named data stream \"%ls\" (len = %"PRIu64")",
744                               stream_path, wim_resource_size(lte));
745                         ret = do_win32_extract_stream(h, lte);
746                 }
747         }
748         return ret;
749 }
750
751 static int
752 win32_decrypt_file(HANDLE open_handle, const wchar_t *path)
753 {
754         DWORD err;
755         /* We cannot call DecryptFileW() while there is an open handle to the
756          * file.  So close it first. */
757         if (!CloseHandle(open_handle)) {
758                 err = GetLastError();
759                 ERROR("Failed to close handle for \"%ls\"", path);
760                 win32_error(err);
761                 return WIMLIB_ERR_WRITE;
762         }
763         if (!DecryptFileW(path, 0 /* reserved parameter; set to 0 */)) {
764                 err = GetLastError();
765                 ERROR("Failed to decrypt file \"%ls\"", path);
766                 win32_error(err);
767                 return WIMLIB_ERR_WRITE;
768         }
769         return 0;
770 }
771
772 /*
773  * Create and extract a stream to a file, or create a directory, using the
774  * Windows API.
775  *
776  * This handles reparse points, directories, alternate data streams, encrypted
777  * files, compressed files, etc.
778  *
779  * @dentry: WIM dentry for the file or directory being extracted.
780  *
781  * @path:  Path to extract the file to.
782  *
783  * @stream_name_utf16:
784  *         Name of the stream, or NULL if the stream is unnamed.  This will
785  *         be called with a NULL stream_name_utf16 before any non-NULL
786  *         stream_name_utf16's.
787  *
788  * @lte:   WIM lookup table entry for the stream.  May be NULL to indicate
789  *         a stream of length 0.
790  *
791  * @args:  Additional apply context, including flags indicating supported
792  *         volume features.
793  *
794  * Returns 0 on success; nonzero on failure.
795  */
796 static int
797 win32_extract_stream(const struct wim_dentry *dentry,
798                      const wchar_t *path,
799                      const wchar_t *stream_name_utf16,
800                      struct wim_lookup_table_entry *lte,
801                      struct apply_args *args)
802 {
803         wchar_t *stream_path;
804         HANDLE h;
805         int ret;
806         DWORD err;
807         DWORD creationDisposition = CREATE_ALWAYS;
808         DWORD requestedAccess;
809         BY_HANDLE_FILE_INFORMATION file_info;
810         unsigned remaining_sharing_violations = 1000;
811         const struct wim_inode *inode = dentry->d_inode;
812
813         if (stream_name_utf16) {
814                 /* Named stream.  Create a buffer that contains the UTF-16LE
815                  * string [./]path:stream_name_utf16.  This is needed to
816                  * create and open the stream using CreateFileW().  I'm not
817                  * aware of any other APIs to do this.  Note: the '$DATA' suffix
818                  * seems to be unneeded.  Additional note: a "./" prefix needs
819                  * to be added when the path is not absolute to avoid ambiguity
820                  * with drive letters. */
821                 size_t stream_path_nchars;
822                 size_t path_nchars;
823                 size_t stream_name_nchars;
824                 const wchar_t *prefix;
825
826                 path_nchars = wcslen(path);
827                 stream_name_nchars = wcslen(stream_name_utf16);
828                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
829                 if (path[0] != cpu_to_le16(L'\0') &&
830                     path[0] != cpu_to_le16(L'/') &&
831                     path[0] != cpu_to_le16(L'\\') &&
832                     path[1] != cpu_to_le16(L':'))
833                 {
834                         prefix = L"./";
835                         stream_path_nchars += 2;
836                 } else {
837                         prefix = L"";
838                 }
839                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
840                 swprintf(stream_path, L"%ls%ls:%ls",
841                          prefix, path, stream_name_utf16);
842         } else {
843                 /* Unnamed stream; its path is just the path to the file itself.
844                  * */
845                 stream_path = (wchar_t*)path;
846
847                 ret = win32_begin_extract_unnamed_stream(inode, lte, path,
848                                                          &creationDisposition,
849                                                          args->vol_flags);
850                 if (ret)
851                         goto fail;
852         }
853
854         DEBUG("Opening \"%ls\"", stream_path);
855         /* DELETE access is needed for SetFileShortNameW(), for some reason. */
856         requestedAccess = GENERIC_READ | GENERIC_WRITE | DELETE |
857                           ACCESS_SYSTEM_SECURITY;
858 try_open_again:
859         /* Open the stream to be extracted.  Depending on what we have set
860          * creationDisposition to, we may be creating this for the first time,
861          * or we may be opening on existing stream we already created using
862          * CreateDirectoryW() or OpenEncryptedFileRawW(). */
863         h = CreateFileW(stream_path,
864                         requestedAccess,
865                         FILE_SHARE_READ,
866                         NULL,
867                         creationDisposition,
868                         win32_get_create_flags_and_attributes(inode->i_attributes),
869                         NULL);
870         if (h == INVALID_HANDLE_VALUE) {
871                 err = GetLastError();
872                 if (err == ERROR_ACCESS_DENIED &&
873                     path_is_root_of_drive(stream_path))
874                 {
875                         ret = 0;
876                         goto out;
877                 }
878                 if ((err == ERROR_PRIVILEGE_NOT_HELD ||
879                      err == ERROR_ACCESS_DENIED) &&
880                     (requestedAccess & ACCESS_SYSTEM_SECURITY))
881                 {
882                         /* Try opening the file again without privilege to
883                          * modify SACL. */
884                         requestedAccess &= ~ACCESS_SYSTEM_SECURITY;
885                         goto try_open_again;
886                 }
887                 if (err == ERROR_SHARING_VIOLATION) {
888                         if (remaining_sharing_violations) {
889                                 --remaining_sharing_violations;
890                                 /* This can happen when restoring encrypted directories
891                                  * for some reason.  Probably a bug in EncryptFile(). */
892                                 WARNING("Couldn't open \"%ls\" due to sharing violation; "
893                                         "re-trying after 100ms", stream_path);
894                                 Sleep(100);
895                                 goto try_open_again;
896                         } else {
897                                 ERROR("Too many sharing violations; giving up...");
898                         }
899                 } else {
900                         if (creationDisposition == OPEN_EXISTING)
901                                 ERROR("Failed to open \"%ls\"", stream_path);
902                         else
903                                 ERROR("Failed to create \"%ls\"", stream_path);
904                         win32_error(err);
905                 }
906                 ret = WIMLIB_ERR_OPEN;
907                 goto fail;
908         }
909
910         /* Check the attributes of the file we just opened, and remove
911          * encryption or compression if either was set by default but is not
912          * supposed to be set based on the WIM inode attributes. */
913         if (!GetFileInformationByHandle(h, &file_info)) {
914                 err = GetLastError();
915                 ERROR("Failed to get attributes of \"%ls\"", stream_path);
916                 win32_error(err);
917                 ret = WIMLIB_ERR_STAT;
918                 goto fail_close_handle;
919         }
920
921         /* Remove encryption? */
922         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED &&
923             !(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
924         {
925                 /* File defaulted to encrypted due to being in an encrypted
926                  * directory, but is not actually supposed to be encrypted.
927                  *
928                  * This is a workaround, because I'm not aware of any way to
929                  * directly (e.g. with CreateFileW()) create an unencrypted file
930                  * in a directory with FILE_ATTRIBUTE_ENCRYPTED set. */
931                 ret = win32_decrypt_file(h, stream_path);
932                 if (ret)
933                         goto fail; /* win32_decrypt_file() closed the handle. */
934                 creationDisposition = OPEN_EXISTING;
935                 goto try_open_again;
936         }
937
938         /* Remove compression? */
939         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED &&
940             !(inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED))
941         {
942                 /* Similar to the encrypted case, above, if the file defaulted
943                  * to compressed due to being in an compressed directory, but is
944                  * not actually supposed to be compressed, explicitly set the
945                  * compression format to COMPRESSION_FORMAT_NONE. */
946                 ret = win32_set_compression_state(h, COMPRESSION_FORMAT_NONE,
947                                                   stream_path);
948                 if (ret)
949                         goto fail_close_handle;
950         }
951
952         /* Set compression and/or sparse attributes if needed */
953         ret = win32_set_special_stream_attributes(h, inode, lte, path,
954                                                   args->vol_flags);
955
956         if (ret)
957                 goto fail_close_handle;
958
959         /* At this point we have at least created the needed stream with the
960          * appropriate attributes.  We have yet to set the appropriate security
961          * descriptor and actually extract the stream data (other than for
962          * extracted files, which were already extracted).
963          * win32_finish_extract_stream() handles these additional steps. */
964         ret = win32_finish_extract_stream(h, dentry, lte, stream_path,
965                                           stream_name_utf16, args);
966         if (ret)
967                 goto fail_close_handle;
968
969         /* Done extracting the stream.  Close the handle and return. */
970         DEBUG("Closing \"%ls\"", stream_path);
971         if (!CloseHandle(h)) {
972                 err = GetLastError();
973                 ERROR("Failed to close \"%ls\"", stream_path);
974                 win32_error(err);
975                 ret = WIMLIB_ERR_WRITE;
976                 goto fail;
977         }
978         ret = 0;
979         goto out;
980 fail_close_handle:
981         CloseHandle(h);
982 fail:
983         ERROR("Error extracting \"%ls\"", stream_path);
984 out:
985         return ret;
986 }
987
988 /*
989  * Creates a file, directory, or reparse point and extracts all streams to it
990  * (unnamed data stream and/or reparse point stream, plus any alternate data
991  * streams).  Handles sparse, compressed, and/or encrypted files.
992  *
993  * @dentry:     WIM dentry for this file or directory.
994  * @path:       UTF-16LE external path to extract the inode to.
995  * @args:       Additional extraction context.
996  *
997  * Returns 0 on success; nonzero on failure.
998  */
999 static int
1000 win32_extract_streams(const struct wim_dentry *dentry,
1001                       const wchar_t *path, struct apply_args *args)
1002 {
1003         struct wim_lookup_table_entry *unnamed_lte;
1004         int ret;
1005         const struct wim_inode *inode = dentry->d_inode;
1006
1007         /* First extract the unnamed stream. */
1008
1009         unnamed_lte = inode_unnamed_lte_resolved(inode);
1010         ret = win32_extract_stream(dentry, path, NULL, unnamed_lte, args);
1011         if (ret)
1012                 goto out;
1013
1014         /* Extract any named streams, if supported by the volume. */
1015
1016         if (!(args->vol_flags & FILE_NAMED_STREAMS))
1017                 goto out;
1018         for (u16 i = 0; i < inode->i_num_ads; i++) {
1019                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1020
1021                 /* Skip the unnamed stream if it's in the ADS entries (we
1022                  * already extracted it...) */
1023                 if (ads_entry->stream_name_nbytes == 0)
1024                         continue;
1025
1026                 /* Skip special UNIX data entries (see documentation for
1027                  * WIMLIB_ADD_FLAG_UNIX_DATA) */
1028                 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1029                     && !memcmp(ads_entry->stream_name,
1030                                WIMLIB_UNIX_DATA_TAG_UTF16LE,
1031                                WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1032                         continue;
1033
1034                 /* Extract the named stream */
1035                 ret = win32_extract_stream(dentry,
1036                                            path,
1037                                            ads_entry->stream_name,
1038                                            ads_entry->lte,
1039                                            args);
1040                 if (ret)
1041                         break;
1042         }
1043 out:
1044         return ret;
1045 }
1046
1047 static int
1048 dentry_clear_inode_visited(struct wim_dentry *dentry, void *_ignore)
1049 {
1050         dentry->d_inode->i_visited = 0;
1051         return 0;
1052 }
1053
1054 static int
1055 dentry_get_features(struct wim_dentry *dentry, void *_features_p)
1056 {
1057         DWORD features = 0;
1058         DWORD *features_p = _features_p;
1059         struct wim_inode *inode = dentry->d_inode;
1060
1061         if (inode->i_visited) {
1062                 features |= FILE_SUPPORTS_HARD_LINKS;
1063         } else {
1064                 inode->i_visited = 1;
1065                 if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE)
1066                         features |= FILE_SUPPORTS_SPARSE_FILES;
1067                 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1068                         features |= FILE_SUPPORTS_REPARSE_POINTS;
1069                 for (unsigned i = 0; i < inode->i_num_ads; i++)
1070                         if (inode->i_ads_entries[i].stream_name_nbytes)
1071                                 features |= FILE_NAMED_STREAMS;
1072                 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)
1073                         features |= FILE_SUPPORTS_ENCRYPTION;
1074                 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED)
1075                         features |= FILE_FILE_COMPRESSION;
1076                 if (inode->i_security_id != -1)
1077                         features |= FILE_PERSISTENT_ACLS;
1078         }
1079         *features_p |= features;
1080         return 0;
1081 }
1082
1083 /* If not done already, load the supported feature flags for the volume onto
1084  * which the image is being extracted, and warn the user about any missing
1085  * features that could be important. */
1086 static int
1087 win32_check_vol_flags(const wchar_t *output_path,
1088                       struct wim_dentry *root, struct apply_args *args)
1089 {
1090         DWORD dentry_features = 0;
1091         DWORD missing_features;
1092
1093         if (args->have_vol_flags)
1094                 return 0;
1095
1096         for_dentry_in_tree(root, dentry_clear_inode_visited, NULL);
1097         for_dentry_in_tree(root, dentry_get_features, &dentry_features);
1098
1099         win32_get_vol_flags(output_path, &args->vol_flags);
1100         args->have_vol_flags = true;
1101
1102         missing_features = dentry_features & ~args->vol_flags;
1103
1104         /* Warn the user about data that may not be extracted. */
1105         if (missing_features & FILE_SUPPORTS_SPARSE_FILES)
1106                 WARNING("Volume does not support sparse files!\n"
1107                         "          Sparse files will be extracted as non-sparse.");
1108         if (missing_features & FILE_SUPPORTS_REPARSE_POINTS)
1109                 WARNING("Volume does not support reparse points!\n"
1110                         "          Reparse point data will not be extracted.");
1111         if (missing_features & FILE_NAMED_STREAMS) {
1112                 WARNING("Volume does not support named data streams!\n"
1113                         "          Named data streams will not be extracted.");
1114         }
1115         if (missing_features & FILE_SUPPORTS_ENCRYPTION) {
1116                 WARNING("Volume does not support encryption!\n"
1117                         "          Encrypted files will be extracted as raw data.");
1118         }
1119         if (missing_features & FILE_FILE_COMPRESSION) {
1120                 WARNING("Volume does not support transparent compression!\n"
1121                         "          Compressed files will be extracted as non-compressed.");
1122         }
1123         if (missing_features & FILE_PERSISTENT_ACLS) {
1124                 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
1125                         ERROR("Strict ACLs requested, but the volume does not "
1126                               "support ACLs!");
1127                         return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
1128                 } else {
1129                         WARNING("Volume does not support persistent ACLS!\n"
1130                                 "          File permissions will not be extracted.");
1131                 }
1132         }
1133         if (running_on_windows_7_or_later() &&
1134             (missing_features & FILE_SUPPORTS_HARD_LINKS))
1135         {
1136                 WARNING("Volume does not support hard links!\n"
1137                         "          Hard links will be extracted as duplicate files.");
1138         }
1139         return 0;
1140 }
1141
1142 /*
1143  * Try extracting a hard link.
1144  *
1145  * @output_path:  Path to link to be extracted.
1146  *
1147  * @inode:        WIM inode that the link is to; inode->i_extracted_file
1148  *                the path to a name of the file that has already been
1149  *                extracted (we use this to create the hard link).
1150  *
1151  * @args:         Additional apply context, used here to keep track of
1152  *                the number of times creating a hard link failed due to
1153  *                ERROR_INVALID_FUNCTION.  This error should indicate that hard
1154  *                links are not supported by the volume, and we would like to
1155  *                warn the user a few times, but not too many times.
1156  *
1157  * Returns 0 if the hard link was successfully extracted.  Returns
1158  * WIMLIB_ERR_LINK (> 0) if an error occurred, other than hard links possibly
1159  * being unsupported by the volume.  Returns a negative value if creating the
1160  * hard link failed due to ERROR_INVALID_FUNCTION.
1161  */
1162 static int
1163 win32_try_hard_link(const wchar_t *output_path, const struct wim_inode *inode,
1164                     struct apply_args *args)
1165 {
1166         DWORD err;
1167
1168         /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
1169          * but it's only available on Windows 7 and later.
1170          *
1171          * Otherwise, CreateHardLinkW() will apparently return
1172          * ERROR_INVALID_FUNCTION if the volume does not support hard links. */
1173
1174         DEBUG("Creating hard link \"%ls => %ls\"",
1175               output_path, inode->i_extracted_file);
1176
1177         if (running_on_windows_7_or_later() &&
1178             !(args->vol_flags & FILE_SUPPORTS_HARD_LINKS))
1179                 goto hard_links_unsupported;
1180
1181         if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
1182                 return 0;
1183
1184         err = GetLastError();
1185         if (err != ERROR_INVALID_FUNCTION) {
1186                 ERROR("Can't create hard link \"%ls => %ls\"",
1187                       output_path, inode->i_extracted_file);
1188                 win32_error(err);
1189                 return WIMLIB_ERR_LINK;
1190         }
1191 hard_links_unsupported:
1192         args->num_hard_links_failed++;
1193         if (args->num_hard_links_failed <= MAX_CREATE_HARD_LINK_WARNINGS) {
1194                 if (running_on_windows_7_or_later())
1195                 {
1196                         WARNING("Extracting duplicate copy of \"%ls\" "
1197                                 "rather than hard link", output_path);
1198                 } else {
1199                         WARNING("Can't create hard link \"%ls\" => \"%ls\":\n"
1200                                 "          Volume does not support hard links!\n"
1201                                 "          Falling back to extracting a copy of the file.",
1202                                 output_path, inode->i_extracted_file);
1203                 }
1204         }
1205         if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS)
1206                 WARNING("Suppressing further hard linking warnings...");
1207         return -1;
1208 }
1209
1210 /* Extract a file, directory, reparse point, or hard link to an
1211  * already-extracted file using the Win32 API */
1212 int
1213 win32_do_apply_dentry(const wchar_t *output_path,
1214                       size_t output_path_num_chars,
1215                       struct wim_dentry *dentry,
1216                       struct apply_args *args)
1217 {
1218         int ret;
1219         struct wim_inode *inode = dentry->d_inode;
1220
1221         ret = win32_check_vol_flags(output_path, dentry, args);
1222         if (ret)
1223                 return ret;
1224         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1225                 /* Linked file, with another name already extracted.  Create a
1226                  * hard link. */
1227                 ret = win32_try_hard_link(output_path, inode, args);
1228                 if (ret >= 0)
1229                         return ret;
1230                 /* Negative return value from win32_try_hard_link() indicates
1231                  * that hard links are probably not supported by the volume.
1232                  * Fall back to extracting a copy of the file. */
1233         }
1234
1235         /* If this is a reparse point and the volume does not support reparse
1236          * points, just skip it completely. */
1237         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1238             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1239         {
1240                 WARNING("Not extracting reparse point \"%ls\"", output_path);
1241                 dentry->not_extracted = 1;
1242         } else {
1243                 /* Create the file, directory, or reparse point, and extract the
1244                  * data streams. */
1245                 ret = win32_extract_streams(dentry, output_path, args);
1246                 if (ret)
1247                         return ret;
1248         }
1249         if (inode->i_extracted_file == NULL) {
1250                 const struct wim_lookup_table_entry *lte;
1251
1252                 /* Tally bytes extracted, including all alternate data streams,
1253                  * unless we extracted a hard link (or, at least extracted a
1254                  * name that was supposed to be a hard link) */
1255                 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1256                         lte = inode_stream_lte_resolved(inode, i);
1257                         if (lte)
1258                                 args->progress.extract.completed_bytes +=
1259                                                         wim_resource_size(lte);
1260                 }
1261                 if (inode->i_nlink > 1) {
1262                         /* Save extracted path for a later call to
1263                          * CreateHardLinkW() if this inode has multiple links.
1264                          * */
1265                         inode->i_extracted_file = WCSDUP(output_path);
1266                         if (!inode->i_extracted_file)
1267                                 return WIMLIB_ERR_NOMEM;
1268                 }
1269         }
1270         return 0;
1271 }
1272
1273 /* Set timestamps on an extracted file using the Win32 API */
1274 int
1275 win32_do_apply_dentry_timestamps(const wchar_t *path,
1276                                  size_t path_num_chars,
1277                                  struct wim_dentry *dentry,
1278                                  struct apply_args *args)
1279 {
1280         DWORD err;
1281         HANDLE h;
1282         const struct wim_inode *inode = dentry->d_inode;
1283
1284         /* Windows doesn't let you change the timestamps of the root directory
1285          * (at least on FAT, which is dumb but expected since FAT doesn't store
1286          * any metadata about the root directory...) */
1287         if (path_is_root_of_drive(path))
1288                 return 0;
1289
1290         DEBUG("Opening \"%ls\" to set timestamps", path);
1291         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1292         if (h == INVALID_HANDLE_VALUE) {
1293                 err = GetLastError();
1294                 goto fail;
1295         }
1296
1297         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1298                                  .dwHighDateTime = inode->i_creation_time >> 32};
1299         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1300                                   .dwHighDateTime = inode->i_last_access_time >> 32};
1301         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1302                                   .dwHighDateTime = inode->i_last_write_time >> 32};
1303
1304         DEBUG("Calling SetFileTime() on \"%ls\"", path);
1305         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1306                 err = GetLastError();
1307                 CloseHandle(h);
1308                 goto fail;
1309         }
1310         DEBUG("Closing \"%ls\"", path);
1311         if (!CloseHandle(h)) {
1312                 err = GetLastError();
1313                 goto fail;
1314         }
1315         goto out;
1316 fail:
1317         /* Only warn if setting timestamps failed; still return 0. */
1318         WARNING("Can't set timestamps on \"%ls\"", path);
1319         win32_error(err);
1320 out:
1321         return 0;
1322 }
1323
1324 #endif /* __WIN32__ */