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