]> wimlib.net Git - wimlib/blob - src/win32_apply.c
300571f03e41f41a02211aa09f50c9ff5e02b93f
[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, 2014 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 "wimlib/win32_common.h"
31
32 #include "wimlib/apply.h"
33 #include "wimlib/capture.h" /* for mangle_pat() and match_pattern_list()  */
34 #include "wimlib/dentry.h"
35 #include "wimlib/error.h"
36 #include "wimlib/lookup_table.h"
37 #include "wimlib/metadata.h"
38 #include "wimlib/reparse.h"
39 #include "wimlib/textfile.h"
40 #include "wimlib/xml.h"
41 #include "wimlib/wimboot.h"
42
43 struct win32_apply_ctx {
44
45         /* Extract flags, the pointer to the WIMStruct, etc.  */
46         struct apply_ctx common;
47
48         /* WIMBoot information, only filled in if WIMLIB_EXTRACT_FLAG_WIMBOOT
49          * was provided  */
50         struct {
51                 u64 data_source_id;
52                 struct string_set *prepopulate_pats;
53                 void *mem_prepopulate_pats;
54                 u8 wim_lookup_table_hash[SHA1_HASH_SIZE];
55                 bool wof_running;
56         } wimboot;
57
58         /* Open handle to the target directory  */
59         HANDLE h_target;
60
61         /* NT namespace path to the target directory (buffer allocated)  */
62         UNICODE_STRING target_ntpath;
63
64         /* Temporary buffer for building paths (buffer allocated)  */
65         UNICODE_STRING pathbuf;
66
67         /* Object attributes to reuse for opening files in the target directory.
68          * (attr.ObjectName == &pathbuf) and (attr.RootDirectory == h_target).
69          */
70         OBJECT_ATTRIBUTES attr;
71
72         /* Temporary I/O status block for system calls  */
73         IO_STATUS_BLOCK iosb;
74
75         /* Allocated buffer for creating "printable" paths from our
76          * target-relative NT paths  */
77         wchar_t *print_buffer;
78
79         /* Allocated buffer for reading stream data when it cannot be extracted
80          * directly  */
81         u8 *data_buffer;
82
83         /* Pointer to the next byte in @data_buffer to fill  */
84         u8 *data_buffer_ptr;
85
86         /* Size allocated in @data_buffer  */
87         size_t data_buffer_size;
88
89         /* Current offset in the raw encrypted file being written  */
90         size_t encrypted_offset;
91
92         /* Current size of the raw encrypted file being written  */
93         size_t encrypted_size;
94
95         /* Temporary buffer for reparse data  */
96         struct reparse_buffer_disk rpbuf;
97
98         /* Temporary buffer for reparse data of "fixed" absolute symbolic links
99          * and junctions  */
100         struct reparse_buffer_disk rpfixbuf;
101
102         /* Array of open handles to filesystem streams currently being written
103          */
104         HANDLE open_handles[MAX_OPEN_STREAMS];
105
106         /* Number of handles in @open_handles currently open (filled in from the
107          * beginning of the array)  */
108         unsigned num_open_handles;
109
110         /* List of dentries, joined by @tmp_list, that need to have reparse data
111          * extracted as soon as the whole stream has been read into
112          * @data_buffer.  */
113         struct list_head reparse_dentries;
114
115         /* List of dentries, joined by @tmp_list, that need to have raw
116          * encrypted data extracted as soon as the whole stream has been read
117          * into @data_buffer.  */
118         struct list_head encrypted_dentries;
119
120         /* Number of files for which we didn't have permission to set the full
121          * security descriptor.  */
122         unsigned long partial_security_descriptors;
123
124         /* Number of files for which we didn't have permission to set any part
125          * of the security descriptor.  */
126         unsigned long no_security_descriptors;
127 };
128
129 /* Get the drive letter from a Windows path, or return the null character if the
130  * path is relative.  */
131 static wchar_t
132 get_drive_letter(const wchar_t *path)
133 {
134         /* Skip \\?\ prefix  */
135         if (!wcsncmp(path, L"\\\\?\\", 4))
136                 path += 4;
137
138         /* Return drive letter if valid  */
139         if (((path[0] >= L'a' && path[0] <= L'z') ||
140              (path[0] >= L'A' && path[0] <= L'Z')) && path[1] == L':')
141                 return path[0];
142
143         return L'\0';
144 }
145
146 static void
147 get_vol_flags(const wchar_t *target, DWORD *vol_flags_ret,
148               bool *short_names_supported_ret)
149 {
150         wchar_t filesystem_name[MAX_PATH + 1];
151         wchar_t drive[4];
152         wchar_t *volume = NULL;
153
154         *vol_flags_ret = 0;
155         *short_names_supported_ret = false;
156
157         drive[0] = get_drive_letter(target);
158         if (drive[0]) {
159                 drive[1] = L':';
160                 drive[2] = L'\\';
161                 drive[3] = L'\0';
162                 volume = drive;
163         }
164
165         if (!GetVolumeInformation(volume, NULL, 0, NULL, NULL,
166                                   vol_flags_ret, filesystem_name,
167                                   ARRAY_LEN(filesystem_name)))
168         {
169                 DWORD err = GetLastError();
170                 set_errno_from_win32_error(err);
171                 WARNING_WITH_ERRNO("Failed to get volume information for "
172                                    "\"%ls\" (err=%"PRIu32")",
173                                    target, (u32)err);
174                 return;
175         }
176
177         if (wcsstr(filesystem_name, L"NTFS")) {
178                 /* FILE_SUPPORTS_HARD_LINKS is only supported on Windows 7 and
179                  * later.  Force it on anyway if filesystem is NTFS.  */
180                 *vol_flags_ret |= FILE_SUPPORTS_HARD_LINKS;
181
182                 /* There's no volume flag for short names, but according to the
183                  * MS documentation they are only user-settable on NTFS.  */
184                 *short_names_supported_ret = true;
185         }
186 }
187
188 static int
189 win32_get_supported_features(const wchar_t *target,
190                              struct wim_features *supported_features)
191 {
192         DWORD vol_flags;
193         bool short_names_supported;
194
195         /* Query the features of the target volume.  */
196
197         get_vol_flags(target, &vol_flags, &short_names_supported);
198
199         supported_features->archive_files = 1;
200         supported_features->hidden_files = 1;
201         supported_features->system_files = 1;
202
203         if (vol_flags & FILE_FILE_COMPRESSION)
204                 supported_features->compressed_files = 1;
205
206         if (vol_flags & FILE_SUPPORTS_ENCRYPTION) {
207                 supported_features->encrypted_files = 1;
208                 supported_features->encrypted_directories = 1;
209         }
210
211         supported_features->not_context_indexed_files = 1;
212
213         /* Don't do anything with FILE_SUPPORTS_SPARSE_FILES.  */
214
215         if (vol_flags & FILE_NAMED_STREAMS)
216                 supported_features->named_data_streams = 1;
217
218         if (vol_flags & FILE_SUPPORTS_HARD_LINKS)
219                 supported_features->hard_links = 1;
220
221         if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS)
222                 supported_features->reparse_points = 1;
223
224         if (vol_flags & FILE_PERSISTENT_ACLS)
225                 supported_features->security_descriptors = 1;
226
227         if (short_names_supported)
228                 supported_features->short_names = 1;
229
230         supported_features->timestamps = 1;
231
232         /* Note: Windows does not support case sensitive filenames!  At least
233          * not without changing the registry and rebooting...  */
234
235         return 0;
236 }
237
238 /* Load the patterns from [PrepopulateList] of WimBootCompress.ini in the WIM
239  * image being extracted.  */
240 static int
241 load_prepopulate_pats(struct win32_apply_ctx *ctx)
242 {
243         const wchar_t *path = L"\\Windows\\System32\\WimBootCompress.ini";
244         struct wim_dentry *dentry;
245         struct wim_lookup_table_entry *lte;
246         int ret;
247         void *buf;
248         struct string_set *s;
249         void *mem;
250         struct text_file_section sec;
251
252         dentry = get_dentry(ctx->common.wim, path, WIMLIB_CASE_INSENSITIVE);
253         if (!dentry ||
254             (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
255                                               FILE_ATTRIBUTE_REPARSE_POINT |
256                                               FILE_ATTRIBUTE_ENCRYPTED)) ||
257             !(lte = inode_unnamed_lte(dentry->d_inode, ctx->common.wim->lookup_table)))
258         {
259                 WARNING("%ls does not exist in WIM image!", path);
260                 return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
261         }
262
263         ret = read_full_stream_into_alloc_buf(lte, &buf);
264         if (ret)
265                 return ret;
266
267         s = CALLOC(1, sizeof(struct string_set));
268         if (!s) {
269                 FREE(buf);
270                 return WIMLIB_ERR_NOMEM;
271         }
272
273         sec.name = T("PrepopulateList");
274         sec.strings = s;
275
276         ret = do_load_text_file(path, buf, lte->size, &mem, &sec, 1,
277                                 LOAD_TEXT_FILE_REMOVE_QUOTES |
278                                         LOAD_TEXT_FILE_NO_WARNINGS,
279                                 mangle_pat);
280         BUILD_BUG_ON(OS_PREFERRED_PATH_SEPARATOR != WIM_PATH_SEPARATOR);
281         FREE(buf);
282         if (ret) {
283                 FREE(s);
284                 return ret;
285         }
286         ctx->wimboot.prepopulate_pats = s;
287         ctx->wimboot.mem_prepopulate_pats = mem;
288         return 0;
289 }
290
291 /* Returns %true if the path to @dentry matches a pattern in [PrepopulateList]
292  * of WimBootCompress.ini.  Otherwise returns %false.
293  *
294  * @dentry must have had its full path calculated.  */
295 static bool
296 in_prepopulate_list(struct wim_dentry *dentry,
297                     const struct win32_apply_ctx *ctx)
298 {
299         const struct string_set *pats = ctx->wimboot.prepopulate_pats;
300
301         if (!pats || !pats->num_strings)
302                 return false;
303
304         return match_pattern_list(dentry->_full_path,
305                                   wcslen(dentry->_full_path), pats);
306 }
307
308 /* Calculates the SHA-1 message digest of the WIM's lookup table.  */
309 static int
310 hash_lookup_table(WIMStruct *wim, u8 hash[SHA1_HASH_SIZE])
311 {
312         return wim_reshdr_to_hash(&wim->hdr.lookup_table_reshdr, wim, hash);
313 }
314
315 /* Prepare for doing a "WIMBoot" extraction by loading patterns from
316  * [PrepopulateList] of WimBootCompress.ini and allocating a WOF data source ID
317  * on the target volume.  */
318 static int
319 start_wimboot_extraction(struct win32_apply_ctx *ctx)
320 {
321         int ret;
322         WIMStruct *wim = ctx->common.wim;
323
324         ret = load_prepopulate_pats(ctx);
325         if (ret == WIMLIB_ERR_NOMEM)
326                 return ret;
327
328         if (!wim_info_get_wimboot(wim->wim_info, wim->current_image))
329                 WARNING("Image is not marked as WIMBoot compatible!");
330
331         ret = hash_lookup_table(ctx->common.wim,
332                                 ctx->wimboot.wim_lookup_table_hash);
333         if (ret)
334                 return ret;
335
336         return wimboot_alloc_data_source_id(wim->filename,
337                                             wim->hdr.guid,
338                                             wim->current_image,
339                                             ctx->common.target,
340                                             &ctx->wimboot.data_source_id,
341                                             &ctx->wimboot.wof_running);
342 }
343
344 /* Returns the number of wide characters needed to represent the path to the
345  * specified @dentry, relative to the target directory, when extracted.
346  *
347  * Does not include null terminator (not needed for NtCreateFile).  */
348 static size_t
349 dentry_extraction_path_length(const struct wim_dentry *dentry)
350 {
351         size_t len = 0;
352         const struct wim_dentry *d;
353
354         d = dentry;
355         do {
356                 len += d->d_extraction_name_nchars + 1;
357                 d = d->d_parent;
358         } while (!dentry_is_root(d) && will_extract_dentry(d));
359
360         return --len;  /* No leading slash  */
361 }
362
363 /* Returns the length of the longest string that might need to be appended to
364  * the path to an alias of an inode to open or create a named data stream.
365  *
366  * If the inode has no named data streams, this will be 0.  Otherwise, this will
367  * be 1 plus the length of the longest-named data stream, since the data stream
368  * name must be separated from the path by the ':' character.  */
369 static size_t
370 inode_longest_named_data_stream_spec(const struct wim_inode *inode)
371 {
372         size_t max = 0;
373         for (u16 i = 0; i < inode->i_num_ads; i++) {
374                 size_t len = inode->i_ads_entries[i].stream_name_nbytes;
375                 if (len > max)
376                         max = len;
377         }
378         if (max)
379                 max = 1 + (max / sizeof(wchar_t));
380         return max;
381 }
382
383 /* Find the length, in wide characters, of the longest path needed for
384  * extraction of any file in @dentry_list relative to the target directory.
385  *
386  * Accounts for named data streams, but does not include null terminator (not
387  * needed for NtCreateFile).  */
388 static size_t
389 compute_path_max(struct list_head *dentry_list)
390 {
391         size_t max = 0;
392         const struct wim_dentry *dentry;
393
394         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
395                 size_t len;
396
397                 len = dentry_extraction_path_length(dentry);
398
399                 /* Account for named data streams  */
400                 len += inode_longest_named_data_stream_spec(dentry->d_inode);
401
402                 if (len > max)
403                         max = len;
404         }
405
406         return max;
407 }
408
409 /* Build the path at which to extract the @dentry, relative to the target
410  * directory.
411  *
412  * The path is saved in ctx->pathbuf.  */
413 static void
414 build_extraction_path(const struct wim_dentry *dentry,
415                       struct win32_apply_ctx *ctx)
416 {
417         size_t len;
418         wchar_t *p;
419         const struct wim_dentry *d;
420
421         len = dentry_extraction_path_length(dentry);
422
423         ctx->pathbuf.Length = len * sizeof(wchar_t);
424         p = ctx->pathbuf.Buffer + len;
425         for (d = dentry;
426              !dentry_is_root(d->d_parent) && will_extract_dentry(d->d_parent);
427              d = d->d_parent)
428         {
429                 p -= d->d_extraction_name_nchars;
430                 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
431                 *--p = '\\';
432         }
433         /* No leading slash  */
434         p -= d->d_extraction_name_nchars;
435         wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
436 }
437
438 /* Build the path at which to extract the @dentry, relative to the target
439  * directory, adding the suffix for a named data stream.
440  *
441  * The path is saved in ctx->pathbuf.  */
442 static void
443 build_extraction_path_with_ads(const struct wim_dentry *dentry,
444                                struct win32_apply_ctx *ctx,
445                                const wchar_t *stream_name,
446                                size_t stream_name_nchars)
447 {
448         wchar_t *p;
449
450         build_extraction_path(dentry, ctx);
451
452         /* Add :NAME for named data stream  */
453         p = ctx->pathbuf.Buffer + (ctx->pathbuf.Length / sizeof(wchar_t));
454         *p++ = L':';
455         wmemcpy(p, stream_name, stream_name_nchars);
456         ctx->pathbuf.Length += (1 + stream_name_nchars) * sizeof(wchar_t);
457 }
458
459 /* Build the Win32 namespace path to the specified @dentry when extracted.
460  *
461  * The path is saved in ctx->pathbuf and will be null terminated.
462  *
463  * XXX: We could get rid of this if it wasn't needed for the file encryption
464  * APIs.  */
465 static void
466 build_win32_extraction_path(const struct wim_dentry *dentry,
467                             struct win32_apply_ctx *ctx)
468 {
469         build_extraction_path(dentry, ctx);
470
471         /* Prepend target_ntpath to our relative path, then change \??\ into \\?\  */
472
473         memmove(ctx->pathbuf.Buffer +
474                         (ctx->target_ntpath.Length / sizeof(wchar_t)) + 1,
475                 ctx->pathbuf.Buffer, ctx->pathbuf.Length);
476         memcpy(ctx->pathbuf.Buffer, ctx->target_ntpath.Buffer,
477                 ctx->target_ntpath.Length);
478         ctx->pathbuf.Buffer[ctx->target_ntpath.Length / sizeof(wchar_t)] = L'\\';
479         ctx->pathbuf.Length += ctx->target_ntpath.Length + sizeof(wchar_t);
480         ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)] = L'\0';
481
482         wimlib_assert(ctx->pathbuf.Length >= 4 * sizeof(wchar_t) &&
483                       !wmemcmp(ctx->pathbuf.Buffer, L"\\??\\", 4));
484
485         ctx->pathbuf.Buffer[1] = L'\\';
486
487 }
488
489 /* Returns a "printable" representation of the last relative NT path that was
490  * constructed with build_extraction_path() or build_extraction_path_with_ads().
491  *
492  * This will be overwritten by the next call to this function.  */
493 static const wchar_t *
494 current_path(struct win32_apply_ctx *ctx)
495 {
496         wchar_t *p = ctx->print_buffer;
497
498         p = wmempcpy(p, ctx->common.target, ctx->common.target_nchars);
499         *p++ = L'\\';
500         p = wmempcpy(p, ctx->pathbuf.Buffer, ctx->pathbuf.Length / sizeof(wchar_t));
501         *p = L'\0';
502         return ctx->print_buffer;
503 }
504
505 /*
506  * Ensures the target directory exists and opens a handle to it, in preparation
507  * of using paths relative to it.
508  */
509 static int
510 prepare_target(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
511 {
512         int ret;
513         NTSTATUS status;
514         size_t path_max;
515
516         /* Open handle to the target directory (possibly creating it).  */
517
518         ret = win32_path_to_nt_path(ctx->common.target, &ctx->target_ntpath);
519         if (ret)
520                 return ret;
521
522         ctx->attr.Length = sizeof(ctx->attr);
523         ctx->attr.ObjectName = &ctx->target_ntpath;
524
525         status = (*func_NtCreateFile)(&ctx->h_target,
526                                       FILE_TRAVERSE,
527                                       &ctx->attr,
528                                       &ctx->iosb,
529                                       NULL,
530                                       0,
531                                       FILE_SHARE_VALID_FLAGS,
532                                       FILE_OPEN_IF,
533                                       FILE_DIRECTORY_FILE |
534                                               FILE_OPEN_REPARSE_POINT |
535                                               FILE_OPEN_FOR_BACKUP_INTENT,
536                                       NULL,
537                                       0);
538
539         if (!NT_SUCCESS(status)) {
540                 set_errno_from_nt_status(status);
541                 ERROR_WITH_ERRNO("Can't open or create directory \"%ls\" "
542                                  "(status=0x%08"PRIx32")",
543                                  ctx->common.target, (u32)status);
544                 return WIMLIB_ERR_OPENDIR;
545         }
546
547         path_max = compute_path_max(dentry_list);
548
549         /* Add some extra for building Win32 paths for the file encryption APIs
550          * ...  */
551         path_max += 2 + (ctx->target_ntpath.Length / sizeof(wchar_t));
552
553         ctx->pathbuf.MaximumLength = path_max * sizeof(wchar_t);
554         ctx->pathbuf.Buffer = MALLOC(ctx->pathbuf.MaximumLength);
555         if (!ctx->pathbuf.Buffer)
556                 return WIMLIB_ERR_NOMEM;
557
558         ctx->attr.RootDirectory = ctx->h_target;
559         ctx->attr.ObjectName = &ctx->pathbuf;
560
561         ctx->print_buffer = MALLOC((ctx->common.target_nchars + 1 + path_max + 1) *
562                                    sizeof(wchar_t));
563         if (!ctx->print_buffer)
564                 return WIMLIB_ERR_NOMEM;
565
566         return 0;
567 }
568
569 /* When creating an inode that will have a short (DOS) name, we create it using
570  * the long name associated with the short name.  This ensures that the short
571  * name gets associated with the correct long name.  */
572 static const struct wim_dentry *
573 first_extraction_alias(const struct wim_inode *inode)
574 {
575         const struct list_head *next = inode->i_extraction_aliases.next;
576         const struct wim_dentry *dentry;
577
578         do {
579                 dentry = list_entry(next, struct wim_dentry,
580                                     d_extraction_alias_node);
581                 if (dentry_has_short_name(dentry))
582                         break;
583                 next = next->next;
584         } while (next != &inode->i_extraction_aliases);
585         return dentry;
586 }
587
588 /*
589  * Set or clear FILE_ATTRIBUTE_COMPRESSED if the inherited value is different
590  * from the desired value.
591  *
592  * Note that you can NOT override the inherited value of
593  * FILE_ATTRIBUTE_COMPRESSED directly with NtCreateFile().
594  */
595 static int
596 adjust_compression_attribute(HANDLE h, const struct wim_dentry *dentry,
597                              struct win32_apply_ctx *ctx)
598 {
599         const bool compressed = (dentry->d_inode->i_attributes &
600                                  FILE_ATTRIBUTE_COMPRESSED);
601
602         if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
603                 return 0;
604
605         if (!ctx->common.supported_features.compressed_files)
606                 return 0;
607
608         FILE_BASIC_INFORMATION info;
609         NTSTATUS status;
610         USHORT compression_state;
611
612         /* Get current attributes  */
613         status = (*func_NtQueryInformationFile)(h, &ctx->iosb,
614                                                 &info, sizeof(info),
615                                                 FileBasicInformation);
616         if (NT_SUCCESS(status) &&
617             compressed == !!(info.FileAttributes & FILE_ATTRIBUTE_COMPRESSED))
618         {
619                 /* Nothing needs to be done.  */
620                 return 0;
621         }
622
623         /* Set the new compression state  */
624
625         if (compressed)
626                 compression_state = COMPRESSION_FORMAT_DEFAULT;
627         else
628                 compression_state = COMPRESSION_FORMAT_NONE;
629
630         status = (*func_NtFsControlFile)(h,
631                                          NULL,
632                                          NULL,
633                                          NULL,
634                                          &ctx->iosb,
635                                          FSCTL_SET_COMPRESSION,
636                                          &compression_state,
637                                          sizeof(USHORT),
638                                          NULL,
639                                          0);
640         if (NT_SUCCESS(status))
641                 return 0;
642
643         set_errno_from_nt_status(status);
644         ERROR_WITH_ERRNO("Can't %s compression attribute on \"%ls\" "
645                          "(status=0x%08"PRIx32")",
646                          (compressed ? "set" : "clear"),
647                          current_path(ctx), status);
648         return WIMLIB_ERR_SET_ATTRIBUTES;
649 }
650
651 /*
652  * Clear FILE_ATTRIBUTE_ENCRYPTED if the file or directory is not supposed to be
653  * encrypted.
654  *
655  * You can provide FILE_ATTRIBUTE_ENCRYPTED to NtCreateFile() to set it on the
656  * created file.  However, the file or directory will otherwise default to the
657  * encryption state of the parent directory.  This function works around this
658  * limitation by using DecryptFile() to remove FILE_ATTRIBUTE_ENCRYPTED on files
659  * (and directories) that are not supposed to have it set.
660  *
661  * Regardless of whether it succeeds or fails, this function may close the
662  * handle to the file.  If it does, it sets it to NULL.
663  */
664 static int
665 maybe_clear_encryption_attribute(HANDLE *h_ptr, const struct wim_dentry *dentry,
666                                  struct win32_apply_ctx *ctx)
667 {
668         if (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)
669                 return 0;
670
671         if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
672                 return 0;
673
674         if (!ctx->common.supported_features.encrypted_files)
675                 return 0;
676
677         FILE_BASIC_INFORMATION info;
678         NTSTATUS status;
679         BOOL bret;
680
681         /* Get current attributes  */
682         status = (*func_NtQueryInformationFile)(*h_ptr, &ctx->iosb,
683                                                 &info, sizeof(info),
684                                                 FileBasicInformation);
685         if (NT_SUCCESS(status) &&
686             !(info.FileAttributes & FILE_ATTRIBUTE_ENCRYPTED))
687         {
688                 /* Nothing needs to be done.  */
689                 return 0;
690         }
691
692         /* Set the new encryption state  */
693
694         /* Due to Windows' crappy file encryption APIs, we need to close the
695          * handle to the file so we don't get ERROR_SHARING_VIOLATION.  We also
696          * hack together a Win32 path, although we will use the \\?\ prefix so
697          * it will actually be a NT path in disguise...  */
698         (*func_NtClose)(*h_ptr);
699         *h_ptr = NULL;
700
701         build_win32_extraction_path(dentry, ctx);
702
703         bret = DecryptFile(ctx->pathbuf.Buffer, 0);
704
705         /* Restore the NT namespace path  */
706         build_extraction_path(dentry, ctx);
707
708         if (!bret) {
709                 DWORD err = GetLastError();
710                 set_errno_from_win32_error(err);
711                 ERROR_WITH_ERRNO("Can't decrypt file \"%ls\" (err=%"PRIu32")",
712                                   current_path(ctx), (u32)err);
713                 return WIMLIB_ERR_SET_ATTRIBUTES;
714         }
715         return 0;
716 }
717
718 /* Set the short name on the open file @h which has been created at the location
719  * indicated by @dentry.
720  *
721  * Note that this may add, change, or remove the short name.
722  *
723  * @h must be opened with DELETE access.
724  *
725  * Returns 0 or WIMLIB_ERR_SET_SHORT_NAME.  The latter only happens in
726  * STRICT_SHORT_NAMES mode.
727  */
728 static int
729 set_short_name(HANDLE h, const struct wim_dentry *dentry,
730                struct win32_apply_ctx *ctx)
731 {
732         size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
733                          dentry->short_name_nbytes;
734         u8 buf[bufsize] _aligned_attribute(8);
735         FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
736         NTSTATUS status;
737
738         info->FileNameLength = dentry->short_name_nbytes;
739         memcpy(info->FileName, dentry->short_name, dentry->short_name_nbytes);
740
741         status = (*func_NtSetInformationFile)(h, &ctx->iosb, info, bufsize,
742                                               FileShortNameInformation);
743         if (NT_SUCCESS(status))
744                 return 0;
745
746         /* By default, failure to set short names is not an error (since short
747          * names aren't too important anymore...).  */
748         if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES))
749                 return 0;
750
751         if (status == STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME) {
752                 if (dentry->short_name_nbytes == 0)
753                         return 0;
754                 ERROR("Can't extract short name when short "
755                       "names are not enabled on the volume!");
756         } else {
757                 ERROR("Can't set short name on \"%ls\" (status=0x%08"PRIx32")",
758                       current_path(ctx), (u32)status);
759         }
760         return WIMLIB_ERR_SET_SHORT_NAME;
761 }
762
763 /*
764  * A wrapper around NtCreateFile() to make it slightly more usable...
765  * This uses the path currently constructed in ctx->pathbuf.
766  *
767  * Also, we always specify FILE_OPEN_FOR_BACKUP_INTENT and
768  * FILE_OPEN_REPARSE_POINT.
769  */
770 static NTSTATUS
771 do_create_file(PHANDLE FileHandle,
772                ACCESS_MASK DesiredAccess,
773                PLARGE_INTEGER AllocationSize,
774                ULONG FileAttributes,
775                ULONG CreateDisposition,
776                ULONG CreateOptions,
777                struct win32_apply_ctx *ctx)
778 {
779         return (*func_NtCreateFile)(FileHandle,
780                                     DesiredAccess,
781                                     &ctx->attr,
782                                     &ctx->iosb,
783                                     AllocationSize,
784                                     FileAttributes,
785                                     FILE_SHARE_VALID_FLAGS,
786                                     CreateDisposition,
787                                     CreateOptions |
788                                         FILE_OPEN_FOR_BACKUP_INTENT |
789                                         FILE_OPEN_REPARSE_POINT,
790                                     NULL,
791                                     0);
792 }
793
794 /* Like do_create_file(), but builds the extraction path of the @dentry first.
795  */
796 static NTSTATUS
797 create_file(PHANDLE FileHandle,
798             ACCESS_MASK DesiredAccess,
799             PLARGE_INTEGER AllocationSize,
800             ULONG FileAttributes,
801             ULONG CreateDisposition,
802             ULONG CreateOptions,
803             const struct wim_dentry *dentry,
804             struct win32_apply_ctx *ctx)
805 {
806         build_extraction_path(dentry, ctx);
807         return do_create_file(FileHandle,
808                               DesiredAccess,
809                               AllocationSize,
810                               FileAttributes,
811                               CreateDisposition,
812                               CreateOptions,
813                               ctx);
814 }
815
816 /* Create empty named data streams.
817  *
818  * Since these won't have 'struct wim_lookup_table_entry's, they won't show up
819  * in the call to extract_stream_list().  Hence the need for the special case.
820  */
821 static int
822 create_any_empty_ads(const struct wim_dentry *dentry,
823                      struct win32_apply_ctx *ctx)
824 {
825         const struct wim_inode *inode = dentry->d_inode;
826         LARGE_INTEGER allocation_size;
827         bool path_modified = false;
828         int ret = 0;
829
830         if (!ctx->common.supported_features.named_data_streams)
831                 return 0;
832
833         for (u16 i = 0; i < inode->i_num_ads; i++) {
834                 const struct wim_ads_entry *entry;
835                 NTSTATUS status;
836                 HANDLE h;
837
838                 entry = &inode->i_ads_entries[i];
839
840                 /* Not named?  */
841                 if (!entry->stream_name_nbytes)
842                         continue;
843
844                 /* Not empty?  */
845                 if (entry->lte)
846                         continue;
847
848                 /* Probably setting the allocation size to 0 has no effect, but
849                  * we might as well try.  */
850                 allocation_size.QuadPart = 0;
851
852                 build_extraction_path_with_ads(dentry, ctx,
853                                                entry->stream_name,
854                                                entry->stream_name_nbytes /
855                                                         sizeof(wchar_t));
856                 path_modified = true;
857                 status = do_create_file(&h, FILE_WRITE_DATA, &allocation_size,
858                                         0, FILE_SUPERSEDE, 0, ctx);
859                 if (!NT_SUCCESS(status)) {
860                         set_errno_from_nt_status(status);
861                         ERROR_WITH_ERRNO("Can't create \"%ls\" "
862                                          "(status=0x%08"PRIx32")",
863                                          current_path(ctx), (u32)status);
864                         ret = WIMLIB_ERR_OPEN;
865                         break;
866                 }
867                 (*func_NtClose)(h);
868         }
869         /* Restore the path to the dentry itself  */
870         if (path_modified)
871                 build_extraction_path(dentry, ctx);
872         return ret;
873 }
874
875 /*
876  * Creates the directory named by @dentry, or uses an existing directory at that
877  * location.  If necessary, sets the short name and/or fixes compression and
878  * encryption attributes.
879  *
880  * Returns 0, WIMLIB_ERR_MKDIR, or WIMLIB_ERR_SET_SHORT_NAME.
881  */
882 static int
883 create_directory(const struct wim_dentry *dentry,
884                  struct win32_apply_ctx *ctx)
885 {
886         HANDLE h;
887         NTSTATUS status;
888         int ret;
889         ULONG attrib;
890
891         /* Special attributes:
892          *
893          * Use FILE_ATTRIBUTE_ENCRYPTED if the directory needs to have it set.
894          * This doesn't work for FILE_ATTRIBUTE_COMPRESSED (unfortunately).
895          *
896          * Don't specify FILE_ATTRIBUTE_DIRECTORY; it gets set anyway as a
897          * result of the FILE_DIRECTORY_FILE option.  */
898         attrib = (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED);
899
900         /* DELETE is needed for set_short_name().
901          * GENERIC_READ and GENERIC_WRITE are needed for
902          * adjust_compression_attribute().  */
903         status = create_file(&h, GENERIC_READ | GENERIC_WRITE | DELETE, NULL,
904                              attrib, FILE_OPEN_IF, FILE_DIRECTORY_FILE,
905                              dentry, ctx);
906         if (!NT_SUCCESS(status)) {
907                 set_errno_from_nt_status(status);
908                 ERROR_WITH_ERRNO("Can't create directory \"%ls\" "
909                                  "(status=0x%08"PRIx32")",
910                                  current_path(ctx), (u32)status);
911                 return WIMLIB_ERR_MKDIR;
912         }
913
914         ret = set_short_name(h, dentry, ctx);
915
916         if (!ret)
917                 ret = adjust_compression_attribute(h, dentry, ctx);
918
919         if (!ret)
920                 ret = maybe_clear_encryption_attribute(&h, dentry, ctx);
921                 /* May close the handle!!! */
922
923         if (h)
924                 (*func_NtClose)(h);
925         return ret;
926 }
927
928 /*
929  * Create all the directories being extracted, other than the target directory
930  * itself.
931  *
932  * Note: we don't honor directory hard links.  However, we don't allow them to
933  * exist in WIM images anyway (see inode_fixup.c).
934  */
935 static int
936 create_directories(struct list_head *dentry_list,
937                    struct win32_apply_ctx *ctx)
938 {
939         const struct wim_dentry *dentry;
940         int ret;
941
942         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
943
944                 if (!(dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY))
945                         continue;
946
947                 /* Note: Here we include files with
948                  * FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT, but we
949                  * wait until later to actually set the reparse data.  */
950
951                 /* If the root dentry is being extracted, it was already done so
952                  * in prepare_target().  */
953                 if (dentry_is_root(dentry))
954                         continue;
955
956                 ret = create_directory(dentry, ctx);
957                 if (ret)
958                         return ret;
959
960                 ret = create_any_empty_ads(dentry, ctx);
961                 if (ret)
962                         return ret;
963         }
964         return 0;
965 }
966
967 /*
968  * Creates the nondirectory file named by @dentry.
969  *
970  * On success, returns an open handle to the file in @h_ret, with GENERIC_READ,
971  * GENERIC_WRITE, and DELETE access.  Also, the path to the file will be saved
972  * in ctx->pathbuf.  On failure, returns WIMLIB_ERR_OPEN.
973  */
974 static int
975 create_nondirectory_inode(HANDLE *h_ret, const struct wim_dentry *dentry,
976                           struct win32_apply_ctx *ctx)
977 {
978         const struct wim_inode *inode;
979         ULONG attrib;
980         NTSTATUS status;
981         bool retried = false;
982
983         inode = dentry->d_inode;
984
985         /* If the file already exists and has FILE_ATTRIBUTE_SYSTEM and/or
986          * FILE_ATTRIBUTE_HIDDEN, these must be specified in order to supersede
987          * the file.
988          *
989          * Normally the user shouldn't be trying to overwrite such files anyway,
990          * but we at least provide FILE_ATTRIBUTE_SYSTEM and
991          * FILE_ATTRIBUTE_HIDDEN if the WIM inode has those attributes so that
992          * we catch the case where the user extracts the same files to the same
993          * location more than one time.
994          *
995          * Also specify FILE_ATTRIBUTE_ENCRYPTED if the file needs to be
996          * encrypted.
997          *
998          * In NO_ATTRIBUTES mode just don't specify any attributes at all.
999          */
1000         if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES) {
1001                 attrib = 0;
1002         } else {
1003                 attrib = (inode->i_attributes & (FILE_ATTRIBUTE_SYSTEM |
1004                                                  FILE_ATTRIBUTE_HIDDEN |
1005                                                  FILE_ATTRIBUTE_ENCRYPTED));
1006         }
1007         build_extraction_path(dentry, ctx);
1008 retry:
1009         status = do_create_file(h_ret, GENERIC_READ | GENERIC_WRITE | DELETE,
1010                                 NULL, attrib, FILE_SUPERSEDE,
1011                                 FILE_NON_DIRECTORY_FILE, ctx);
1012         if (NT_SUCCESS(status)) {
1013                 int ret;
1014
1015                 ret = adjust_compression_attribute(*h_ret, dentry, ctx);
1016                 if (ret) {
1017                         (*func_NtClose)(*h_ret);
1018                         return ret;
1019                 }
1020
1021                 ret = maybe_clear_encryption_attribute(h_ret, dentry, ctx);
1022                 /* May close the handle!!! */
1023
1024                 if (ret) {
1025                         if (*h_ret)
1026                                 (*func_NtClose)(*h_ret);
1027                         return ret;
1028                 }
1029
1030                 if (!*h_ret) {
1031                         /* Re-open the handle so that we can return it on
1032                          * success.  */
1033                         status = do_create_file(h_ret,
1034                                                 GENERIC_READ |
1035                                                         GENERIC_WRITE | DELETE,
1036                                                 NULL, 0, FILE_OPEN,
1037                                                 FILE_NON_DIRECTORY_FILE, ctx);
1038                         if (!NT_SUCCESS(status))
1039                                 goto fail;
1040                 }
1041
1042                 ret = create_any_empty_ads(dentry, ctx);
1043                 if (ret) {
1044                         (*func_NtClose)(*h_ret);
1045                         return ret;
1046                 }
1047                 return 0;
1048         }
1049
1050         if (status == STATUS_ACCESS_DENIED && !retried) {
1051                 /* We also can't supersede an existing file that has
1052                  * FILE_ATTRIBUTE_READONLY set; doing so causes NtCreateFile()
1053                  * to return STATUS_ACCESS_DENIED .  The only workaround seems
1054                  * to be to explicitly remove FILE_ATTRIBUTE_READONLY on the
1055                  * existing file, then try again.  */
1056
1057                 FILE_BASIC_INFORMATION info;
1058                 HANDLE h;
1059
1060                 status = do_create_file(&h, FILE_WRITE_ATTRIBUTES, NULL, 0,
1061                                         FILE_OPEN, FILE_NON_DIRECTORY_FILE, ctx);
1062                 if (!NT_SUCCESS(status))
1063                         goto fail;
1064
1065                 memset(&info, 0, sizeof(info));
1066                 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1067
1068                 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1069                                                       &info, sizeof(info),
1070                                                       FileBasicInformation);
1071                 (*func_NtClose)(h);
1072                 if (!NT_SUCCESS(status))
1073                         goto fail;
1074                 retried = true;
1075                 goto retry;
1076         }
1077 fail:
1078         set_errno_from_nt_status(status);
1079         ERROR_WITH_ERRNO("Can't create file \"%ls\" (status=0x%08"PRIx32")",
1080                          current_path(ctx), (u32)status);
1081         return WIMLIB_ERR_OPEN;
1082 }
1083
1084 /* Creates a hard link at the location named by @dentry to the file represented
1085  * by the open handle @h.  Or, if the target volume does not support hard links,
1086  * create a separate file instead.  */
1087 static int
1088 create_link(HANDLE h, const struct wim_dentry *dentry,
1089             struct win32_apply_ctx *ctx)
1090 {
1091         if (ctx->common.supported_features.hard_links) {
1092
1093                 build_extraction_path(dentry, ctx);
1094
1095                 size_t bufsize = offsetof(FILE_LINK_INFORMATION, FileName) +
1096                                  ctx->pathbuf.Length + sizeof(wchar_t);
1097                 u8 buf[bufsize] _aligned_attribute(8);
1098                 FILE_LINK_INFORMATION *info = (FILE_LINK_INFORMATION *)buf;
1099                 NTSTATUS status;
1100
1101                 info->ReplaceIfExists = TRUE;
1102                 info->RootDirectory = ctx->attr.RootDirectory;
1103                 info->FileNameLength = ctx->pathbuf.Length;
1104                 memcpy(info->FileName, ctx->pathbuf.Buffer, ctx->pathbuf.Length);
1105                 info->FileName[info->FileNameLength / 2] = L'\0';
1106
1107                 /* Note: the null terminator isn't actually necessary,
1108                  * but if you don't add the extra character, you get
1109                  * STATUS_INFO_LENGTH_MISMATCH when FileNameLength
1110                  * happens to be 2  */
1111
1112                 status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1113                                                       info, bufsize,
1114                                                       FileLinkInformation);
1115                 if (NT_SUCCESS(status))
1116                         return 0;
1117                 ERROR("Failed to create link \"%ls\" (status=0x%08"PRIx32")",
1118                       current_path(ctx), (u32)status);
1119                 return WIMLIB_ERR_LINK;
1120         } else {
1121                 HANDLE h2;
1122                 int ret;
1123
1124                 ret = create_nondirectory_inode(&h2, dentry, ctx);
1125                 if (ret)
1126                         return ret;
1127
1128                 (*func_NtClose)(h2);
1129                 return 0;
1130         }
1131 }
1132
1133 /* Given an inode (represented by the open handle @h) for which one link has
1134  * been created (named by @first_dentry), create the other links.
1135  *
1136  * Or, if the target volume does not support hard links, create separate files.
1137  *
1138  * Note: This uses ctx->pathbuf and does not reset it.
1139  */
1140 static int
1141 create_links(HANDLE h, const struct wim_dentry *first_dentry,
1142              struct win32_apply_ctx *ctx)
1143 {
1144         const struct wim_inode *inode;
1145         const struct list_head *next;
1146         const struct wim_dentry *dentry;
1147         int ret;
1148
1149         inode = first_dentry->d_inode;
1150         next = inode->i_extraction_aliases.next;
1151         do {
1152                 dentry = list_entry(next, struct wim_dentry,
1153                                     d_extraction_alias_node);
1154                 if (dentry != first_dentry) {
1155                         ret = create_link(h, dentry, ctx);
1156                         if (ret)
1157                                 return ret;
1158                 }
1159                 next = next->next;
1160         } while (next != &inode->i_extraction_aliases);
1161         return 0;
1162 }
1163
1164 /* Create a nondirectory file, including all links.  */
1165 static int
1166 create_nondirectory(const struct wim_inode *inode, struct win32_apply_ctx *ctx)
1167 {
1168         const struct wim_dentry *first_dentry;
1169         HANDLE h;
1170         int ret;
1171
1172         first_dentry = first_extraction_alias(inode);
1173
1174         /* Create first link.  */
1175         ret = create_nondirectory_inode(&h, first_dentry, ctx);
1176         if (ret)
1177                 return ret;
1178
1179         /* Set short name.  */
1180         ret = set_short_name(h, first_dentry, ctx);
1181
1182         /* Create additional links, OR if hard links are not supported just
1183          * create more files.  */
1184         if (!ret)
1185                 ret = create_links(h, first_dentry, ctx);
1186
1187         (*func_NtClose)(h);
1188         return ret;
1189 }
1190
1191 /* Create all the nondirectory files being extracted, including all aliases
1192  * (hard links).  */
1193 static int
1194 create_nondirectories(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1195 {
1196         const struct wim_dentry *dentry;
1197         const struct wim_inode *inode;
1198         int ret;
1199
1200         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1201                 inode = dentry->d_inode;
1202                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1203                         continue;
1204                 /* Call create_nondirectory() only once per inode  */
1205                 if (dentry != inode_first_extraction_dentry(inode))
1206                         continue;
1207                 ret = create_nondirectory(inode, ctx);
1208                 if (ret)
1209                         return ret;
1210         }
1211         return 0;
1212 }
1213
1214 static void
1215 close_handles(struct win32_apply_ctx *ctx)
1216 {
1217         for (unsigned i = 0; i < ctx->num_open_handles; i++)
1218                 (*func_NtClose)(ctx->open_handles[i]);
1219 }
1220
1221 /* Prepare to read the next stream, which has size @stream_size, into an
1222  * in-memory buffer.  */
1223 static int
1224 prepare_data_buffer(struct win32_apply_ctx *ctx, u64 stream_size)
1225 {
1226         if (stream_size > ctx->data_buffer_size) {
1227                 /* Larger buffer needed.  */
1228                 void *new_buffer;
1229                 if ((size_t)stream_size != stream_size)
1230                         return WIMLIB_ERR_NOMEM;
1231                 new_buffer = REALLOC(ctx->data_buffer, stream_size);
1232                 if (!new_buffer)
1233                         return WIMLIB_ERR_NOMEM;
1234                 ctx->data_buffer = new_buffer;
1235                 ctx->data_buffer_size = stream_size;
1236         }
1237         /* On the first call this changes data_buffer_ptr from NULL, which tells
1238          * extract_chunk() that the data buffer needs to be filled while reading
1239          * the stream data.  */
1240         ctx->data_buffer_ptr = ctx->data_buffer;
1241         return 0;
1242 }
1243
1244 static int
1245 begin_extract_stream_instance(const struct wim_lookup_table_entry *stream,
1246                               struct wim_dentry *dentry,
1247                               const wchar_t *stream_name,
1248                               struct win32_apply_ctx *ctx)
1249 {
1250         const struct wim_inode *inode = dentry->d_inode;
1251         size_t stream_name_nchars = 0;
1252         FILE_ALLOCATION_INFORMATION alloc_info;
1253         HANDLE h;
1254         NTSTATUS status;
1255
1256         if (unlikely(stream_name))
1257                 stream_name_nchars = wcslen(stream_name);
1258
1259         if (unlikely(stream_name_nchars)) {
1260                 build_extraction_path_with_ads(dentry, ctx,
1261                                                stream_name, stream_name_nchars);
1262         } else {
1263                 build_extraction_path(dentry, ctx);
1264         }
1265
1266         /* Reparse point?  */
1267         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1268             && (stream_name_nchars == 0))
1269         {
1270                 if (!ctx->common.supported_features.reparse_points)
1271                         return 0;
1272
1273                 /* We can't write the reparse stream directly; we must set it
1274                  * with FSCTL_SET_REPARSE_POINT, which requires that all the
1275                  * data be available.  So, stage the data in a buffer.  */
1276
1277                 list_add_tail(&dentry->tmp_list, &ctx->reparse_dentries);
1278                 return prepare_data_buffer(ctx, stream->size);
1279         }
1280
1281         /* Encrypted file?  */
1282         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)
1283             && (stream_name_nchars == 0))
1284         {
1285                 if (!ctx->common.supported_features.encrypted_files)
1286                         return 0;
1287
1288                 /* We can't write encrypted file streams directly; we must use
1289                  * WriteEncryptedFileRaw(), which requires providing the data
1290                  * through a callback function.  This can't easily be combined
1291                  * with our own callback-based approach.
1292                  *
1293                  * The current workaround is to simply read the stream into
1294                  * memory and write the encrypted file from that.
1295                  *
1296                  * TODO: This isn't sufficient for extremely large encrypted
1297                  * files.  Perhaps we should create an extra thread to write
1298                  * such files...  */
1299                 list_add_tail(&dentry->tmp_list, &ctx->encrypted_dentries);
1300                 return prepare_data_buffer(ctx, stream->size);
1301         }
1302
1303         /* Extracting unnamed data stream in WIMBoot mode?  */
1304         if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)
1305             && (stream_name_nchars == 0)
1306             && (stream->resource_location == RESOURCE_IN_WIM)
1307             && (stream->rspec->wim == ctx->common.wim)
1308             && (stream->size == stream->rspec->uncompressed_size))
1309         {
1310                 int ret = calculate_dentry_full_path(dentry);
1311                 if (ret)
1312                         return ret;
1313                 if (in_prepopulate_list(dentry, ctx)) {
1314                         union wimlib_progress_info info;
1315
1316                         info.wimboot_exclude.path_in_wim = dentry->_full_path;
1317                         info.wimboot_exclude.extraction_path = current_path(ctx);
1318
1319                         ret = call_progress(ctx->common.progfunc,
1320                                             WIMLIB_PROGRESS_MSG_WIMBOOT_EXCLUDE,
1321                                             &info, ctx->common.progctx);
1322                         FREE(dentry->_full_path);
1323                         dentry->_full_path = NULL;
1324                         if (ret)
1325                                 return ret;
1326                         /* Go on and open the file for normal extraction.  */
1327                 } else {
1328                         FREE(dentry->_full_path);
1329                         dentry->_full_path = NULL;
1330                         return wimboot_set_pointer(&ctx->attr,
1331                                                    current_path(ctx),
1332                                                    stream,
1333                                                    ctx->wimboot.data_source_id,
1334                                                    ctx->wimboot.wim_lookup_table_hash,
1335                                                    ctx->wimboot.wof_running);
1336                 }
1337         }
1338
1339         if (ctx->num_open_handles == MAX_OPEN_STREAMS) {
1340                 /* XXX: Fix this.  But because of the checks in
1341                  * extract_stream_list(), this can now only happen on a
1342                  * filesystem that does not support hard links.  */
1343                 ERROR("Can't extract data: too many open files!");
1344                 return WIMLIB_ERR_UNSUPPORTED;
1345         }
1346
1347         /* Open a new handle  */
1348         status = do_create_file(&h,
1349                                 FILE_WRITE_DATA | SYNCHRONIZE,
1350                                 NULL, 0, FILE_OPEN_IF,
1351                                 FILE_SEQUENTIAL_ONLY |
1352                                         FILE_SYNCHRONOUS_IO_NONALERT,
1353                                 ctx);
1354         if (!NT_SUCCESS(status)) {
1355                 set_errno_from_nt_status(status);
1356                 ERROR_WITH_ERRNO("Can't open \"%ls\" for writing "
1357                                  "(status=0x%08"PRIx32")",
1358                                  current_path(ctx), (u32)status);
1359                 return WIMLIB_ERR_OPEN;
1360         }
1361
1362         ctx->open_handles[ctx->num_open_handles++] = h;
1363
1364         /* Allocate space for the data.  */
1365         alloc_info.AllocationSize.QuadPart = stream->size;
1366         (*func_NtSetInformationFile)(h, &ctx->iosb,
1367                                      &alloc_info, sizeof(alloc_info),
1368                                      FileAllocationInformation);
1369         return 0;
1370 }
1371
1372 /* Set the reparse data @rpbuf of length @rpbuflen on the extracted file
1373  * corresponding to the WIM dentry @dentry.  */
1374 static int
1375 do_set_reparse_data(const struct wim_dentry *dentry,
1376                     const void *rpbuf, u16 rpbuflen,
1377                     struct win32_apply_ctx *ctx)
1378 {
1379         NTSTATUS status;
1380         HANDLE h;
1381
1382         status = create_file(&h, GENERIC_WRITE, NULL,
1383                              0, FILE_OPEN, 0, dentry, ctx);
1384         if (!NT_SUCCESS(status))
1385                 goto fail;
1386
1387         status = (*func_NtFsControlFile)(h, NULL, NULL, NULL,
1388                                          &ctx->iosb, FSCTL_SET_REPARSE_POINT,
1389                                          (void *)rpbuf, rpbuflen,
1390                                          NULL, 0);
1391         (*func_NtClose)(h);
1392
1393         if (NT_SUCCESS(status))
1394                 return 0;
1395
1396         /* On Windows, by default only the Administrator can create symbolic
1397          * links for some reason.  By default we just issue a warning if this
1398          * appears to be the problem.  Use WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS
1399          * to get a hard error.  */
1400         if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS)
1401             && (status == STATUS_PRIVILEGE_NOT_HELD ||
1402                 status == STATUS_ACCESS_DENIED)
1403             && (dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1404                 dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1405         {
1406                 WARNING("Can't create symbolic link \"%ls\"!              \n"
1407                         "          (Need Administrator rights, or at least "
1408                         "the\n"
1409                         "          SeCreateSymbolicLink privilege.)",
1410                         current_path(ctx));
1411                 return 0;
1412         }
1413
1414 fail:
1415         set_errno_from_nt_status(status);
1416         ERROR_WITH_ERRNO("Can't set reparse data on \"%ls\" "
1417                          "(status=0x%08"PRIx32")",
1418                          current_path(ctx), (u32)status);
1419         return WIMLIB_ERR_SET_REPARSE_DATA;
1420 }
1421
1422 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1423  * pointer to the suffix of the path that begins with the device directly, such
1424  * as e:\Windows\System32.  */
1425 static const wchar_t *
1426 skip_nt_toplevel_component(const wchar_t *path, size_t path_nchars)
1427 {
1428         static const wchar_t * const dirs[] = {
1429                 L"\\??\\",
1430                 L"\\DosDevices\\",
1431                 L"\\Device\\",
1432         };
1433         size_t first_dir_len = 0;
1434         const wchar_t * const end = path + path_nchars;
1435
1436         for (size_t i = 0; i < ARRAY_LEN(dirs); i++) {
1437                 size_t len = wcslen(dirs[i]);
1438                 if (len <= (end - path) && !wcsnicmp(path, dirs[i], len)) {
1439                         first_dir_len = len;
1440                         break;
1441                 }
1442         }
1443         if (first_dir_len == 0)
1444                 return path;
1445         path += first_dir_len;
1446         while (path != end && *path == L'\\')
1447                 path++;
1448         return path;
1449 }
1450
1451 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
1452  * pointer to the suffix of the path that is device-relative, such as
1453  * Windows\System32.
1454  *
1455  * The path has an explicit length and is not necessarily null terminated.
1456  *
1457  * If the path just something like \??\e: then the returned pointer will point
1458  * just past the colon.  In this case the length of the result will be 0
1459  * characters.  */
1460 static const wchar_t *
1461 get_device_relative_path(const wchar_t *path, size_t path_nchars)
1462 {
1463         const wchar_t * const orig_path = path;
1464         const wchar_t * const end = path + path_nchars;
1465
1466         path = skip_nt_toplevel_component(path, path_nchars);
1467         if (path == orig_path)
1468                 return orig_path;
1469
1470         path = wmemchr(path, L'\\', (end - path));
1471         if (!path)
1472                 return end;
1473         do {
1474                 path++;
1475         } while (path != end && *path == L'\\');
1476         return path;
1477 }
1478
1479 /*
1480  * Given a reparse point buffer for a symbolic link or junction, adjust its
1481  * contents so that the target of the link is consistent with the new location
1482  * of the files.
1483  */
1484 static void
1485 try_rpfix(u8 *rpbuf, u16 *rpbuflen_p, struct win32_apply_ctx *ctx)
1486 {
1487         struct reparse_data rpdata;
1488         size_t orig_subst_name_nchars;
1489         const wchar_t *relpath;
1490         size_t relpath_nchars;
1491         size_t target_ntpath_nchars;
1492         size_t fixed_subst_name_nchars;
1493         const wchar_t *fixed_print_name;
1494         size_t fixed_print_name_nchars;
1495
1496         if (parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata)) {
1497                 /* Do nothing if the reparse data is invalid.  */
1498                 return;
1499         }
1500
1501         if (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
1502             (rpdata.rpflags & SYMBOLIC_LINK_RELATIVE))
1503         {
1504                 /* Do nothing if it's a relative symbolic link.  */
1505                 return;
1506         }
1507
1508         /* Build the new substitute name from the NT namespace path to the
1509          * target directory, then a path separator, then the "device relative"
1510          * part of the old substitute name.  */
1511
1512         orig_subst_name_nchars = rpdata.substitute_name_nbytes / sizeof(wchar_t);
1513
1514         relpath = get_device_relative_path(rpdata.substitute_name,
1515                                            orig_subst_name_nchars);
1516         relpath_nchars = orig_subst_name_nchars -
1517                          (relpath - rpdata.substitute_name);
1518
1519         target_ntpath_nchars = ctx->target_ntpath.Length / sizeof(wchar_t);
1520
1521         fixed_subst_name_nchars = target_ntpath_nchars;
1522         if (relpath_nchars)
1523                 fixed_subst_name_nchars += 1 + relpath_nchars;
1524         wchar_t fixed_subst_name[fixed_subst_name_nchars];
1525
1526         wmemcpy(fixed_subst_name, ctx->target_ntpath.Buffer,
1527                 target_ntpath_nchars);
1528         if (relpath_nchars) {
1529                 fixed_subst_name[target_ntpath_nchars] = L'\\';
1530                 wmemcpy(&fixed_subst_name[target_ntpath_nchars + 1],
1531                         relpath, relpath_nchars);
1532         }
1533         /* Doesn't need to be null-terminated.  */
1534
1535         /* Print name should be Win32, but not all NT names can even be
1536          * translated to Win32 names.  But we can at least delete the top-level
1537          * directory, such as \??\, and this will have the expected result in
1538          * the usual case.  */
1539         fixed_print_name = skip_nt_toplevel_component(fixed_subst_name,
1540                                                       fixed_subst_name_nchars);
1541         fixed_print_name_nchars = fixed_subst_name_nchars - (fixed_print_name -
1542                                                              fixed_subst_name);
1543
1544         rpdata.substitute_name = fixed_subst_name;
1545         rpdata.substitute_name_nbytes = fixed_subst_name_nchars * sizeof(wchar_t);
1546         rpdata.print_name = (wchar_t *)fixed_print_name;
1547         rpdata.print_name_nbytes = fixed_print_name_nchars * sizeof(wchar_t);
1548         make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
1549 }
1550
1551 /* Sets reparse data on the specified file.  This handles "fixing" the targets
1552  * of absolute symbolic links and junctions if WIMLIB_EXTRACT_FLAG_RPFIX was
1553  * specified.  */
1554 static int
1555 set_reparse_data(const struct wim_dentry *dentry,
1556                  const void *_rpbuf, u16 rpbuflen, struct win32_apply_ctx *ctx)
1557 {
1558         const struct wim_inode *inode = dentry->d_inode;
1559         const void *rpbuf = _rpbuf;
1560
1561         if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
1562             && !inode->i_not_rpfixed
1563             && (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1564                 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1565         {
1566                 memcpy(&ctx->rpfixbuf, _rpbuf, rpbuflen);
1567                 try_rpfix((u8 *)&ctx->rpfixbuf, &rpbuflen, ctx);
1568                 rpbuf = &ctx->rpfixbuf;
1569         }
1570         return do_set_reparse_data(dentry, rpbuf, rpbuflen, ctx);
1571
1572 }
1573
1574 /* Import the next block of raw encrypted data  */
1575 static DWORD WINAPI
1576 import_encrypted_data(PBYTE pbData, PVOID pvCallbackContext, PULONG Length)
1577 {
1578         struct win32_apply_ctx *ctx = pvCallbackContext;
1579         ULONG copy_len;
1580
1581         copy_len = min(ctx->encrypted_size - ctx->encrypted_offset, *Length);
1582         memcpy(pbData, &ctx->data_buffer[ctx->encrypted_offset], copy_len);
1583         ctx->encrypted_offset += copy_len;
1584         *Length = copy_len;
1585         return ERROR_SUCCESS;
1586 }
1587
1588 /* Write the raw encrypted data to the already-created file corresponding to
1589  * @dentry.
1590  *
1591  * The raw encrypted data is provided in ctx->data_buffer, and its size is
1592  * ctx->encrypted_size.  */
1593 static int
1594 extract_encrypted_file(const struct wim_dentry *dentry,
1595                        struct win32_apply_ctx *ctx)
1596 {
1597         void *rawctx;
1598         DWORD err;
1599
1600         /* Temporarily build a Win32 path for OpenEncryptedFileRaw()  */
1601         build_win32_extraction_path(dentry, ctx);
1602
1603         err = OpenEncryptedFileRaw(ctx->pathbuf.Buffer,
1604                                    CREATE_FOR_IMPORT, &rawctx);
1605
1606         /* Restore the NT namespace path  */
1607         build_extraction_path(dentry, ctx);
1608
1609         if (err != ERROR_SUCCESS) {
1610                 set_errno_from_win32_error(err);
1611                 ERROR_WITH_ERRNO("Can't open \"%ls\" for encrypted import "
1612                                  "(err=%"PRIu32")", current_path(ctx), (u32)err);
1613                 return WIMLIB_ERR_OPEN;
1614         }
1615
1616         ctx->encrypted_offset = 0;
1617
1618         err = WriteEncryptedFileRaw(import_encrypted_data, ctx, rawctx);
1619
1620         CloseEncryptedFileRaw(rawctx);
1621
1622         if (err != ERROR_SUCCESS) {
1623                 set_errno_from_win32_error(err);
1624                 ERROR_WITH_ERRNO("Can't import encrypted file \"%ls\" "
1625                                  "(err=%"PRIu32")", current_path(ctx), (u32)err);
1626                 return WIMLIB_ERR_WRITE;
1627         }
1628
1629         return 0;
1630 }
1631
1632 /* Called when starting to read a stream for extraction on Windows  */
1633 static int
1634 begin_extract_stream(struct wim_lookup_table_entry *stream, void *_ctx)
1635 {
1636         struct win32_apply_ctx *ctx = _ctx;
1637         const struct stream_owner *owners = stream_owners(stream);
1638         int ret;
1639
1640         ctx->num_open_handles = 0;
1641         ctx->data_buffer_ptr = NULL;
1642         INIT_LIST_HEAD(&ctx->reparse_dentries);
1643         INIT_LIST_HEAD(&ctx->encrypted_dentries);
1644
1645         for (u32 i = 0; i < stream->out_refcnt; i++) {
1646                 const struct wim_inode *inode = owners[i].inode;
1647                 const wchar_t *stream_name = owners[i].stream_name;
1648                 struct wim_dentry *dentry;
1649
1650                 /* A copy of the stream needs to be extracted to @inode.  */
1651
1652                 if (ctx->common.supported_features.hard_links) {
1653                         dentry = inode_first_extraction_dentry(inode);
1654                         ret = begin_extract_stream_instance(stream, dentry,
1655                                                             stream_name, ctx);
1656                         if (ret)
1657                                 goto fail;
1658                 } else {
1659                         /* Hard links not supported.  Extract the stream
1660                          * separately to each alias of the inode.  */
1661                         struct list_head *next;
1662
1663                         next = inode->i_extraction_aliases.next;
1664                         do {
1665                                 dentry = list_entry(next, struct wim_dentry,
1666                                                     d_extraction_alias_node);
1667                                 ret = begin_extract_stream_instance(stream,
1668                                                                     dentry,
1669                                                                     stream_name,
1670                                                                     ctx);
1671                                 if (ret)
1672                                         goto fail;
1673                                 next = next->next;
1674                         } while (next != &inode->i_extraction_aliases);
1675                 }
1676         }
1677
1678         return 0;
1679
1680 fail:
1681         close_handles(ctx);
1682         return ret;
1683 }
1684
1685 /* Called when the next chunk of a stream has been read for extraction on
1686  * Windows  */
1687 static int
1688 extract_chunk(const void *chunk, size_t size, void *_ctx)
1689 {
1690         struct win32_apply_ctx *ctx = _ctx;
1691
1692         /* Write the data chunk to each open handle  */
1693         for (unsigned i = 0; i < ctx->num_open_handles; i++) {
1694                 u8 *bufptr = (u8 *)chunk;
1695                 size_t bytes_remaining = size;
1696                 NTSTATUS status;
1697                 while (bytes_remaining) {
1698                         ULONG count = min(0xFFFFFFFF, bytes_remaining);
1699
1700                         status = (*func_NtWriteFile)(ctx->open_handles[i],
1701                                                      NULL, NULL, NULL,
1702                                                      &ctx->iosb, bufptr, count,
1703                                                      NULL, NULL);
1704                         if (!NT_SUCCESS(status)) {
1705                                 set_errno_from_nt_status(status);
1706                                 ERROR_WITH_ERRNO("Error writing data to target "
1707                                                  "volume (status=0x%08"PRIx32")",
1708                                                  (u32)status);
1709                                 return WIMLIB_ERR_WRITE;
1710                         }
1711                         bufptr += ctx->iosb.Information;
1712                         bytes_remaining -= ctx->iosb.Information;
1713                 }
1714         }
1715
1716         /* Copy the data chunk into the buffer (if needed)  */
1717         if (ctx->data_buffer_ptr)
1718                 ctx->data_buffer_ptr = mempcpy(ctx->data_buffer_ptr,
1719                                                chunk, size);
1720         return 0;
1721 }
1722
1723 /* Called when a stream has been fully read for extraction on Windows  */
1724 static int
1725 end_extract_stream(struct wim_lookup_table_entry *stream, int status, void *_ctx)
1726 {
1727         struct win32_apply_ctx *ctx = _ctx;
1728         int ret;
1729         const struct wim_dentry *dentry;
1730
1731         close_handles(ctx);
1732
1733         if (status)
1734                 return status;
1735
1736         if (likely(!ctx->data_buffer_ptr))
1737                 return 0;
1738
1739         if (!list_empty(&ctx->reparse_dentries)) {
1740                 if (stream->size > REPARSE_DATA_MAX_SIZE) {
1741                         dentry = list_first_entry(&ctx->reparse_dentries,
1742                                                   struct wim_dentry, tmp_list);
1743                         build_extraction_path(dentry, ctx);
1744                         ERROR("Reparse data of \"%ls\" has size "
1745                               "%"PRIu64" bytes (exceeds %u bytes)",
1746                               current_path(ctx), stream->size,
1747                               REPARSE_DATA_MAX_SIZE);
1748                         return WIMLIB_ERR_INVALID_REPARSE_DATA;
1749                 }
1750                 /* In the WIM format, reparse streams are just the reparse data
1751                  * and omit the header.  But we can reconstruct the header.  */
1752                 memcpy(ctx->rpbuf.rpdata, ctx->data_buffer, stream->size);
1753                 ctx->rpbuf.rpdatalen = stream->size;
1754                 ctx->rpbuf.rpreserved = 0;
1755                 list_for_each_entry(dentry, &ctx->reparse_dentries, tmp_list) {
1756                         ctx->rpbuf.rptag = dentry->d_inode->i_reparse_tag;
1757                         ret = set_reparse_data(dentry, &ctx->rpbuf,
1758                                                stream->size + REPARSE_DATA_OFFSET,
1759                                                ctx);
1760                         if (ret)
1761                                 return ret;
1762                 }
1763         }
1764
1765         if (!list_empty(&ctx->encrypted_dentries)) {
1766                 ctx->encrypted_size = stream->size;
1767                 list_for_each_entry(dentry, &ctx->encrypted_dentries, tmp_list) {
1768                         ret = extract_encrypted_file(dentry, ctx);
1769                         if (ret)
1770                                 return ret;
1771                 }
1772         }
1773
1774         return 0;
1775 }
1776
1777 /* Attributes that can't be set directly  */
1778 #define SPECIAL_ATTRIBUTES                      \
1779         (FILE_ATTRIBUTE_REPARSE_POINT   |       \
1780          FILE_ATTRIBUTE_DIRECTORY       |       \
1781          FILE_ATTRIBUTE_ENCRYPTED       |       \
1782          FILE_ATTRIBUTE_SPARSE_FILE     |       \
1783          FILE_ATTRIBUTE_COMPRESSED)
1784
1785 /* Set the security descriptor @desc, of @desc_size bytes, on the file with open
1786  * handle @h.  */
1787 static NTSTATUS
1788 set_security_descriptor(HANDLE h, const void *desc,
1789                         size_t desc_size, struct win32_apply_ctx *ctx)
1790 {
1791         SECURITY_INFORMATION info;
1792         NTSTATUS status;
1793
1794         /* We really just want to set entire the security descriptor as-is, but
1795          * all available APIs require specifying the specific parts of the
1796          * descriptor being set.  Start out by requesting all parts be set.  If
1797          * permissions problems are encountered, fall back to omitting some
1798          * parts (first the SACL, then the DACL, then the owner), unless the
1799          * WIMLIB_EXTRACT_FLAG_STRICT_ACLS flag has been enabled.  */
1800         info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
1801                DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION;
1802
1803         /* Prefer NtSetSecurityObject() to SetFileSecurity().  SetFileSecurity()
1804          * itself necessarily uses NtSetSecurityObject() as the latter is the
1805          * underlying system call for setting security information, but
1806          * SetFileSecurity() opens the handle with NtCreateFile() without
1807          * FILE_OPEN_FILE_BACKUP_INTENT.  Hence, access checks are done and due
1808          * to the Windows security model, even a process running as the
1809          * Administrator can have access denied.  (Of course, this not mentioned
1810          * in the MS "documentation".)  */
1811 retry:
1812         status = (*func_NtSetSecurityObject)(h, info, (PSECURITY_DESCRIPTOR)desc);
1813         if (NT_SUCCESS(status))
1814                 return status;
1815         /* Failed to set the requested parts of the security descriptor.  If the
1816          * error was permissions-related, try to set fewer parts of the security
1817          * descriptor, unless WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled.  */
1818         if ((status == STATUS_PRIVILEGE_NOT_HELD ||
1819              status == STATUS_ACCESS_DENIED) &&
1820             !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
1821         {
1822                 if (info & SACL_SECURITY_INFORMATION) {
1823                         info &= ~SACL_SECURITY_INFORMATION;
1824                         ctx->partial_security_descriptors++;
1825                         goto retry;
1826                 }
1827                 if (info & DACL_SECURITY_INFORMATION) {
1828                         info &= ~DACL_SECURITY_INFORMATION;
1829                         goto retry;
1830                 }
1831                 if (info & OWNER_SECURITY_INFORMATION) {
1832                         info &= ~OWNER_SECURITY_INFORMATION;
1833                         goto retry;
1834                 }
1835                 /* Nothing left except GROUP, and if we removed it we
1836                  * wouldn't have anything at all.  */
1837         }
1838
1839         /* No part of the security descriptor could be set, or
1840          * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled and the full security
1841          * descriptor could not be set.  */
1842         if (!(info & SACL_SECURITY_INFORMATION))
1843                 ctx->partial_security_descriptors--;
1844         ctx->no_security_descriptors++;
1845         return status;
1846 }
1847
1848 /* Set metadata on the open file @h from the WIM inode @inode.  */
1849 static int
1850 do_apply_metadata_to_file(HANDLE h, const struct wim_inode *inode,
1851                           struct win32_apply_ctx *ctx)
1852 {
1853         FILE_BASIC_INFORMATION info;
1854         NTSTATUS status;
1855
1856         /* Set security descriptor if present and not in NO_ACLS mode  */
1857         if (inode->i_security_id >= 0 &&
1858             !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
1859         {
1860                 const struct wim_security_data *sd;
1861                 const void *desc;
1862                 size_t desc_size;
1863
1864                 sd = wim_get_current_security_data(ctx->common.wim);
1865                 desc = sd->descriptors[inode->i_security_id];
1866                 desc_size = sd->sizes[inode->i_security_id];
1867
1868                 status = set_security_descriptor(h, desc, desc_size, ctx);
1869                 if (!NT_SUCCESS(status) &&
1870                     (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
1871                 {
1872                         set_errno_from_nt_status(status);
1873                         ERROR_WITH_ERRNO("Can't set security descriptor "
1874                                          "on \"%ls\" (status=0x%08"PRIx32")",
1875                                          current_path(ctx), (u32)status);
1876                         return WIMLIB_ERR_SET_SECURITY;
1877                 }
1878         }
1879
1880         /* Set attributes and timestamps  */
1881         info.CreationTime.QuadPart = inode->i_creation_time;
1882         info.LastAccessTime.QuadPart = inode->i_last_access_time;
1883         info.LastWriteTime.QuadPart = inode->i_last_write_time;
1884         info.ChangeTime.QuadPart = 0;
1885         if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
1886                 info.FileAttributes = 0;
1887         else
1888                 info.FileAttributes = inode->i_attributes & ~SPECIAL_ATTRIBUTES;
1889
1890         status = (*func_NtSetInformationFile)(h, &ctx->iosb,
1891                                               &info, sizeof(info),
1892                                               FileBasicInformation);
1893         /* On FAT volumes we get STATUS_INVALID_PARAMETER if we try to set
1894          * attributes on the root directory.  (Apparently because FAT doesn't
1895          * actually have a place to store those attributes!)  */
1896         if (!NT_SUCCESS(status)
1897             && !(status == STATUS_INVALID_PARAMETER &&
1898                  dentry_is_root(inode_first_extraction_dentry(inode))))
1899         {
1900                 set_errno_from_nt_status(status);
1901                 ERROR_WITH_ERRNO("Can't set basic metadata on \"%ls\" "
1902                                  "(status=0x%08"PRIx32")",
1903                                  current_path(ctx), (u32)status);
1904                 return WIMLIB_ERR_SET_ATTRIBUTES;
1905         }
1906
1907         return 0;
1908 }
1909
1910 static int
1911 apply_metadata_to_file(const struct wim_dentry *dentry,
1912                        struct win32_apply_ctx *ctx)
1913 {
1914         const struct wim_inode *inode = dentry->d_inode;
1915         DWORD perms;
1916         HANDLE h;
1917         NTSTATUS status;
1918         int ret;
1919
1920         perms = FILE_WRITE_ATTRIBUTES | WRITE_DAC |
1921                 WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
1922
1923         build_extraction_path(dentry, ctx);
1924
1925         /* Open a handle with as many relevant permissions as possible.  */
1926         while (!NT_SUCCESS(status = do_create_file(&h, perms, NULL,
1927                                                    0, FILE_OPEN, 0, ctx)))
1928         {
1929                 if (status == STATUS_PRIVILEGE_NOT_HELD ||
1930                     status == STATUS_ACCESS_DENIED)
1931                 {
1932                         if (perms & ACCESS_SYSTEM_SECURITY) {
1933                                 perms &= ~ACCESS_SYSTEM_SECURITY;
1934                                 continue;
1935                         }
1936                         if (perms & WRITE_DAC) {
1937                                 perms &= ~WRITE_DAC;
1938                                 continue;
1939                         }
1940                         if (perms & WRITE_OWNER) {
1941                                 perms &= ~WRITE_OWNER;
1942                                 continue;
1943                         }
1944                 }
1945                 set_errno_from_nt_status(status);
1946                 ERROR_WITH_ERRNO("Can't open \"%ls\" to set metadata "
1947                                  "(status=0x%08"PRIx32")",
1948                                  current_path(ctx), (u32)status);
1949                 return WIMLIB_ERR_OPEN;
1950         }
1951
1952         ret = do_apply_metadata_to_file(h, inode, ctx);
1953
1954         (*func_NtClose)(h);
1955
1956         return ret;
1957 }
1958
1959 static int
1960 apply_metadata(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1961 {
1962         const struct wim_dentry *dentry;
1963         int ret;
1964
1965         /* We go in reverse so that metadata is set on all a directory's
1966          * children before the directory itself.  This avoids any potential
1967          * problems with attributes, timestamps, or security descriptors.  */
1968         list_for_each_entry_reverse(dentry, dentry_list, d_extraction_list_node)
1969         {
1970                 ret = apply_metadata_to_file(dentry, ctx);
1971                 if (ret)
1972                         return ret;
1973         }
1974         return 0;
1975 }
1976
1977 /* Issue warnings about problems during the extraction for which warnings were
1978  * not already issued (due to the high number of potential warnings if we issued
1979  * them per-file).  */
1980 static void
1981 do_warnings(const struct win32_apply_ctx *ctx)
1982 {
1983         if (ctx->partial_security_descriptors == 0 &&
1984             ctx->no_security_descriptors == 0)
1985                 return;
1986
1987         WARNING("Extraction to \"%ls\" complete, but with one or more warnings:",
1988                 ctx->common.target);
1989         if (ctx->partial_security_descriptors != 0) {
1990                 WARNING("- Could only partially set the security descriptor\n"
1991                         "            on %lu files or directories.",
1992                         ctx->partial_security_descriptors);
1993         }
1994         if (ctx->no_security_descriptors != 0) {
1995                 WARNING("- Could not set security descriptor at all\n"
1996                         "            on %lu files or directories.",
1997                         ctx->no_security_descriptors);
1998         }
1999         WARNING("To fully restore all security descriptors, run the program\n"
2000                 "          with Administrator rights.");
2001 }
2002
2003 /* Extract files from a WIM image to a directory on Windows  */
2004 static int
2005 win32_extract(struct list_head *dentry_list, struct apply_ctx *_ctx)
2006 {
2007         int ret;
2008         struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
2009
2010         ret = prepare_target(dentry_list, ctx);
2011         if (ret)
2012                 goto out;
2013
2014         if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT) {
2015                 ret = start_wimboot_extraction(ctx);
2016                 if (ret)
2017                         goto out;
2018         }
2019
2020         ret = create_directories(dentry_list, ctx);
2021         if (ret)
2022                 goto out;
2023
2024         ret = create_nondirectories(dentry_list, ctx);
2025         if (ret)
2026                 goto out;
2027
2028         struct read_stream_list_callbacks cbs = {
2029                 .begin_stream      = begin_extract_stream,
2030                 .begin_stream_ctx  = ctx,
2031                 .consume_chunk     = extract_chunk,
2032                 .consume_chunk_ctx = ctx,
2033                 .end_stream        = end_extract_stream,
2034                 .end_stream_ctx    = ctx,
2035         };
2036         ret = extract_stream_list(&ctx->common, &cbs);
2037         if (ret)
2038                 goto out;
2039
2040         ret = apply_metadata(dentry_list, ctx);
2041         if (ret)
2042                 goto out;
2043
2044         do_warnings(ctx);
2045 out:
2046         if (ctx->h_target)
2047                 (*func_NtClose)(ctx->h_target);
2048         if (ctx->target_ntpath.Buffer)
2049                 HeapFree(GetProcessHeap(), 0, ctx->target_ntpath.Buffer);
2050         FREE(ctx->pathbuf.Buffer);
2051         FREE(ctx->print_buffer);
2052         if (ctx->wimboot.prepopulate_pats) {
2053                 FREE(ctx->wimboot.prepopulate_pats->strings);
2054                 FREE(ctx->wimboot.prepopulate_pats);
2055         }
2056         FREE(ctx->wimboot.mem_prepopulate_pats);
2057         FREE(ctx->data_buffer);
2058         return ret;
2059 }
2060
2061 const struct apply_operations win32_apply_ops = {
2062         .name                   = "Windows",
2063         .get_supported_features = win32_get_supported_features,
2064         .extract                = win32_extract,
2065         .context_size           = sizeof(struct win32_apply_ctx),
2066 };
2067
2068 #endif /* __WIN32__ */