]> wimlib.net Git - wimlib/blob - src/win32_apply.c
win32_apply: bail if paths are too long for a UNICODE_STRING
[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-2016 Eric Biggers
7  *
8  * This file is free software; you can redistribute it and/or modify it under
9  * the terms of the GNU Lesser General Public License as published by the Free
10  * Software Foundation; either version 3 of the License, or (at your option) any
11  * later version.
12  *
13  * This file is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this file; if not, see http://www.gnu.org/licenses/.
20  */
21
22 #ifdef __WIN32__
23
24 #ifdef HAVE_CONFIG_H
25 #  include "config.h"
26 #endif
27
28 #include "wimlib/win32_common.h"
29
30 #include "wimlib/apply.h"
31 #include "wimlib/assert.h"
32 #include "wimlib/blob_table.h"
33 #include "wimlib/dentry.h"
34 #include "wimlib/encoding.h"
35 #include "wimlib/error.h"
36 #include "wimlib/metadata.h"
37 #include "wimlib/object_id.h"
38 #include "wimlib/paths.h"
39 #include "wimlib/pattern.h"
40 #include "wimlib/reparse.h"
41 #include "wimlib/scan.h" /* for mangle_pat() and match_pattern_list()  */
42 #include "wimlib/textfile.h"
43 #include "wimlib/xml.h"
44 #include "wimlib/wimboot.h"
45 #include "wimlib/wof.h"
46
47 struct win32_apply_ctx {
48
49         /* Extract flags, the pointer to the WIMStruct, etc.  */
50         struct apply_ctx common;
51
52         /* WIMBoot information, only filled in if WIMLIB_EXTRACT_FLAG_WIMBOOT
53          * was provided  */
54         struct {
55                 /* This array contains the WIM files registered with WOF on the
56                  * target volume for this extraction operation.  All WIMStructs
57                  * in this array are distinct and have ->filename != NULL.  */
58                 struct wimboot_wim {
59                         WIMStruct *wim;
60                         u64 data_source_id;
61                         u8 blob_table_hash[SHA1_HASH_SIZE];
62                 } *wims;
63                 size_t num_wims;
64                 bool wof_running;
65                 bool have_wrong_version_wims;
66                 bool have_uncompressed_wims;
67                 bool have_unsupported_compressed_resources;
68                 bool have_huge_resources;
69         } wimboot;
70
71         /* External backing information  */
72         struct string_list *prepopulate_pats;
73         void *mem_prepopulate_pats;
74         bool tried_to_load_prepopulate_list;
75
76         /* Open handle to the target directory  */
77         HANDLE h_target;
78
79         /* NT namespace path to the target directory (buffer allocated)  */
80         UNICODE_STRING target_ntpath;
81
82         /* Temporary buffer for building paths (buffer allocated)  */
83         UNICODE_STRING pathbuf;
84
85         /* Object attributes to reuse for opening files in the target directory.
86          * (attr.ObjectName == &pathbuf) and (attr.RootDirectory == h_target).
87          */
88         OBJECT_ATTRIBUTES attr;
89
90         /* Temporary I/O status block for system calls  */
91         IO_STATUS_BLOCK iosb;
92
93         /* Allocated buffer for creating "printable" paths from our
94          * target-relative NT paths  */
95         wchar_t *print_buffer;
96
97         /* Allocated buffer for reading blob data when it cannot be extracted
98          * directly  */
99         u8 *data_buffer;
100
101         /* Pointer to the next byte in @data_buffer to fill  */
102         u8 *data_buffer_ptr;
103
104         /* Size allocated in @data_buffer  */
105         size_t data_buffer_size;
106
107         /* Current offset in the raw encrypted file being written  */
108         size_t encrypted_offset;
109
110         /* Current size of the raw encrypted file being written  */
111         size_t encrypted_size;
112
113         /* Temporary buffer for reparse data  */
114         struct reparse_buffer_disk rpbuf;
115
116         /* Temporary buffer for reparse data of "fixed" absolute symbolic links
117          * and junctions  */
118         struct reparse_buffer_disk rpfixbuf;
119
120         /* Array of open handles to filesystem streams currently being written
121          */
122         HANDLE open_handles[MAX_OPEN_FILES];
123
124         /* Number of handles in @open_handles currently open (filled in from the
125          * beginning of the array)  */
126         unsigned num_open_handles;
127
128         /* For each currently open stream, whether we're writing to it in
129          * "sparse" mode or not.  */
130         bool is_sparse_stream[MAX_OPEN_FILES];
131
132         /* Whether is_sparse_stream[] is true for any currently open stream  */
133         bool any_sparse_streams;
134
135         /* List of dentries, joined by @d_tmp_list, that need to have reparse
136          * data extracted as soon as the whole blob has been read into
137          * @data_buffer.  */
138         struct list_head reparse_dentries;
139
140         /* List of dentries, joined by @d_tmp_list, that need to have raw
141          * encrypted data extracted as soon as the whole blob has been read into
142          * @data_buffer.  */
143         struct list_head encrypted_dentries;
144
145         /* Number of files for which we didn't have permission to set the full
146          * security descriptor.  */
147         unsigned long partial_security_descriptors;
148
149         /* Number of files for which we didn't have permission to set any part
150          * of the security descriptor.  */
151         unsigned long no_security_descriptors;
152
153         /* Number of files for which we couldn't set the short name.  */
154         unsigned long num_set_short_name_failures;
155
156         /* Number of files for which we couldn't remove the short name.  */
157         unsigned long num_remove_short_name_failures;
158
159         /* Number of files on which we couldn't set System Compression.  */
160         unsigned long num_system_compression_failures;
161
162         /* The number of files which, for compatibility with the Windows
163          * bootloader, were not compressed using the requested system
164          * compression format.  This includes matches with the hardcoded pattern
165          * list only; it does not include matches with patterns in
166          * [PrepopulateList].  */
167         unsigned long num_system_compression_exclusions;
168
169         /* Number of files for which we couldn't set the object ID.  */
170         unsigned long num_object_id_failures;
171
172         /* The Windows build number of the image being applied, or 0 if unknown.
173          */
174         u64 windows_build_number;
175
176         /* Have we tried to enable short name support on the target volume yet?
177          */
178         bool tried_to_enable_short_names;
179 };
180
181 /* Get the drive letter from a Windows path, or return the null character if the
182  * path is relative.  */
183 static wchar_t
184 get_drive_letter(const wchar_t *path)
185 {
186         /* Skip \\?\ prefix  */
187         if (!wcsncmp(path, L"\\\\?\\", 4))
188                 path += 4;
189
190         /* Return drive letter if valid  */
191         if (((path[0] >= L'a' && path[0] <= L'z') ||
192              (path[0] >= L'A' && path[0] <= L'Z')) && path[1] == L':')
193                 return path[0];
194
195         return L'\0';
196 }
197
198 static void
199 get_vol_flags(const wchar_t *target, DWORD *vol_flags_ret,
200               bool *short_names_supported_ret)
201 {
202         wchar_t filesystem_name[MAX_PATH + 1];
203         wchar_t drive[4];
204         wchar_t *volume = NULL;
205
206         *vol_flags_ret = 0;
207         *short_names_supported_ret = false;
208
209         drive[0] = get_drive_letter(target);
210         if (drive[0]) {
211                 drive[1] = L':';
212                 drive[2] = L'\\';
213                 drive[3] = L'\0';
214                 volume = drive;
215         }
216
217         if (!GetVolumeInformation(volume, NULL, 0, NULL, NULL,
218                                   vol_flags_ret, filesystem_name,
219                                   ARRAY_LEN(filesystem_name)))
220         {
221                 win32_warning(GetLastError(),
222                               L"Failed to get volume information for \"%ls\"",
223                               target);
224                 return;
225         }
226
227         if (wcsstr(filesystem_name, L"NTFS")) {
228                 /* FILE_SUPPORTS_HARD_LINKS is only supported on Windows 7 and
229                  * later.  Force it on anyway if filesystem is NTFS.  */
230                 *vol_flags_ret |= FILE_SUPPORTS_HARD_LINKS;
231
232                 /* There's no volume flag for short names, but according to the
233                  * MS documentation they are only user-settable on NTFS.  */
234                 *short_names_supported_ret = true;
235         }
236 }
237
238 /* Is the image being extracted an OS image for Windows 10 or later?  */
239 static bool
240 is_image_windows_10_or_later(struct win32_apply_ctx *ctx)
241 {
242         /* Note: if no build number is available, this returns false.  */
243         return ctx->windows_build_number >= 10240;
244 }
245
246 static const wchar_t *
247 current_path(struct win32_apply_ctx *ctx);
248
249 static void
250 build_extraction_path(const struct wim_dentry *dentry,
251                       struct win32_apply_ctx *ctx);
252
253 static int
254 report_dentry_apply_error(const struct wim_dentry *dentry,
255                           struct win32_apply_ctx *ctx, int ret)
256 {
257         build_extraction_path(dentry, ctx);
258         return report_apply_error(&ctx->common, ret, current_path(ctx));
259 }
260
261 static inline int
262 check_apply_error(const struct wim_dentry *dentry,
263                   struct win32_apply_ctx *ctx, int ret)
264 {
265         if (unlikely(ret))
266                 ret = report_dentry_apply_error(dentry, ctx, ret);
267         return ret;
268 }
269
270 static int
271 win32_get_supported_features(const wchar_t *target,
272                              struct wim_features *supported_features)
273 {
274         DWORD vol_flags;
275         bool short_names_supported;
276
277         /* Query the features of the target volume.  */
278
279         get_vol_flags(target, &vol_flags, &short_names_supported);
280
281         supported_features->readonly_files = 1;
282         supported_features->hidden_files = 1;
283         supported_features->system_files = 1;
284         supported_features->archive_files = 1;
285
286         if (vol_flags & FILE_FILE_COMPRESSION)
287                 supported_features->compressed_files = 1;
288
289         if (vol_flags & FILE_SUPPORTS_ENCRYPTION) {
290                 supported_features->encrypted_files = 1;
291                 supported_features->encrypted_directories = 1;
292         }
293
294         supported_features->not_context_indexed_files = 1;
295
296         if (vol_flags & FILE_SUPPORTS_SPARSE_FILES)
297                 supported_features->sparse_files = 1;
298
299         if (vol_flags & FILE_NAMED_STREAMS)
300                 supported_features->named_data_streams = 1;
301
302         if (vol_flags & FILE_SUPPORTS_HARD_LINKS)
303                 supported_features->hard_links = 1;
304
305         if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS)
306                 supported_features->reparse_points = 1;
307
308         if (vol_flags & FILE_PERSISTENT_ACLS)
309                 supported_features->security_descriptors = 1;
310
311         if (short_names_supported)
312                 supported_features->short_names = 1;
313
314         if (vol_flags & FILE_SUPPORTS_OBJECT_IDS)
315                 supported_features->object_ids = 1;
316
317         supported_features->timestamps = 1;
318
319         if (vol_flags & FILE_CASE_SENSITIVE_SEARCH) {
320                 /*
321                  * The filesystem supports case-sensitive filenames.  But does
322                  * the operating system as well?  This normally requires the
323                  * registry setting ObCaseInsensitive=0.  We can test it
324                  * indirectly by attempting to open the "\SystemRoot" symbolic
325                  * link using a name with the wrong case.  If we get
326                  * STATUS_OBJECT_NAME_NOT_FOUND instead of STATUS_ACCESS_DENIED,
327                  * then case-sensitive names must be enabled.
328                  */
329                 UNICODE_STRING path;
330                 OBJECT_ATTRIBUTES attr;
331                 HANDLE h;
332                 NTSTATUS status;
333
334                 RtlInitUnicodeString(&path, L"\\systemroot");
335                 InitializeObjectAttributes(&attr, &path, 0, NULL, NULL);
336
337                 status = NtOpenSymbolicLinkObject(&h, 0, &attr);
338                 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
339                         supported_features->case_sensitive_filenames = 1;
340         }
341
342         return 0;
343 }
344
345 #define COMPACT_FLAGS   (WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS4K |         \
346                          WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS8K |         \
347                          WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS16K |        \
348                          WIMLIB_EXTRACT_FLAG_COMPACT_LZX)
349
350
351
352 /*
353  * If not done already, load the patterns from the [PrepopulateList] section of
354  * WimBootCompress.ini in the WIM image being extracted.
355  *
356  * Note: WimBootCompress.ini applies to both types of "external backing":
357  *
358  *      - WIM backing ("WIMBoot" - Windows 8.1 and later)
359  *      - File backing ("System Compression" - Windows 10 and later)
360  */
361 static int
362 load_prepopulate_pats(struct win32_apply_ctx *ctx)
363 {
364         const wchar_t *path = L"\\Windows\\System32\\WimBootCompress.ini";
365         struct wim_dentry *dentry;
366         const struct blob_descriptor *blob;
367         int ret;
368         void *buf;
369         struct string_list *strings;
370         void *mem;
371         struct text_file_section sec;
372
373         if (ctx->tried_to_load_prepopulate_list)
374                 return 0;
375
376         ctx->tried_to_load_prepopulate_list = true;
377
378         dentry = get_dentry(ctx->common.wim, path, WIMLIB_CASE_INSENSITIVE);
379         if (!dentry ||
380             (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
381                                               FILE_ATTRIBUTE_REPARSE_POINT |
382                                               FILE_ATTRIBUTE_ENCRYPTED)) ||
383             !(blob = inode_get_blob_for_unnamed_data_stream(dentry->d_inode,
384                                                             ctx->common.wim->blob_table)))
385         {
386                 WARNING("%ls does not exist in the WIM image.\n"
387                         "          The default configuration will be used instead; it assumes that all\n"
388                         "          files are valid for external backing regardless of path, equivalent\n"
389                         "          to an empty [PrepopulateList] section.", path);
390                 return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
391         }
392
393         ret = read_blob_into_alloc_buf(blob, &buf);
394         if (ret)
395                 return ret;
396
397         strings = CALLOC(1, sizeof(struct string_list));
398         if (!strings) {
399                 FREE(buf);
400                 return WIMLIB_ERR_NOMEM;
401         }
402
403         sec.name = T("PrepopulateList");
404         sec.strings = strings;
405
406         ret = do_load_text_file(path, buf, blob->size, &mem, &sec, 1,
407                                 LOAD_TEXT_FILE_REMOVE_QUOTES |
408                                         LOAD_TEXT_FILE_NO_WARNINGS,
409                                 mangle_pat);
410         STATIC_ASSERT(OS_PREFERRED_PATH_SEPARATOR == WIM_PATH_SEPARATOR);
411         FREE(buf);
412         if (ret) {
413                 FREE(strings);
414                 return ret;
415         }
416         ctx->prepopulate_pats = strings;
417         ctx->mem_prepopulate_pats = mem;
418         return 0;
419 }
420
421 /* Returns %true if the specified absolute path to a file in the WIM image can
422  * be subject to external backing when extracted.  Otherwise returns %false.  */
423 static bool
424 can_externally_back_path(const wchar_t *path, const struct win32_apply_ctx *ctx)
425 {
426         /* Does the path match a pattern given in the [PrepopulateList] section
427          * of WimBootCompress.ini?  */
428         if (ctx->prepopulate_pats && match_pattern_list(path, ctx->prepopulate_pats))
429                 return false;
430
431         /* Since we attempt to modify the SYSTEM registry after it's extracted
432          * (see end_wimboot_extraction()), it can't be extracted as externally
433          * backed.  This extends to associated files such as SYSTEM.LOG that
434          * also must be writable in order to write to the registry.  Normally,
435          * SYSTEM is in [PrepopulateList], and the SYSTEM.* files match patterns
436          * in [ExclusionList] and therefore are not captured in the WIM at all.
437          * However, a WIM that wasn't specifically captured in "WIMBoot mode"
438          * may contain SYSTEM.* files.  So to make things "just work", hard-code
439          * the pattern.  */
440         if (match_path(path, L"\\Windows\\System32\\config\\SYSTEM*", false))
441                 return false;
442
443         return true;
444 }
445
446 /* Can the specified WIM resource be used as the source of an external backing
447  * for the wof.sys WIM provider?  */
448 static bool
449 is_resource_valid_for_external_backing(const struct wim_resource_descriptor *rdesc,
450                                        struct win32_apply_ctx *ctx)
451 {
452         /* Must be the original WIM file format.  This check excludes pipable
453          * resources and solid resources.  It also excludes other resources
454          * contained in such files even if they would be otherwise compatible.
455          */
456         if (rdesc->wim->hdr.magic != WIM_MAGIC ||
457             rdesc->wim->hdr.wim_version != WIM_VERSION_DEFAULT)
458         {
459                 ctx->wimboot.have_wrong_version_wims = true;
460                 return false;
461         }
462
463         /*
464          * Whitelist of compression types and chunk sizes supported by
465          * Microsoft's WOF driver.
466          *
467          * Notes:
468          *    - Uncompressed WIMs result in BSOD.  However, this only applies to
469          *      the WIM file itself, not to uncompressed resources in a WIM file
470          *      that is otherwise compressed.
471          *    - XPRESS 64K sometimes appears to work, but sometimes it causes
472          *      reads to fail with STATUS_UNSUCCESSFUL.
473          */
474         switch (rdesc->compression_type) {
475         case WIMLIB_COMPRESSION_TYPE_NONE:
476                 if (rdesc->wim->compression_type == WIMLIB_COMPRESSION_TYPE_NONE) {
477                         ctx->wimboot.have_uncompressed_wims = true;
478                         return false;
479                 }
480                 break;
481         case WIMLIB_COMPRESSION_TYPE_XPRESS:
482                 switch (rdesc->chunk_size) {
483                 case 4096:
484                 case 8192:
485                 case 16384:
486                 case 32768:
487                         break;
488                 default:
489                         ctx->wimboot.have_unsupported_compressed_resources = true;
490                         return false;
491                 }
492                 break;
493         case WIMLIB_COMPRESSION_TYPE_LZX:
494                 switch (rdesc->chunk_size) {
495                 case 32768:
496                         break;
497                 default:
498                         ctx->wimboot.have_unsupported_compressed_resources = true;
499                         return false;
500                 }
501                 break;
502         default:
503                 ctx->wimboot.have_unsupported_compressed_resources = true;
504                 return false;
505         }
506
507         /* Microsoft's WoF driver errors out if it tries to satisfy a read with
508          * ending offset >= 4 GiB from an externally backed file.  */
509         if (rdesc->uncompressed_size > 4200000000) {
510                 ctx->wimboot.have_huge_resources = true;
511                 return false;
512         }
513
514         return true;
515 }
516
517 #define EXTERNAL_BACKING_NOT_ENABLED            -1
518 #define EXTERNAL_BACKING_NOT_POSSIBLE           -2
519 #define EXTERNAL_BACKING_EXCLUDED               -3
520
521 /*
522  * Determines whether the specified file will be externally backed.  Returns a
523  * negative status code if no, 0 if yes, or a positive wimlib error code on
524  * error.  If the file is excluded from external backing based on its path, then
525  * *excluded_dentry_ret is set to the dentry for the path that matched the
526  * exclusion rule.
527  *
528  * Note that this logic applies to both types of "external backing":
529  *
530  *      - WIM backing ("WIMBoot" - Windows 8.1 and later)
531  *      - File backing ("System Compression" - Windows 10 and later)
532  *
533  * However, in the case of WIM backing we also need to validate that the WIM
534  * resource that would be the source of the backing is supported by the wof.sys
535  * WIM provider.
536  */
537 static int
538 will_externally_back_inode(struct wim_inode *inode, struct win32_apply_ctx *ctx,
539                            const struct wim_dentry **excluded_dentry_ret,
540                            bool wimboot_mode)
541 {
542         struct wim_dentry *dentry;
543         struct blob_descriptor *blob;
544         int ret;
545
546         if (load_prepopulate_pats(ctx) == WIMLIB_ERR_NOMEM)
547                 return WIMLIB_ERR_NOMEM;
548
549         if (inode->i_can_externally_back)
550                 return 0;
551
552         /* This may do redundant checks because the cached value
553          * i_can_externally_back is 2-state (as opposed to 3-state:
554          * unknown/no/yes).  But most files can be externally backed, so this
555          * way is fine.  */
556
557         if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
558                                    FILE_ATTRIBUTE_REPARSE_POINT |
559                                    FILE_ATTRIBUTE_ENCRYPTED))
560                 return EXTERNAL_BACKING_NOT_POSSIBLE;
561
562         blob = inode_get_blob_for_unnamed_data_stream_resolved(inode);
563
564         if (!blob)
565                 return EXTERNAL_BACKING_NOT_POSSIBLE;
566
567         if (wimboot_mode &&
568             (blob->blob_location != BLOB_IN_WIM ||
569              !is_resource_valid_for_external_backing(blob->rdesc, ctx)))
570                 return EXTERNAL_BACKING_NOT_POSSIBLE;
571
572         /*
573          * We need to check the patterns in [PrepopulateList] against every name
574          * of the inode, in case any of them match.
575          */
576
577         inode_for_each_extraction_alias(dentry, inode) {
578
579                 ret = calculate_dentry_full_path(dentry);
580                 if (ret)
581                         return ret;
582
583                 if (!can_externally_back_path(dentry->d_full_path, ctx)) {
584                         if (excluded_dentry_ret)
585                                 *excluded_dentry_ret = dentry;
586                         return EXTERNAL_BACKING_EXCLUDED;
587                 }
588         }
589
590         inode->i_can_externally_back = 1;
591         return 0;
592 }
593
594 /*
595  * Determines if the unnamed data stream of a file will be created as a WIM
596  * external backing (a "WIMBoot pointer file"), as opposed to a standard
597  * extraction.
598  */
599 static int
600 win32_will_back_from_wim(struct wim_dentry *dentry, struct apply_ctx *_ctx)
601 {
602         struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
603
604         if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
605                 return EXTERNAL_BACKING_NOT_ENABLED;
606
607         return will_externally_back_inode(dentry->d_inode, ctx, NULL, true);
608 }
609
610 /* Find the WOF registration information for the specified WIM file.  */
611 static struct wimboot_wim *
612 find_wimboot_wim(WIMStruct *wim_to_find, struct win32_apply_ctx *ctx)
613 {
614         for (size_t i = 0; i < ctx->wimboot.num_wims; i++)
615                 if (wim_to_find == ctx->wimboot.wims[i].wim)
616                         return &ctx->wimboot.wims[i];
617
618         wimlib_assert(0);
619         return NULL;
620 }
621
622 static int
623 set_backed_from_wim(HANDLE h, struct wim_inode *inode, struct win32_apply_ctx *ctx)
624 {
625         int ret;
626         const struct wim_dentry *excluded_dentry;
627         const struct blob_descriptor *blob;
628         const struct wimboot_wim *wimboot_wim;
629
630         ret = will_externally_back_inode(inode, ctx, &excluded_dentry, true);
631         if (ret > 0) /* Error.  */
632                 return ret;
633
634         if (ret < 0 && ret != EXTERNAL_BACKING_EXCLUDED)
635                 return 0; /* Not externally backing, other than due to exclusion.  */
636
637         if (unlikely(ret == EXTERNAL_BACKING_EXCLUDED)) {
638                 /* Not externally backing due to exclusion.  */
639                 union wimlib_progress_info info;
640
641                 build_extraction_path(excluded_dentry, ctx);
642
643                 info.wimboot_exclude.path_in_wim = excluded_dentry->d_full_path;
644                 info.wimboot_exclude.extraction_path = current_path(ctx);
645
646                 return call_progress(ctx->common.progfunc,
647                                      WIMLIB_PROGRESS_MSG_WIMBOOT_EXCLUDE,
648                                      &info, ctx->common.progctx);
649         }
650
651         /* Externally backing.  */
652
653         blob = inode_get_blob_for_unnamed_data_stream_resolved(inode);
654         wimboot_wim = find_wimboot_wim(blob->rdesc->wim, ctx);
655
656         if (unlikely(!wimboot_set_pointer(h,
657                                           blob,
658                                           wimboot_wim->data_source_id,
659                                           wimboot_wim->blob_table_hash,
660                                           ctx->wimboot.wof_running)))
661         {
662                 const DWORD err = GetLastError();
663
664                 build_extraction_path(inode_first_extraction_dentry(inode), ctx);
665                 win32_error(err, L"\"%ls\": Couldn't set WIMBoot pointer data",
666                             current_path(ctx));
667                 return WIMLIB_ERR_WIMBOOT;
668         }
669         return 0;
670 }
671
672 /* Calculates the SHA-1 message digest of the WIM's blob table.  */
673 static int
674 hash_blob_table(WIMStruct *wim, u8 hash[SHA1_HASH_SIZE])
675 {
676         return wim_reshdr_to_hash(&wim->hdr.blob_table_reshdr, wim, hash);
677 }
678
679 static int
680 register_wim_with_wof(WIMStruct *wim, struct win32_apply_ctx *ctx)
681 {
682         struct wimboot_wim *p;
683         int ret;
684
685         /* Check if already registered  */
686         for (size_t i = 0; i < ctx->wimboot.num_wims; i++)
687                 if (wim == ctx->wimboot.wims[i].wim)
688                         return 0;
689
690         /* Not yet registered  */
691
692         p = REALLOC(ctx->wimboot.wims,
693                     (ctx->wimboot.num_wims + 1) * sizeof(ctx->wimboot.wims[0]));
694         if (!p)
695                 return WIMLIB_ERR_NOMEM;
696         ctx->wimboot.wims = p;
697
698         ctx->wimboot.wims[ctx->wimboot.num_wims].wim = wim;
699
700         ret = hash_blob_table(wim, ctx->wimboot.wims[ctx->wimboot.num_wims].blob_table_hash);
701         if (ret)
702                 return ret;
703
704         ret = wimboot_alloc_data_source_id(wim->filename,
705                                            wim->hdr.guid,
706                                            ctx->common.wim->current_image,
707                                            ctx->common.target,
708                                            &ctx->wimboot.wims[ctx->wimboot.num_wims].data_source_id,
709                                            &ctx->wimboot.wof_running);
710         if (ret)
711                 return ret;
712
713         ctx->wimboot.num_wims++;
714         return 0;
715 }
716
717 /* Prepare for doing a "WIMBoot" extraction by registering each source WIM file
718  * with WOF on the target volume.  */
719 static int
720 start_wimboot_extraction(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
721 {
722         int ret;
723         struct wim_dentry *dentry;
724
725         if (!xml_get_wimboot(ctx->common.wim->xml_info,
726                              ctx->common.wim->current_image))
727                 WARNING("The WIM image is not marked as WIMBoot compatible.  This usually\n"
728                         "          means it is not intended to be used to back a Windows operating\n"
729                         "          system.  Proceeding anyway.");
730
731         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
732                 struct blob_descriptor *blob;
733
734                 ret = win32_will_back_from_wim(dentry, &ctx->common);
735                 if (ret > 0) /* Error */
736                         return ret;
737                 if (ret < 0) /* Won't externally back */
738                         continue;
739
740                 blob = inode_get_blob_for_unnamed_data_stream_resolved(dentry->d_inode);
741                 ret = register_wim_with_wof(blob->rdesc->wim, ctx);
742                 if (ret)
743                         return ret;
744         }
745
746         if (ctx->wimboot.have_wrong_version_wims) {
747   WARNING("At least one of the source WIM files uses a version of the WIM\n"
748 "          file format that not supported by Microsoft's wof.sys driver.\n"
749 "          Files whose data is contained in one of these WIM files will be\n"
750 "          extracted as full files rather than externally backed.");
751         }
752
753         if (ctx->wimboot.have_uncompressed_wims) {
754   WARNING("At least one of the source WIM files is uncompressed.  Files whose\n"
755 "          data is contained in an uncompressed WIM file will be extracted as\n"
756 "          full files rather than externally backed, since uncompressed WIM\n"
757 "          files are not supported by Microsoft's wof.sys driver.");
758         }
759
760         if (ctx->wimboot.have_unsupported_compressed_resources) {
761   WARNING("At least one of the source WIM files uses a compression format that\n"
762 "          is not supported by Microsoft's wof.sys driver.  Files whose data is\n"
763 "          contained in a compressed resource in one of these WIM files will be\n"
764 "          extracted as full files rather than externally backed.  (The\n"
765 "          compression formats supported by wof.sys are: XPRESS 4K, XPRESS 8K,\n"
766 "          XPRESS 16K, XPRESS 32K, and LZX 32K.)");
767         }
768
769         if (ctx->wimboot.have_huge_resources) {
770   WARNING("Some files exceeded 4.2 GB in size.  Such files will be extracted\n"
771 "          as full files rather than externally backed, since very large files\n"
772 "          are not supported by Microsoft's wof.sys driver.");
773         }
774
775         return 0;
776 }
777
778 static void
779 build_win32_extraction_path(const struct wim_dentry *dentry,
780                             struct win32_apply_ctx *ctx);
781
782 /* Sets WimBoot=1 in the extracted SYSTEM registry hive.
783  *
784  * WIMGAPI does this, and it's possible that it's important.
785  * But I don't know exactly what this value means to Windows.  */
786 static int
787 end_wimboot_extraction(struct win32_apply_ctx *ctx)
788 {
789         struct wim_dentry *dentry;
790         wchar_t subkeyname[32];
791         LONG res;
792         LONG res2;
793         HKEY key;
794         DWORD value;
795
796         dentry = get_dentry(ctx->common.wim, L"\\Windows\\System32\\config\\SYSTEM",
797                             WIMLIB_CASE_INSENSITIVE);
798
799         if (!dentry || !will_extract_dentry(dentry))
800                 goto out;
801
802         if (!will_extract_dentry(wim_get_current_root_dentry(ctx->common.wim)))
803                 goto out;
804
805         /* Not bothering to use the native routines (e.g. NtLoadKey()) for this.
806          * If this doesn't work, you probably also have many other problems.  */
807
808         build_win32_extraction_path(dentry, ctx);
809
810         get_random_alnum_chars(subkeyname, 20);
811         subkeyname[20] = L'\0';
812
813         res = RegLoadKey(HKEY_LOCAL_MACHINE, subkeyname, ctx->pathbuf.Buffer);
814         if (res)
815                 goto out_check_res;
816
817         wcscpy(&subkeyname[20], L"\\Setup");
818
819         res = RegCreateKeyEx(HKEY_LOCAL_MACHINE, subkeyname, 0, NULL,
820                              REG_OPTION_BACKUP_RESTORE, 0, NULL, &key, NULL);
821         if (res)
822                 goto out_unload_key;
823
824         value = 1;
825
826         res = RegSetValueEx(key, L"WimBoot", 0, REG_DWORD,
827                             (const BYTE *)&value, sizeof(DWORD));
828         if (res)
829                 goto out_close_key;
830
831         res = RegFlushKey(key);
832
833 out_close_key:
834         res2 = RegCloseKey(key);
835         if (!res)
836                 res = res2;
837 out_unload_key:
838         subkeyname[20] = L'\0';
839         RegUnLoadKey(HKEY_LOCAL_MACHINE, subkeyname);
840 out_check_res:
841         if (res) {
842                 /* Warning only.  */
843                 win32_warning(res, L"Failed to set \\Setup: dword \"WimBoot\"=1 "
844                               "value in registry hive \"%ls\"",
845                               ctx->pathbuf.Buffer);
846         }
847 out:
848         return 0;
849 }
850
851 /* Returns the number of wide characters needed to represent the path to the
852  * specified @dentry, relative to the target directory, when extracted.
853  *
854  * Does not include null terminator (not needed for NtCreateFile).  */
855 static size_t
856 dentry_extraction_path_length(const struct wim_dentry *dentry)
857 {
858         size_t len = 0;
859         const struct wim_dentry *d;
860
861         d = dentry;
862         do {
863                 len += d->d_extraction_name_nchars + 1;
864                 d = d->d_parent;
865         } while (!dentry_is_root(d) && will_extract_dentry(d));
866
867         return --len;  /* No leading slash  */
868 }
869
870 /* Returns the length of the longest string that might need to be appended to
871  * the path to an alias of an inode to open or create a named data stream.
872  *
873  * If the inode has no named data streams, this will be 0.  Otherwise, this will
874  * be 1 plus the length of the longest-named data stream, since the data stream
875  * name must be separated from the path by the ':' character.  */
876 static size_t
877 inode_longest_named_data_stream_spec(const struct wim_inode *inode)
878 {
879         size_t max = 0;
880         for (unsigned i = 0; i < inode->i_num_streams; i++) {
881                 const struct wim_inode_stream *strm = &inode->i_streams[i];
882                 if (!stream_is_named_data_stream(strm))
883                         continue;
884                 size_t len = utf16le_len_chars(strm->stream_name);
885                 if (len > max)
886                         max = len;
887         }
888         if (max)
889                 max += 1;
890         return max;
891 }
892
893 /* Find the length, in wide characters, of the longest path needed for
894  * extraction of any file in @dentry_list relative to the target directory.
895  *
896  * Accounts for named data streams, but does not include null terminator (not
897  * needed for NtCreateFile).  */
898 static size_t
899 compute_path_max(struct list_head *dentry_list)
900 {
901         size_t max = 0;
902         const struct wim_dentry *dentry;
903
904         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
905                 size_t len;
906
907                 len = dentry_extraction_path_length(dentry);
908
909                 /* Account for named data streams  */
910                 len += inode_longest_named_data_stream_spec(dentry->d_inode);
911
912                 if (len > max)
913                         max = len;
914         }
915
916         return max;
917 }
918
919 /* Build the path at which to extract the @dentry, relative to the target
920  * directory.
921  *
922  * The path is saved in ctx->pathbuf.  */
923 static void
924 build_extraction_path(const struct wim_dentry *dentry,
925                       struct win32_apply_ctx *ctx)
926 {
927         size_t len;
928         wchar_t *p;
929         const struct wim_dentry *d;
930
931         len = dentry_extraction_path_length(dentry);
932
933         ctx->pathbuf.Length = len * sizeof(wchar_t);
934         p = ctx->pathbuf.Buffer + len;
935         for (d = dentry;
936              !dentry_is_root(d->d_parent) && will_extract_dentry(d->d_parent);
937              d = d->d_parent)
938         {
939                 p -= d->d_extraction_name_nchars;
940                 if (d->d_extraction_name_nchars)
941                         wmemcpy(p, d->d_extraction_name,
942                                 d->d_extraction_name_nchars);
943                 *--p = '\\';
944         }
945         /* No leading slash  */
946         p -= d->d_extraction_name_nchars;
947         wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
948 }
949
950 /* Build the path at which to extract the @dentry, relative to the target
951  * directory, adding the suffix for a named data stream.
952  *
953  * The path is saved in ctx->pathbuf.  */
954 static void
955 build_extraction_path_with_ads(const struct wim_dentry *dentry,
956                                struct win32_apply_ctx *ctx,
957                                const wchar_t *stream_name,
958                                size_t stream_name_nchars)
959 {
960         wchar_t *p;
961
962         build_extraction_path(dentry, ctx);
963
964         /* Add :NAME for named data stream  */
965         p = ctx->pathbuf.Buffer + (ctx->pathbuf.Length / sizeof(wchar_t));
966         *p++ = L':';
967         wmemcpy(p, stream_name, stream_name_nchars);
968         ctx->pathbuf.Length += (1 + stream_name_nchars) * sizeof(wchar_t);
969 }
970
971 /* Build the Win32 namespace path to the specified @dentry when extracted.
972  *
973  * The path is saved in ctx->pathbuf and will be null terminated.
974  *
975  * XXX: We could get rid of this if it wasn't needed for the file encryption
976  * APIs, and the registry manipulation in WIMBoot mode.  */
977 static void
978 build_win32_extraction_path(const struct wim_dentry *dentry,
979                             struct win32_apply_ctx *ctx)
980 {
981         build_extraction_path(dentry, ctx);
982
983         /* Prepend target_ntpath to our relative path, then change \??\ into \\?\  */
984
985         memmove(ctx->pathbuf.Buffer +
986                         (ctx->target_ntpath.Length / sizeof(wchar_t)) + 1,
987                 ctx->pathbuf.Buffer, ctx->pathbuf.Length);
988         memcpy(ctx->pathbuf.Buffer, ctx->target_ntpath.Buffer,
989                 ctx->target_ntpath.Length);
990         ctx->pathbuf.Buffer[ctx->target_ntpath.Length / sizeof(wchar_t)] = L'\\';
991         ctx->pathbuf.Length += ctx->target_ntpath.Length + sizeof(wchar_t);
992         ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)] = L'\0';
993
994         wimlib_assert(ctx->pathbuf.Length >= 4 * sizeof(wchar_t) &&
995                       !wmemcmp(ctx->pathbuf.Buffer, L"\\??\\", 4));
996
997         ctx->pathbuf.Buffer[1] = L'\\';
998
999 }
1000
1001 /* Returns a "printable" representation of the last relative NT path that was
1002  * constructed with build_extraction_path() or build_extraction_path_with_ads().
1003  *
1004  * This will be overwritten by the next call to this function.  */
1005 static const wchar_t *
1006 current_path(struct win32_apply_ctx *ctx)
1007 {
1008         wchar_t *p = ctx->print_buffer;
1009
1010         p = wmempcpy(p, ctx->common.target, ctx->common.target_nchars);
1011         *p++ = L'\\';
1012         p = wmempcpy(p, ctx->pathbuf.Buffer, ctx->pathbuf.Length / sizeof(wchar_t));
1013         *p = L'\0';
1014         return ctx->print_buffer;
1015 }
1016
1017 /* Open handle to the target directory if it is not already open.  If the target
1018  * directory does not exist, this creates it.  */
1019 static int
1020 open_target_directory(struct win32_apply_ctx *ctx)
1021 {
1022         NTSTATUS status;
1023
1024         if (ctx->h_target)
1025                 return 0;
1026
1027         ctx->attr.Length = sizeof(ctx->attr);
1028         ctx->attr.RootDirectory = NULL;
1029         ctx->attr.ObjectName = &ctx->target_ntpath;
1030
1031         /* Don't use FILE_OPEN_REPARSE_POINT here; we want the extraction to
1032          * happen at the directory "pointed to" by the reparse point. */
1033         status = NtCreateFile(&ctx->h_target,
1034                               FILE_TRAVERSE,
1035                               &ctx->attr,
1036                               &ctx->iosb,
1037                               NULL,
1038                               0,
1039                               FILE_SHARE_VALID_FLAGS,
1040                               FILE_OPEN_IF,
1041                               FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT,
1042                               NULL,
1043                               0);
1044         if (!NT_SUCCESS(status)) {
1045                 winnt_error(status, L"Can't open or create directory \"%ls\"",
1046                             ctx->common.target);
1047                 return WIMLIB_ERR_OPENDIR;
1048         }
1049         ctx->attr.RootDirectory = ctx->h_target;
1050         ctx->attr.ObjectName = &ctx->pathbuf;
1051         return 0;
1052 }
1053
1054 static void
1055 close_target_directory(struct win32_apply_ctx *ctx)
1056 {
1057         if (ctx->h_target) {
1058                 NtClose(ctx->h_target);
1059                 ctx->h_target = NULL;
1060                 ctx->attr.RootDirectory = NULL;
1061         }
1062 }
1063
1064 /*
1065  * Ensures the target directory exists and opens a handle to it, in preparation
1066  * of using paths relative to it.
1067  */
1068 static int
1069 prepare_target(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1070 {
1071         int ret;
1072         size_t path_max;
1073
1074         ret = win32_path_to_nt_path(ctx->common.target, &ctx->target_ntpath);
1075         if (ret)
1076                 return ret;
1077
1078         ret = open_target_directory(ctx);
1079         if (ret)
1080                 return ret;
1081
1082         path_max = compute_path_max(dentry_list);
1083         /* Add some extra for building Win32 paths for the file encryption APIs,
1084          * and ensure we have at least enough to potentially use a 8.3 name for
1085          * the last component.  */
1086         path_max += max(2 + (ctx->target_ntpath.Length / sizeof(wchar_t)),
1087                         8 + 1 + 3);
1088
1089         ctx->pathbuf.MaximumLength = path_max * sizeof(wchar_t);
1090         if (ctx->pathbuf.MaximumLength != path_max * sizeof(wchar_t)) {
1091                 /* Paths are too long for a UNICODE_STRING! */
1092                 ERROR("Some paths are too long to extract (> 32768 characters)!");
1093                 return WIMLIB_ERR_UNSUPPORTED;
1094         }
1095
1096         ctx->pathbuf.Buffer = MALLOC(ctx->pathbuf.MaximumLength);
1097         if (!ctx->pathbuf.Buffer)
1098                 return WIMLIB_ERR_NOMEM;
1099
1100         ctx->print_buffer = MALLOC((ctx->common.target_nchars + 1 + path_max + 1) *
1101                                    sizeof(wchar_t));
1102         if (!ctx->print_buffer)
1103                 return WIMLIB_ERR_NOMEM;
1104
1105         return 0;
1106 }
1107
1108 /* When creating an inode that will have a short (DOS) name, we create it using
1109  * the long name associated with the short name.  This ensures that the short
1110  * name gets associated with the correct long name.  */
1111 static struct wim_dentry *
1112 first_extraction_alias(const struct wim_inode *inode)
1113 {
1114         struct wim_dentry *dentry;
1115
1116         inode_for_each_extraction_alias(dentry, inode)
1117                 if (dentry_has_short_name(dentry))
1118                         return dentry;
1119         return inode_first_extraction_dentry(inode);
1120 }
1121
1122 /*
1123  * Set or clear FILE_ATTRIBUTE_COMPRESSED if the inherited value is different
1124  * from the desired value.
1125  *
1126  * Note that you can NOT override the inherited value of
1127  * FILE_ATTRIBUTE_COMPRESSED directly with NtCreateFile().
1128  */
1129 static int
1130 adjust_compression_attribute(HANDLE h, const struct wim_dentry *dentry,
1131                              struct win32_apply_ctx *ctx)
1132 {
1133         const bool compressed = (dentry->d_inode->i_attributes &
1134                                  FILE_ATTRIBUTE_COMPRESSED);
1135         FILE_BASIC_INFORMATION info;
1136         USHORT compression_state;
1137         NTSTATUS status;
1138
1139         if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
1140                 return 0;
1141
1142         if (!ctx->common.supported_features.compressed_files)
1143                 return 0;
1144
1145
1146         /* Get current attributes  */
1147         status = NtQueryInformationFile(h, &ctx->iosb, &info, sizeof(info),
1148                                         FileBasicInformation);
1149         if (NT_SUCCESS(status) &&
1150             compressed == !!(info.FileAttributes & FILE_ATTRIBUTE_COMPRESSED))
1151         {
1152                 /* Nothing needs to be done.  */
1153                 return 0;
1154         }
1155
1156         /* Set the new compression state  */
1157
1158         if (compressed)
1159                 compression_state = COMPRESSION_FORMAT_DEFAULT;
1160         else
1161                 compression_state = COMPRESSION_FORMAT_NONE;
1162
1163         status = winnt_fsctl(h, FSCTL_SET_COMPRESSION,
1164                              &compression_state, sizeof(USHORT), NULL, 0, NULL);
1165         if (NT_SUCCESS(status))
1166                 return 0;
1167
1168         winnt_error(status, L"Can't %s compression attribute on \"%ls\"",
1169                     (compressed ? "set" : "clear"), current_path(ctx));
1170         return WIMLIB_ERR_SET_ATTRIBUTES;
1171 }
1172
1173 static bool
1174 need_sparse_flag(const struct wim_inode *inode,
1175                  const struct win32_apply_ctx *ctx)
1176 {
1177         return (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) &&
1178                 ctx->common.supported_features.sparse_files;
1179 }
1180
1181 static int
1182 set_sparse_flag(HANDLE h, struct win32_apply_ctx *ctx)
1183 {
1184         NTSTATUS status;
1185
1186         status = winnt_fsctl(h, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, NULL);
1187         if (NT_SUCCESS(status))
1188                 return 0;
1189
1190         winnt_error(status, L"Can't set sparse flag on \"%ls\"",
1191                     current_path(ctx));
1192         return WIMLIB_ERR_SET_ATTRIBUTES;
1193 }
1194
1195 /* Try to enable short name support on the target volume.  If successful, return
1196  * true.  If unsuccessful, issue a warning and return false.  */
1197 static bool
1198 try_to_enable_short_names(const wchar_t *volume)
1199 {
1200         HANDLE h;
1201         FILE_FS_PERSISTENT_VOLUME_INFORMATION info;
1202         BOOL bret;
1203         DWORD bytesReturned;
1204
1205         h = CreateFile(volume, GENERIC_WRITE,
1206                        FILE_SHARE_VALID_FLAGS, NULL, OPEN_EXISTING,
1207                        FILE_FLAG_BACKUP_SEMANTICS, NULL);
1208         if (h == INVALID_HANDLE_VALUE)
1209                 goto fail;
1210
1211         info.VolumeFlags = 0;
1212         info.FlagMask = PERSISTENT_VOLUME_STATE_SHORT_NAME_CREATION_DISABLED;
1213         info.Version = 1;
1214         info.Reserved = 0;
1215
1216         bret = DeviceIoControl(h, FSCTL_SET_PERSISTENT_VOLUME_STATE,
1217                                &info, sizeof(info), NULL, 0,
1218                                &bytesReturned, NULL);
1219
1220         CloseHandle(h);
1221
1222         if (!bret)
1223                 goto fail;
1224         return true;
1225
1226 fail:
1227         win32_warning(GetLastError(),
1228                       L"Failed to enable short name support on %ls",
1229                       volume + 4);
1230         return false;
1231 }
1232
1233 static NTSTATUS
1234 remove_conflicting_short_name(const struct wim_dentry *dentry, struct win32_apply_ctx *ctx)
1235 {
1236         wchar_t *name;
1237         wchar_t *end;
1238         NTSTATUS status;
1239         HANDLE h;
1240         size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1241                          (13 * sizeof(wchar_t));
1242         u8 buf[bufsize] _aligned_attribute(8);
1243         bool retried = false;
1244         FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1245
1246         memset(buf, 0, bufsize);
1247
1248         /* Build the path with the short name.  */
1249         name = &ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)];
1250         while (name != ctx->pathbuf.Buffer && *(name - 1) != L'\\')
1251                 name--;
1252         end = mempcpy(name, dentry->d_short_name, dentry->d_short_name_nbytes);
1253         ctx->pathbuf.Length = ((u8 *)end - (u8 *)ctx->pathbuf.Buffer);
1254
1255         /* Open the conflicting file (by short name).  */
1256         status = NtOpenFile(&h, GENERIC_WRITE | DELETE,
1257                             &ctx->attr, &ctx->iosb,
1258                             FILE_SHARE_VALID_FLAGS,
1259                             FILE_OPEN_REPARSE_POINT | FILE_OPEN_FOR_BACKUP_INTENT);
1260         if (!NT_SUCCESS(status)) {
1261                 winnt_warning(status, L"Can't open \"%ls\"", current_path(ctx));
1262                 goto out;
1263         }
1264
1265 #if 0
1266         WARNING("Overriding conflicting short name; path=\"%ls\"",
1267                 current_path(ctx));
1268 #endif
1269
1270         /* Try to remove the short name on the conflicting file.  */
1271
1272 retry:
1273         status = NtSetInformationFile(h, &ctx->iosb, info, bufsize,
1274                                       FileShortNameInformation);
1275
1276         if (status == STATUS_INVALID_PARAMETER && !retried) {
1277                 /* Microsoft forgot to make it possible to remove short names
1278                  * until Windows 7.  Oops.  Use a random short name instead.  */
1279                 get_random_alnum_chars(info->FileName, 8);
1280                 wcscpy(&info->FileName[8], L".WLB");
1281                 info->FileNameLength = 12 * sizeof(wchar_t);
1282                 retried = true;
1283                 goto retry;
1284         }
1285         NtClose(h);
1286 out:
1287         build_extraction_path(dentry, ctx);
1288         return status;
1289 }
1290
1291 /* Set the short name on the open file @h which has been created at the location
1292  * indicated by @dentry.
1293  *
1294  * Note that this may add, change, or remove the short name.
1295  *
1296  * @h must be opened with DELETE access.
1297  *
1298  * Returns 0 or WIMLIB_ERR_SET_SHORT_NAME.  The latter only happens in
1299  * STRICT_SHORT_NAMES mode.
1300  */
1301 static int
1302 set_short_name(HANDLE h, const struct wim_dentry *dentry,
1303                struct win32_apply_ctx *ctx)
1304 {
1305
1306         if (!ctx->common.supported_features.short_names)
1307                 return 0;
1308
1309         /*
1310          * Note: The size of the FILE_NAME_INFORMATION buffer must be such that
1311          * FileName contains at least 2 wide characters (4 bytes).  Otherwise,
1312          * NtSetInformationFile() will return STATUS_INFO_LENGTH_MISMATCH.  This
1313          * is despite the fact that FileNameLength can validly be 0 or 2 bytes,
1314          * with the former case being removing the existing short name if
1315          * present, rather than setting one.
1316          *
1317          * The null terminator is seemingly optional, but to be safe we include
1318          * space for it and zero all unused space.
1319          */
1320
1321         size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1322                          max(dentry->d_short_name_nbytes, sizeof(wchar_t)) +
1323                          sizeof(wchar_t);
1324         u8 buf[bufsize] _aligned_attribute(8);
1325         FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1326         NTSTATUS status;
1327         bool tried_to_remove_existing = false;
1328
1329         memset(buf, 0, bufsize);
1330
1331         info->FileNameLength = dentry->d_short_name_nbytes;
1332         memcpy(info->FileName, dentry->d_short_name, dentry->d_short_name_nbytes);
1333
1334 retry:
1335         status = NtSetInformationFile(h, &ctx->iosb, info, bufsize,
1336                                       FileShortNameInformation);
1337         if (NT_SUCCESS(status))
1338                 return 0;
1339
1340         if (status == STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME) {
1341                 if (dentry->d_short_name_nbytes == 0)
1342                         return 0;
1343                 if (!ctx->tried_to_enable_short_names) {
1344                         wchar_t volume[7];
1345                         int ret;
1346
1347                         ctx->tried_to_enable_short_names = true;
1348
1349                         ret = win32_get_drive_path(ctx->common.target,
1350                                                    volume);
1351                         if (ret)
1352                                 return ret;
1353                         if (try_to_enable_short_names(volume))
1354                                 goto retry;
1355                 }
1356         }
1357
1358         /*
1359          * Short names can conflict in several cases:
1360          *
1361          * - a file being extracted has a short name conflicting with an
1362          *   existing file
1363          *
1364          * - a file being extracted has a short name conflicting with another
1365          *   file being extracted (possible, but shouldn't happen)
1366          *
1367          * - a file being extracted has a short name that conflicts with the
1368          *   automatically generated short name of a file we previously
1369          *   extracted, but failed to set the short name for.  Sounds unlikely,
1370          *   but this actually does happen fairly often on versions of Windows
1371          *   prior to Windows 7 because they do not support removing short names
1372          *   from files.
1373          */
1374         if (unlikely(status == STATUS_OBJECT_NAME_COLLISION) &&
1375             dentry->d_short_name_nbytes && !tried_to_remove_existing)
1376         {
1377                 tried_to_remove_existing = true;
1378                 status = remove_conflicting_short_name(dentry, ctx);
1379                 if (NT_SUCCESS(status))
1380                         goto retry;
1381         }
1382
1383         /* By default, failure to set short names is not an error (since short
1384          * names aren't too important anymore...).  */
1385         if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES)) {
1386                 if (dentry->d_short_name_nbytes)
1387                         ctx->num_set_short_name_failures++;
1388                 else
1389                         ctx->num_remove_short_name_failures++;
1390                 return 0;
1391         }
1392
1393         winnt_error(status, L"Can't set short name on \"%ls\"", current_path(ctx));
1394         return WIMLIB_ERR_SET_SHORT_NAME;
1395 }
1396
1397 /*
1398  * A wrapper around NtCreateFile() to make it slightly more usable...
1399  * This uses the path currently constructed in ctx->pathbuf.
1400  *
1401  * Also, we always specify SYNCHRONIZE access, FILE_OPEN_FOR_BACKUP_INTENT, and
1402  * FILE_OPEN_REPARSE_POINT.
1403  */
1404 static NTSTATUS
1405 do_create_file(PHANDLE FileHandle,
1406                ACCESS_MASK DesiredAccess,
1407                PLARGE_INTEGER AllocationSize,
1408                ULONG FileAttributes,
1409                ULONG CreateDisposition,
1410                ULONG CreateOptions,
1411                struct win32_apply_ctx *ctx)
1412 {
1413         return NtCreateFile(FileHandle,
1414                             DesiredAccess | SYNCHRONIZE,
1415                             &ctx->attr,
1416                             &ctx->iosb,
1417                             AllocationSize,
1418                             FileAttributes,
1419                             FILE_SHARE_VALID_FLAGS,
1420                             CreateDisposition,
1421                             CreateOptions |
1422                                 FILE_OPEN_FOR_BACKUP_INTENT |
1423                                 FILE_OPEN_REPARSE_POINT,
1424                             NULL,
1425                             0);
1426 }
1427
1428 /* Like do_create_file(), but builds the extraction path of the @dentry first.
1429  */
1430 static NTSTATUS
1431 create_file(PHANDLE FileHandle,
1432             ACCESS_MASK DesiredAccess,
1433             PLARGE_INTEGER AllocationSize,
1434             ULONG FileAttributes,
1435             ULONG CreateDisposition,
1436             ULONG CreateOptions,
1437             const struct wim_dentry *dentry,
1438             struct win32_apply_ctx *ctx)
1439 {
1440         build_extraction_path(dentry, ctx);
1441         return do_create_file(FileHandle,
1442                               DesiredAccess,
1443                               AllocationSize,
1444                               FileAttributes,
1445                               CreateDisposition,
1446                               CreateOptions,
1447                               ctx);
1448 }
1449
1450 static int
1451 delete_file_or_stream(struct win32_apply_ctx *ctx)
1452 {
1453         NTSTATUS status;
1454         HANDLE h;
1455         ULONG perms = DELETE;
1456         ULONG flags = FILE_NON_DIRECTORY_FILE | FILE_DELETE_ON_CLOSE;
1457
1458         /* First try opening the file with FILE_DELETE_ON_CLOSE.  In most cases,
1459          * all we have to do is that plus close the file handle.  */
1460 retry:
1461         status = do_create_file(&h, perms, NULL, 0, FILE_OPEN, flags, ctx);
1462
1463         if (unlikely(status == STATUS_CANNOT_DELETE)) {
1464                 /* This error occurs for files with FILE_ATTRIBUTE_READONLY set.
1465                  * Try an alternate approach: first open the file without
1466                  * FILE_DELETE_ON_CLOSE, then reset the file attributes, then
1467                  * set the "delete" disposition on the handle.  */
1468                 if (flags & FILE_DELETE_ON_CLOSE) {
1469                         flags &= ~FILE_DELETE_ON_CLOSE;
1470                         perms |= FILE_WRITE_ATTRIBUTES;
1471                         goto retry;
1472                 }
1473         }
1474
1475         if (unlikely(!NT_SUCCESS(status))) {
1476                 winnt_error(status, L"Can't open \"%ls\" for deletion "
1477                             "(perms=%x, flags=%x)",
1478                             current_path(ctx), perms, flags);
1479                 return WIMLIB_ERR_OPEN;
1480         }
1481
1482         if (unlikely(!(flags & FILE_DELETE_ON_CLOSE))) {
1483
1484                 FILE_BASIC_INFORMATION basic_info =
1485                         { .FileAttributes = FILE_ATTRIBUTE_NORMAL };
1486                 status = NtSetInformationFile(h, &ctx->iosb, &basic_info,
1487                                               sizeof(basic_info),
1488                                               FileBasicInformation);
1489
1490                 if (!NT_SUCCESS(status)) {
1491                         winnt_error(status, L"Can't reset attributes of \"%ls\" "
1492                                     "to prepare for deletion", current_path(ctx));
1493                         NtClose(h);
1494                         return WIMLIB_ERR_SET_ATTRIBUTES;
1495                 }
1496
1497                 FILE_DISPOSITION_INFORMATION disp_info =
1498                         { .DoDeleteFile = TRUE };
1499                 status = NtSetInformationFile(h, &ctx->iosb, &disp_info,
1500                                               sizeof(disp_info),
1501                                               FileDispositionInformation);
1502                 if (!NT_SUCCESS(status)) {
1503                         winnt_error(status, L"Can't set delete-on-close "
1504                                     "disposition on \"%ls\"", current_path(ctx));
1505                         NtClose(h);
1506                         return WIMLIB_ERR_SET_ATTRIBUTES;
1507                 }
1508         }
1509
1510         status = NtClose(h);
1511         if (unlikely(!NT_SUCCESS(status))) {
1512                 winnt_error(status, L"Error closing \"%ls\" after setting "
1513                             "delete-on-close disposition", current_path(ctx));
1514                 return WIMLIB_ERR_OPEN;
1515         }
1516
1517         return 0;
1518 }
1519
1520 /*
1521  * Create a nondirectory file or named data stream at the current path,
1522  * superseding any that already exists at that path.  If successful, return an
1523  * open handle to the file or named data stream with the requested permissions.
1524  */
1525 static int
1526 supersede_file_or_stream(struct win32_apply_ctx *ctx, DWORD perms,
1527                          HANDLE *h_ret)
1528 {
1529         NTSTATUS status;
1530         bool retried = false;
1531
1532         /* FILE_ATTRIBUTE_SYSTEM is needed to ensure that
1533          * FILE_ATTRIBUTE_ENCRYPTED doesn't get set before we want it to be.  */
1534 retry:
1535         status = do_create_file(h_ret,
1536                                 perms,
1537                                 NULL,
1538                                 FILE_ATTRIBUTE_SYSTEM,
1539                                 FILE_CREATE,
1540                                 FILE_NON_DIRECTORY_FILE,
1541                                 ctx);
1542         if (likely(NT_SUCCESS(status)))
1543                 return 0;
1544
1545         /* STATUS_OBJECT_NAME_COLLISION means that the file or stream already
1546          * exists.  Delete the existing file or stream, then try again.
1547          *
1548          * Note: we don't use FILE_OVERWRITE_IF or FILE_SUPERSEDE because of
1549          * problems with certain file attributes, especially
1550          * FILE_ATTRIBUTE_ENCRYPTED.  FILE_SUPERSEDE is also broken in the
1551          * Windows PE ramdisk.  */
1552         if (status == STATUS_OBJECT_NAME_COLLISION && !retried) {
1553                 int ret = delete_file_or_stream(ctx);
1554                 if (ret)
1555                         return ret;
1556                 retried = true;
1557                 goto retry;
1558         }
1559         winnt_error(status, L"Can't create \"%ls\"", current_path(ctx));
1560         return WIMLIB_ERR_OPEN;
1561 }
1562
1563 /* Set the reparse point @rpbuf of length @rpbuflen on the extracted file
1564  * corresponding to the WIM dentry @dentry.  */
1565 static int
1566 do_set_reparse_point(const struct wim_dentry *dentry,
1567                      const struct reparse_buffer_disk *rpbuf, u16 rpbuflen,
1568                      struct win32_apply_ctx *ctx)
1569 {
1570         NTSTATUS status;
1571         HANDLE h;
1572
1573         status = create_file(&h, GENERIC_WRITE, NULL,
1574                              0, FILE_OPEN, 0, dentry, ctx);
1575         if (!NT_SUCCESS(status))
1576                 goto fail;
1577
1578         status = winnt_fsctl(h, FSCTL_SET_REPARSE_POINT,
1579                              rpbuf, rpbuflen, NULL, 0, NULL);
1580         NtClose(h);
1581
1582         if (NT_SUCCESS(status))
1583                 return 0;
1584
1585         /* On Windows, by default only the Administrator can create symbolic
1586          * links for some reason.  By default we just issue a warning if this
1587          * appears to be the problem.  Use WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS
1588          * to get a hard error.  */
1589         if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS)
1590             && (status == STATUS_PRIVILEGE_NOT_HELD ||
1591                 status == STATUS_ACCESS_DENIED)
1592             && (dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1593                 dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1594         {
1595                 WARNING("Can't create symbolic link \"%ls\"!              \n"
1596                         "          (Need Administrator rights, or at least "
1597                         "the\n"
1598                         "          SeCreateSymbolicLink privilege.)",
1599                         current_path(ctx));
1600                 return 0;
1601         }
1602
1603 fail:
1604         winnt_error(status, L"Can't set reparse data on \"%ls\"",
1605                     current_path(ctx));
1606         return WIMLIB_ERR_SET_REPARSE_DATA;
1607 }
1608
1609 /*
1610  * Create empty named data streams and potentially a reparse point for the
1611  * specified file, if any.
1612  *
1613  * Since these won't have blob descriptors, they won't show up in the call to
1614  * extract_blob_list().  Hence the need for the special case.
1615  */
1616 static int
1617 create_empty_streams(const struct wim_dentry *dentry,
1618                      struct win32_apply_ctx *ctx)
1619 {
1620         const struct wim_inode *inode = dentry->d_inode;
1621         int ret;
1622
1623         for (unsigned i = 0; i < inode->i_num_streams; i++) {
1624                 const struct wim_inode_stream *strm = &inode->i_streams[i];
1625
1626                 if (stream_blob_resolved(strm) != NULL)
1627                         continue;
1628
1629                 if (strm->stream_type == STREAM_TYPE_REPARSE_POINT &&
1630                     ctx->common.supported_features.reparse_points)
1631                 {
1632                         u8 buf[REPARSE_DATA_OFFSET] _aligned_attribute(8);
1633                         struct reparse_buffer_disk *rpbuf =
1634                                 (struct reparse_buffer_disk *)buf;
1635                         complete_reparse_point(rpbuf, inode, 0);
1636                         ret = do_set_reparse_point(dentry, rpbuf,
1637                                                    REPARSE_DATA_OFFSET, ctx);
1638                         if (ret)
1639                                 return ret;
1640                 } else if (stream_is_named_data_stream(strm) &&
1641                            ctx->common.supported_features.named_data_streams)
1642                 {
1643                         HANDLE h;
1644
1645                         build_extraction_path_with_ads(dentry, ctx,
1646                                                        strm->stream_name,
1647                                                        utf16le_len_chars(strm->stream_name));
1648                         /*
1649                          * Note: do not request any permissions on the handle.
1650                          * Otherwise, we may encounter a Windows bug where the
1651                          * parent directory DACL denies read access to the new
1652                          * named data stream, even when using backup semantics!
1653                          */
1654                         ret = supersede_file_or_stream(ctx, 0, &h);
1655
1656                         build_extraction_path(dentry, ctx);
1657
1658                         if (ret)
1659                                 return ret;
1660                         NtClose(h);
1661                 }
1662         }
1663
1664         return 0;
1665 }
1666
1667 /*
1668  * Creates the directory named by @dentry, or uses an existing directory at that
1669  * location.  If necessary, sets the short name and/or fixes compression and
1670  * encryption attributes.
1671  *
1672  * Returns 0, WIMLIB_ERR_MKDIR, or WIMLIB_ERR_SET_SHORT_NAME.
1673  */
1674 static int
1675 create_directory(const struct wim_dentry *dentry, struct win32_apply_ctx *ctx)
1676 {
1677         DWORD perms;
1678         NTSTATUS status;
1679         HANDLE h;
1680         int ret;
1681
1682         /* DELETE is needed for set_short_name(); GENERIC_READ and GENERIC_WRITE
1683          * are needed for adjust_compression_attribute().  */
1684         perms = GENERIC_READ | GENERIC_WRITE;
1685         if (!dentry_is_root(dentry))
1686                 perms |= DELETE;
1687
1688         /* FILE_ATTRIBUTE_SYSTEM is needed to ensure that
1689          * FILE_ATTRIBUTE_ENCRYPTED doesn't get set before we want it to be.  */
1690         status = create_file(&h, perms, NULL, FILE_ATTRIBUTE_SYSTEM,
1691                              FILE_OPEN_IF, FILE_DIRECTORY_FILE, dentry, ctx);
1692         if (unlikely(!NT_SUCCESS(status))) {
1693                 const wchar_t *path = current_path(ctx);
1694                 winnt_error(status, L"Can't create directory \"%ls\"", path);
1695
1696                 /* Check for known issue with WindowsApps directory.  */
1697                 if (status == STATUS_ACCESS_DENIED &&
1698                     (wcsstr(path, L"\\WindowsApps\\") ||
1699                      wcsstr(path, L"\\InfusedApps\\"))) {
1700                         ERROR(
1701 "You seem to be trying to extract files to the WindowsApps directory.\n"
1702 "        Windows 8.1 and later use new file permissions in this directory that\n"
1703 "        cannot be overridden, even by backup/restore programs.  To extract your\n"
1704 "        files anyway, you need to choose a different target directory, delete\n"
1705 "        the WindowsApps directory entirely, reformat the volume, do the\n"
1706 "        extraction from a non-broken operating system such as Windows 7 or\n"
1707 "        Linux, or wait for Microsoft to fix the design flaw in their operating\n"
1708 "        system.  This is *not* a bug in wimlib.  See this thread for more\n"
1709 "        information: https://wimlib.net/forums/viewtopic.php?f=1&t=261");
1710                 }
1711                 return WIMLIB_ERR_MKDIR;
1712         }
1713
1714         if (ctx->iosb.Information == FILE_OPENED) {
1715                 /* If we opened an existing directory, try to clear its file
1716                  * attributes.  As far as I know, this only actually makes a
1717                  * difference in the case where a FILE_ATTRIBUTE_READONLY
1718                  * directory has a named data stream which needs to be
1719                  * extracted.  You cannot create a named data stream of such a
1720                  * directory, even though this contradicts Microsoft's
1721                  * documentation for FILE_ATTRIBUTE_READONLY which states it is
1722                  * not honored for directories!  */
1723                 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)) {
1724                         FILE_BASIC_INFORMATION basic_info =
1725                                 { .FileAttributes = FILE_ATTRIBUTE_NORMAL };
1726                         NtSetInformationFile(h, &ctx->iosb, &basic_info,
1727                                              sizeof(basic_info),
1728                                              FileBasicInformation);
1729                 }
1730         }
1731
1732         if (!dentry_is_root(dentry)) {
1733                 ret = set_short_name(h, dentry, ctx);
1734                 if (ret)
1735                         goto out;
1736         }
1737
1738         ret = adjust_compression_attribute(h, dentry, ctx);
1739 out:
1740         NtClose(h);
1741         return ret;
1742 }
1743
1744 /*
1745  * Create all the directories being extracted, other than the target directory
1746  * itself.
1747  *
1748  * Note: we don't honor directory hard links.  However, we don't allow them to
1749  * exist in WIM images anyway (see inode_fixup.c).
1750  */
1751 static int
1752 create_directories(struct list_head *dentry_list,
1753                    struct win32_apply_ctx *ctx)
1754 {
1755         const struct wim_dentry *dentry;
1756         int ret;
1757
1758         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1759
1760                 if (!(dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY))
1761                         continue;
1762
1763                 /* Note: Here we include files with
1764                  * FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT, but we
1765                  * wait until later to actually set the reparse data.  */
1766
1767                 ret = create_directory(dentry, ctx);
1768
1769                 if (!ret)
1770                         ret = create_empty_streams(dentry, ctx);
1771
1772                 ret = check_apply_error(dentry, ctx, ret);
1773                 if (ret)
1774                         return ret;
1775
1776                 ret = report_file_created(&ctx->common);
1777                 if (ret)
1778                         return ret;
1779         }
1780         return 0;
1781 }
1782
1783 /*
1784  * Creates the nondirectory file named by @dentry.
1785  *
1786  * On success, returns an open handle to the file in @h_ret, with GENERIC_READ,
1787  * GENERIC_WRITE, and DELETE access.  Also, the path to the file will be saved
1788  * in ctx->pathbuf.  On failure, returns an error code.
1789  */
1790 static int
1791 create_nondirectory_inode(HANDLE *h_ret, const struct wim_dentry *dentry,
1792                           struct win32_apply_ctx *ctx)
1793 {
1794         int ret;
1795         HANDLE h;
1796
1797         build_extraction_path(dentry, ctx);
1798
1799         ret = supersede_file_or_stream(ctx,
1800                                        GENERIC_READ | GENERIC_WRITE | DELETE,
1801                                        &h);
1802         if (ret)
1803                 goto out;
1804
1805         ret = adjust_compression_attribute(h, dentry, ctx);
1806         if (ret)
1807                 goto out_close;
1808
1809         if (need_sparse_flag(dentry->d_inode, ctx)) {
1810                 ret = set_sparse_flag(h, ctx);
1811                 if (ret)
1812                         goto out_close;
1813         }
1814
1815         ret = create_empty_streams(dentry, ctx);
1816         if (ret)
1817                 goto out_close;
1818
1819         *h_ret = h;
1820         return 0;
1821
1822 out_close:
1823         NtClose(h);
1824 out:
1825         return ret;
1826 }
1827
1828 /* Creates a hard link at the location named by @dentry to the file represented
1829  * by the open handle @h.  Or, if the target volume does not support hard links,
1830  * create a separate file instead.  */
1831 static int
1832 create_link(HANDLE h, const struct wim_dentry *dentry,
1833             struct win32_apply_ctx *ctx)
1834 {
1835         if (ctx->common.supported_features.hard_links) {
1836
1837                 build_extraction_path(dentry, ctx);
1838
1839                 size_t bufsize = offsetof(FILE_LINK_INFORMATION, FileName) +
1840                                  ctx->pathbuf.Length + sizeof(wchar_t);
1841                 u8 buf[bufsize] _aligned_attribute(8);
1842                 FILE_LINK_INFORMATION *info = (FILE_LINK_INFORMATION *)buf;
1843                 NTSTATUS status;
1844
1845                 info->ReplaceIfExists = TRUE;
1846                 info->RootDirectory = ctx->attr.RootDirectory;
1847                 info->FileNameLength = ctx->pathbuf.Length;
1848                 memcpy(info->FileName, ctx->pathbuf.Buffer, ctx->pathbuf.Length);
1849                 info->FileName[info->FileNameLength / 2] = L'\0';
1850
1851                 /* Note: the null terminator isn't actually necessary,
1852                  * but if you don't add the extra character, you get
1853                  * STATUS_INFO_LENGTH_MISMATCH when FileNameLength
1854                  * happens to be 2  */
1855
1856                 status = NtSetInformationFile(h, &ctx->iosb, info, bufsize,
1857                                               FileLinkInformation);
1858                 if (NT_SUCCESS(status))
1859                         return 0;
1860                 winnt_error(status, L"Failed to create link \"%ls\"",
1861                             current_path(ctx));
1862                 return WIMLIB_ERR_LINK;
1863         } else {
1864                 HANDLE h2;
1865                 int ret;
1866
1867                 ret = create_nondirectory_inode(&h2, dentry, ctx);
1868                 if (ret)
1869                         return ret;
1870
1871                 NtClose(h2);
1872                 return 0;
1873         }
1874 }
1875
1876 /* Given an inode (represented by the open handle @h) for which one link has
1877  * been created (named by @first_dentry), create the other links.
1878  *
1879  * Or, if the target volume does not support hard links, create separate files.
1880  *
1881  * Note: This uses ctx->pathbuf and does not reset it.
1882  */
1883 static int
1884 create_links(HANDLE h, const struct wim_dentry *first_dentry,
1885              struct win32_apply_ctx *ctx)
1886 {
1887         const struct wim_inode *inode = first_dentry->d_inode;
1888         const struct wim_dentry *dentry;
1889         int ret;
1890
1891         inode_for_each_extraction_alias(dentry, inode) {
1892                 if (dentry != first_dentry) {
1893                         ret = create_link(h, dentry, ctx);
1894                         if (ret)
1895                                 return ret;
1896                 }
1897         }
1898         return 0;
1899 }
1900
1901 /* Create a nondirectory file, including all links.  */
1902 static int
1903 create_nondirectory(struct wim_inode *inode, struct win32_apply_ctx *ctx)
1904 {
1905         struct wim_dentry *first_dentry;
1906         HANDLE h;
1907         int ret;
1908
1909         first_dentry = first_extraction_alias(inode);
1910
1911         /* Create first link.  */
1912         ret = create_nondirectory_inode(&h, first_dentry, ctx);
1913         if (ret)
1914                 return ret;
1915
1916         /* Set short name.  */
1917         ret = set_short_name(h, first_dentry, ctx);
1918
1919         /* Create additional links, OR if hard links are not supported just
1920          * create more files.  */
1921         if (!ret)
1922                 ret = create_links(h, first_dentry, ctx);
1923
1924         /* "WIMBoot" extraction: set external backing by the WIM file if needed.  */
1925         if (!ret && unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
1926                 ret = set_backed_from_wim(h, inode, ctx);
1927
1928         NtClose(h);
1929         return ret;
1930 }
1931
1932 /* Create all the nondirectory files being extracted, including all aliases
1933  * (hard links).  */
1934 static int
1935 create_nondirectories(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1936 {
1937         struct wim_dentry *dentry;
1938         struct wim_inode *inode;
1939         int ret;
1940
1941         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1942                 inode = dentry->d_inode;
1943                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1944                         continue;
1945                 /* Call create_nondirectory() only once per inode  */
1946                 if (dentry == inode_first_extraction_dentry(inode)) {
1947                         ret = create_nondirectory(inode, ctx);
1948                         ret = check_apply_error(dentry, ctx, ret);
1949                         if (ret)
1950                                 return ret;
1951                 }
1952                 ret = report_file_created(&ctx->common);
1953                 if (ret)
1954                         return ret;
1955         }
1956         return 0;
1957 }
1958
1959 static void
1960 close_handles(struct win32_apply_ctx *ctx)
1961 {
1962         for (unsigned i = 0; i < ctx->num_open_handles; i++)
1963                 NtClose(ctx->open_handles[i]);
1964 }
1965
1966 /* Prepare to read the next blob, which has size @blob_size, into an in-memory
1967  * buffer.  */
1968 static bool
1969 prepare_data_buffer(struct win32_apply_ctx *ctx, u64 blob_size)
1970 {
1971         if (blob_size > ctx->data_buffer_size) {
1972                 /* Larger buffer needed.  */
1973                 void *new_buffer;
1974                 if ((size_t)blob_size != blob_size)
1975                         return false;
1976                 new_buffer = REALLOC(ctx->data_buffer, blob_size);
1977                 if (!new_buffer)
1978                         return false;
1979                 ctx->data_buffer = new_buffer;
1980                 ctx->data_buffer_size = blob_size;
1981         }
1982         /* On the first call this changes data_buffer_ptr from NULL, which tells
1983          * extract_chunk() that the data buffer needs to be filled while reading
1984          * the stream data.  */
1985         ctx->data_buffer_ptr = ctx->data_buffer;
1986         return true;
1987 }
1988
1989 static int
1990 begin_extract_blob_instance(const struct blob_descriptor *blob,
1991                             struct wim_dentry *dentry,
1992                             const struct wim_inode_stream *strm,
1993                             struct win32_apply_ctx *ctx)
1994 {
1995         HANDLE h;
1996         NTSTATUS status;
1997
1998         if (unlikely(strm->stream_type == STREAM_TYPE_REPARSE_POINT)) {
1999                 /* We can't write the reparse point stream directly; we must set
2000                  * it with FSCTL_SET_REPARSE_POINT, which requires that all the
2001                  * data be available.  So, stage the data in a buffer.  */
2002                 if (!prepare_data_buffer(ctx, blob->size))
2003                         return WIMLIB_ERR_NOMEM;
2004                 list_add_tail(&dentry->d_tmp_list, &ctx->reparse_dentries);
2005                 return 0;
2006         }
2007
2008         if (unlikely(strm->stream_type == STREAM_TYPE_EFSRPC_RAW_DATA)) {
2009                 /* We can't write encrypted files directly; we must use
2010                  * WriteEncryptedFileRaw(), which requires providing the data
2011                  * through a callback function.  This can't easily be combined
2012                  * with our own callback-based approach.
2013                  *
2014                  * The current workaround is to simply read the blob into memory
2015                  * and write the encrypted file from that.
2016                  *
2017                  * TODO: This isn't sufficient for extremely large encrypted
2018                  * files.  Perhaps we should create an extra thread to write
2019                  * such files...  */
2020                 if (!prepare_data_buffer(ctx, blob->size))
2021                         return WIMLIB_ERR_NOMEM;
2022                 list_add_tail(&dentry->d_tmp_list, &ctx->encrypted_dentries);
2023                 return 0;
2024         }
2025
2026         /* It's a data stream (may be unnamed or named).  */
2027         wimlib_assert(strm->stream_type == STREAM_TYPE_DATA);
2028
2029         if (ctx->num_open_handles == MAX_OPEN_FILES) {
2030                 /* XXX: Fix this.  But because of the checks in
2031                  * extract_blob_list(), this can now only happen on a filesystem
2032                  * that does not support hard links.  */
2033                 ERROR("Can't extract data: too many open files!");
2034                 return WIMLIB_ERR_UNSUPPORTED;
2035         }
2036
2037
2038         if (unlikely(stream_is_named(strm))) {
2039                 build_extraction_path_with_ads(dentry, ctx,
2040                                                strm->stream_name,
2041                                                utf16le_len_chars(strm->stream_name));
2042         } else {
2043                 build_extraction_path(dentry, ctx);
2044         }
2045
2046
2047         /* Open a new handle  */
2048         status = do_create_file(&h,
2049                                 FILE_WRITE_DATA | SYNCHRONIZE,
2050                                 NULL, 0, FILE_OPEN_IF,
2051                                 FILE_SEQUENTIAL_ONLY |
2052                                         FILE_SYNCHRONOUS_IO_NONALERT,
2053                                 ctx);
2054         if (!NT_SUCCESS(status)) {
2055                 winnt_error(status, L"Can't open \"%ls\" for writing",
2056                             current_path(ctx));
2057                 return WIMLIB_ERR_OPEN;
2058         }
2059
2060         ctx->is_sparse_stream[ctx->num_open_handles] = false;
2061         if (need_sparse_flag(dentry->d_inode, ctx)) {
2062                 /* If the stream is unnamed, then the sparse flag was already
2063                  * set when the file was created.  But if the stream is named,
2064                  * then we need to set the sparse flag here. */
2065                 if (unlikely(stream_is_named(strm))) {
2066                         int ret = set_sparse_flag(h, ctx);
2067                         if (ret) {
2068                                 NtClose(h);
2069                                 return ret;
2070                         }
2071                 }
2072                 ctx->is_sparse_stream[ctx->num_open_handles] = true;
2073                 ctx->any_sparse_streams = true;
2074         } else {
2075                 /* Allocate space for the data.  */
2076                 FILE_ALLOCATION_INFORMATION info =
2077                         { .AllocationSize = { .QuadPart = blob->size }};
2078                 NtSetInformationFile(h, &ctx->iosb, &info, sizeof(info),
2079                                      FileAllocationInformation);
2080         }
2081         ctx->open_handles[ctx->num_open_handles++] = h;
2082         return 0;
2083 }
2084
2085 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
2086  * pointer to the suffix of the path that begins with the device directly, such
2087  * as e:\Windows\System32.  */
2088 static const wchar_t *
2089 skip_nt_toplevel_component(const wchar_t *path, size_t path_nchars)
2090 {
2091         static const wchar_t * const dirs[] = {
2092                 L"\\??\\",
2093                 L"\\DosDevices\\",
2094                 L"\\Device\\",
2095         };
2096         const wchar_t * const end = path + path_nchars;
2097
2098         for (size_t i = 0; i < ARRAY_LEN(dirs); i++) {
2099                 size_t len = wcslen(dirs[i]);
2100                 if (len <= (end - path) && !wmemcmp(path, dirs[i], len)) {
2101                         path += len;
2102                         while (path != end && *path == L'\\')
2103                                 path++;
2104                         return path;
2105                 }
2106         }
2107         return path;
2108 }
2109
2110 /*
2111  * Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
2112  * pointer to the suffix of the path that is device-relative but possibly with
2113  * leading slashes, such as \Windows\System32.
2114  *
2115  * The path has an explicit length and is not necessarily null terminated.
2116  */
2117 static const wchar_t *
2118 get_device_relative_path(const wchar_t *path, size_t path_nchars)
2119 {
2120         const wchar_t * const orig_path = path;
2121         const wchar_t * const end = path + path_nchars;
2122
2123         path = skip_nt_toplevel_component(path, path_nchars);
2124         if (path == orig_path)
2125                 return orig_path;
2126
2127         while (path != end && *path != L'\\')
2128                 path++;
2129
2130         return path;
2131 }
2132
2133 /*
2134  * Given a reparse point buffer for an inode for which the absolute link target
2135  * was relativized when it was archived, de-relative the link target to be
2136  * consistent with the actual extraction location.
2137  */
2138 static void
2139 try_rpfix(struct reparse_buffer_disk *rpbuf, u16 *rpbuflen_p,
2140           struct win32_apply_ctx *ctx)
2141 {
2142         struct link_reparse_point link;
2143         size_t orig_subst_name_nchars;
2144         const wchar_t *relpath;
2145         size_t relpath_nchars;
2146         size_t target_ntpath_nchars;
2147         size_t fixed_subst_name_nchars;
2148         const wchar_t *fixed_print_name;
2149         size_t fixed_print_name_nchars;
2150
2151         /* Do nothing if the reparse data is invalid.  */
2152         if (parse_link_reparse_point(rpbuf, *rpbuflen_p, &link))
2153                 return;
2154
2155         /* Do nothing if the reparse point is a relative symbolic link.  */
2156         if (link_is_relative_symlink(&link))
2157                 return;
2158
2159         /* Build the new substitute name from the NT namespace path to the
2160          * target directory, then a path separator, then the "device relative"
2161          * part of the old substitute name.  */
2162
2163         orig_subst_name_nchars = link.substitute_name_nbytes / sizeof(wchar_t);
2164
2165         relpath = get_device_relative_path(link.substitute_name,
2166                                            orig_subst_name_nchars);
2167         relpath_nchars = orig_subst_name_nchars -
2168                          (relpath - link.substitute_name);
2169
2170         target_ntpath_nchars = ctx->target_ntpath.Length / sizeof(wchar_t);
2171
2172         /* If the target directory is a filesystem root, such as \??\C:\, then
2173          * it already will have a trailing slash.  Don't include this slash if
2174          * we are already adding slashes via 'relpath'.  This prevents an extra
2175          * slash from being generated each time the link is extracted.  And
2176          * unlike on UNIX, the number of slashes in paths on Windows can be
2177          * significant; Windows won't understand the link target if it contains
2178          * too many slashes.  */
2179         if (target_ntpath_nchars > 0 && relpath_nchars > 0 &&
2180             ctx->target_ntpath.Buffer[target_ntpath_nchars - 1] == L'\\')
2181                 target_ntpath_nchars--;
2182
2183         /* Also remove extra slashes from the beginning of 'relpath'.  Normally
2184          * this isn't needed, but this is here to make the extra slash(es) added
2185          * by wimlib pre-v1.9.1 get removed automatically.  */
2186         while (relpath_nchars >= 2 &&
2187                relpath[0] == L'\\' && relpath[1] == L'\\') {
2188                 relpath++;
2189                 relpath_nchars--;
2190         }
2191
2192         fixed_subst_name_nchars = target_ntpath_nchars + relpath_nchars;
2193
2194         wchar_t fixed_subst_name[fixed_subst_name_nchars];
2195
2196         wmemcpy(fixed_subst_name, ctx->target_ntpath.Buffer, target_ntpath_nchars);
2197         wmemcpy(&fixed_subst_name[target_ntpath_nchars], relpath, relpath_nchars);
2198         /* Doesn't need to be null-terminated.  */
2199
2200         /* Print name should be Win32, but not all NT names can even be
2201          * translated to Win32 names.  But we can at least delete the top-level
2202          * directory, such as \??\, and this will have the expected result in
2203          * the usual case.  */
2204         fixed_print_name = skip_nt_toplevel_component(fixed_subst_name,
2205                                                       fixed_subst_name_nchars);
2206         fixed_print_name_nchars = fixed_subst_name_nchars - (fixed_print_name -
2207                                                              fixed_subst_name);
2208
2209         link.substitute_name = fixed_subst_name;
2210         link.substitute_name_nbytes = fixed_subst_name_nchars * sizeof(wchar_t);
2211         link.print_name = (wchar_t *)fixed_print_name;
2212         link.print_name_nbytes = fixed_print_name_nchars * sizeof(wchar_t);
2213         make_link_reparse_point(&link, rpbuf, rpbuflen_p);
2214 }
2215
2216 /* Sets the reparse point on the specified file.  This handles "fixing" the
2217  * targets of absolute symbolic links and junctions if WIMLIB_EXTRACT_FLAG_RPFIX
2218  * was specified.  */
2219 static int
2220 set_reparse_point(const struct wim_dentry *dentry,
2221                   const struct reparse_buffer_disk *rpbuf, u16 rpbuflen,
2222                   struct win32_apply_ctx *ctx)
2223 {
2224         if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
2225             && !(dentry->d_inode->i_rp_flags & WIM_RP_FLAG_NOT_FIXED))
2226         {
2227                 memcpy(&ctx->rpfixbuf, rpbuf, rpbuflen);
2228                 try_rpfix(&ctx->rpfixbuf, &rpbuflen, ctx);
2229                 rpbuf = &ctx->rpfixbuf;
2230         }
2231         return do_set_reparse_point(dentry, rpbuf, rpbuflen, ctx);
2232
2233 }
2234
2235 /* Import the next block of raw encrypted data  */
2236 static DWORD WINAPI
2237 import_encrypted_data(PBYTE pbData, PVOID pvCallbackContext, PULONG Length)
2238 {
2239         struct win32_apply_ctx *ctx = pvCallbackContext;
2240         ULONG copy_len;
2241
2242         copy_len = min(ctx->encrypted_size - ctx->encrypted_offset, *Length);
2243         memcpy(pbData, &ctx->data_buffer[ctx->encrypted_offset], copy_len);
2244         ctx->encrypted_offset += copy_len;
2245         *Length = copy_len;
2246         return ERROR_SUCCESS;
2247 }
2248
2249 /*
2250  * Write the raw encrypted data to the already-created file (or directory)
2251  * corresponding to @dentry.
2252  *
2253  * The raw encrypted data is provided in ctx->data_buffer, and its size is
2254  * ctx->encrypted_size.
2255  *
2256  * This function may close the target directory, in which case the caller needs
2257  * to re-open it if needed.
2258  */
2259 static int
2260 extract_encrypted_file(const struct wim_dentry *dentry,
2261                        struct win32_apply_ctx *ctx)
2262 {
2263         void *rawctx;
2264         DWORD err;
2265         ULONG flags;
2266         bool retried;
2267
2268         /* Temporarily build a Win32 path for OpenEncryptedFileRaw()  */
2269         build_win32_extraction_path(dentry, ctx);
2270
2271         flags = CREATE_FOR_IMPORT | OVERWRITE_HIDDEN;
2272         if (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
2273                 flags |= CREATE_FOR_DIR;
2274
2275         retried = false;
2276 retry:
2277         err = OpenEncryptedFileRaw(ctx->pathbuf.Buffer, flags, &rawctx);
2278         if (err == ERROR_SHARING_VIOLATION && !retried) {
2279                 /* This can be caused by the handle we have open to the target
2280                  * directory.  Try closing it temporarily.  */
2281                 close_target_directory(ctx);
2282                 retried = true;
2283                 goto retry;
2284         }
2285
2286         /* Restore the NT namespace path  */
2287         build_extraction_path(dentry, ctx);
2288
2289         if (err != ERROR_SUCCESS) {
2290                 win32_error(err, L"Can't open \"%ls\" for encrypted import",
2291                             current_path(ctx));
2292                 return WIMLIB_ERR_OPEN;
2293         }
2294
2295         ctx->encrypted_offset = 0;
2296
2297         err = WriteEncryptedFileRaw(import_encrypted_data, ctx, rawctx);
2298
2299         CloseEncryptedFileRaw(rawctx);
2300
2301         if (err != ERROR_SUCCESS) {
2302                 win32_error(err, L"Can't import encrypted file \"%ls\"",
2303                             current_path(ctx));
2304                 return WIMLIB_ERR_WRITE;
2305         }
2306
2307         return 0;
2308 }
2309
2310 /* Called when starting to read a blob for extraction */
2311 static int
2312 win32_begin_extract_blob(struct blob_descriptor *blob, void *_ctx)
2313 {
2314         struct win32_apply_ctx *ctx = _ctx;
2315         const struct blob_extraction_target *targets = blob_extraction_targets(blob);
2316         int ret;
2317
2318         ctx->num_open_handles = 0;
2319         ctx->data_buffer_ptr = NULL;
2320         ctx->any_sparse_streams = false;
2321         INIT_LIST_HEAD(&ctx->reparse_dentries);
2322         INIT_LIST_HEAD(&ctx->encrypted_dentries);
2323
2324         for (u32 i = 0; i < blob->out_refcnt; i++) {
2325                 const struct wim_inode *inode = targets[i].inode;
2326                 const struct wim_inode_stream *strm = targets[i].stream;
2327                 struct wim_dentry *dentry;
2328
2329                 /* A copy of the blob needs to be extracted to @inode.  */
2330
2331                 if (ctx->common.supported_features.hard_links) {
2332                         dentry = inode_first_extraction_dentry(inode);
2333                         ret = begin_extract_blob_instance(blob, dentry, strm, ctx);
2334                         ret = check_apply_error(dentry, ctx, ret);
2335                         if (ret)
2336                                 goto fail;
2337                 } else {
2338                         /* Hard links not supported.  Extract the blob
2339                          * separately to each alias of the inode.  */
2340                         inode_for_each_extraction_alias(dentry, inode) {
2341                                 ret = begin_extract_blob_instance(blob, dentry, strm, ctx);
2342                                 ret = check_apply_error(dentry, ctx, ret);
2343                                 if (ret)
2344                                         goto fail;
2345                         }
2346                 }
2347         }
2348
2349         return 0;
2350
2351 fail:
2352         close_handles(ctx);
2353         return ret;
2354 }
2355
2356 static int
2357 pwrite_to_handle(HANDLE h, const void *data, size_t size, u64 offset)
2358 {
2359         const void * const end = data + size;
2360         const void *p;
2361         IO_STATUS_BLOCK iosb;
2362         NTSTATUS status;
2363
2364         for (p = data; p != end; p += iosb.Information,
2365                                  offset += iosb.Information)
2366         {
2367                 LARGE_INTEGER offs = { .QuadPart = offset };
2368
2369                 status = NtWriteFile(h, NULL, NULL, NULL, &iosb,
2370                                      (void *)p, min(INT32_MAX, end - p),
2371                                      &offs, NULL);
2372                 if (!NT_SUCCESS(status)) {
2373                         winnt_error(status,
2374                                     L"Error writing data to target volume");
2375                         return WIMLIB_ERR_WRITE;
2376                 }
2377         }
2378         return 0;
2379 }
2380
2381 /* Called when the next chunk of a blob has been read for extraction */
2382 static int
2383 win32_extract_chunk(const struct blob_descriptor *blob, u64 offset,
2384                     const void *chunk, size_t size, void *_ctx)
2385 {
2386         struct win32_apply_ctx *ctx = _ctx;
2387         const void * const end = chunk + size;
2388         const void *p;
2389         bool zeroes;
2390         size_t len;
2391         unsigned i;
2392         int ret;
2393
2394         /*
2395          * For sparse streams, only write nonzero regions.  This lets the
2396          * filesystem use holes to represent zero regions.
2397          */
2398         for (p = chunk; p != end; p += len, offset += len) {
2399                 zeroes = maybe_detect_sparse_region(p, end - p, &len,
2400                                                     ctx->any_sparse_streams);
2401                 for (i = 0; i < ctx->num_open_handles; i++) {
2402                         if (!zeroes || !ctx->is_sparse_stream[i]) {
2403                                 ret = pwrite_to_handle(ctx->open_handles[i],
2404                                                        p, len, offset);
2405                                 if (ret)
2406                                         return ret;
2407                         }
2408                 }
2409         }
2410
2411         /* Copy the data chunk into the buffer (if needed)  */
2412         if (ctx->data_buffer_ptr)
2413                 ctx->data_buffer_ptr = mempcpy(ctx->data_buffer_ptr,
2414                                                chunk, size);
2415         return 0;
2416 }
2417
2418 static int
2419 get_system_compression_format(int extract_flags)
2420 {
2421         if (extract_flags & WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS4K)
2422                 return FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K;
2423
2424         if (extract_flags & WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS8K)
2425                 return FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS8K;
2426
2427         if (extract_flags & WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS16K)
2428                 return FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS16K;
2429
2430         return FILE_PROVIDER_COMPRESSION_FORMAT_LZX;
2431 }
2432
2433
2434 static const wchar_t *
2435 get_system_compression_format_string(int format)
2436 {
2437         switch (format) {
2438         case FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K:
2439                 return L"XPRESS4K";
2440         case FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS8K:
2441                 return L"XPRESS8K";
2442         case FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS16K:
2443                 return L"XPRESS16K";
2444         default:
2445                 return L"LZX";
2446         }
2447 }
2448
2449 static NTSTATUS
2450 set_system_compression(HANDLE h, int format)
2451 {
2452         NTSTATUS status;
2453         struct {
2454                 struct wof_external_info wof_info;
2455                 struct file_provider_external_info file_info;
2456         } in = {
2457                 .wof_info = {
2458                         .version = WOF_CURRENT_VERSION,
2459                         .provider = WOF_PROVIDER_FILE,
2460                 },
2461                 .file_info = {
2462                         .version = FILE_PROVIDER_CURRENT_VERSION,
2463                         .compression_format = format,
2464                 },
2465         };
2466
2467         /* We intentionally use NtFsControlFile() rather than DeviceIoControl()
2468          * here because the "compressing this object would not save space"
2469          * status code does not map to a valid Win32 error code on older
2470          * versions of Windows (before Windows 10?).  This can be a problem if
2471          * the WOFADK driver is being used rather than the regular WOF, since
2472          * WOFADK can be used on older versions of Windows.  */
2473         status = winnt_fsctl(h, FSCTL_SET_EXTERNAL_BACKING,
2474                              &in, sizeof(in), NULL, 0, NULL);
2475
2476         if (status == 0xC000046F) /* "Compressing this object would not save space."  */
2477                 return STATUS_SUCCESS;
2478
2479         return status;
2480 }
2481
2482 /* Hard-coded list of files which the Windows bootloader may need to access
2483  * before the WOF driver has been loaded.  */
2484 static const wchar_t * const bootloader_pattern_strings[] = {
2485         L"*winload.*",
2486         L"*winresume.*",
2487         L"\\Windows\\AppPatch\\drvmain.sdb",
2488         L"\\Windows\\Boot\\DVD\\*",
2489         L"\\Windows\\Boot\\EFI\\*",
2490         L"\\Windows\\bootstat.dat",
2491         L"\\Windows\\Fonts\\vgaoem.fon",
2492         L"\\Windows\\Fonts\\vgasys.fon",
2493         L"\\Windows\\INF\\errata.inf",
2494         L"\\Windows\\System32\\config\\*",
2495         L"\\Windows\\System32\\ntkrnlpa.exe",
2496         L"\\Windows\\System32\\ntoskrnl.exe",
2497         L"\\Windows\\System32\\bootvid.dll",
2498         L"\\Windows\\System32\\ci.dll",
2499         L"\\Windows\\System32\\hal*.dll",
2500         L"\\Windows\\System32\\mcupdate_AuthenticAMD.dll",
2501         L"\\Windows\\System32\\mcupdate_GenuineIntel.dll",
2502         L"\\Windows\\System32\\pshed.dll",
2503         L"\\Windows\\System32\\apisetschema.dll",
2504         L"\\Windows\\System32\\api-ms-win*.dll",
2505         L"\\Windows\\System32\\ext-ms-win*.dll",
2506         L"\\Windows\\System32\\KernelBase.dll",
2507         L"\\Windows\\System32\\drivers\\*.sys",
2508         L"\\Windows\\System32\\*.nls",
2509         L"\\Windows\\System32\\kbd*.dll",
2510         L"\\Windows\\System32\\kd*.dll",
2511         L"\\Windows\\System32\\clfs.sys",
2512         L"\\Windows\\System32\\CodeIntegrity\\driver.stl",
2513 };
2514
2515 static const struct string_list bootloader_patterns = {
2516         .strings = (wchar_t **)bootloader_pattern_strings,
2517         .num_strings = ARRAY_LEN(bootloader_pattern_strings),
2518 };
2519
2520 static NTSTATUS
2521 set_system_compression_on_inode(struct wim_inode *inode, int format,
2522                                 struct win32_apply_ctx *ctx)
2523 {
2524         bool retried = false;
2525         NTSTATUS status;
2526         HANDLE h;
2527
2528         /* If it may be needed for compatibility with the Windows bootloader,
2529          * force this file to XPRESS4K or uncompressed format.  The bootloader
2530          * of Windows 10 supports XPRESS4K only; older versions don't support
2531          * system compression at all.  */
2532         if (!is_image_windows_10_or_later(ctx) ||
2533             format != FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K)
2534         {
2535                 /* We need to check the patterns against every name of the
2536                  * inode, in case any of them match.  */
2537                 struct wim_dentry *dentry;
2538                 inode_for_each_extraction_alias(dentry, inode) {
2539                         bool incompatible;
2540                         bool warned;
2541
2542                         if (calculate_dentry_full_path(dentry)) {
2543                                 ERROR("Unable to compute file path!");
2544                                 return STATUS_NO_MEMORY;
2545                         }
2546
2547                         incompatible = match_pattern_list(dentry->d_full_path,
2548                                                           &bootloader_patterns);
2549                         FREE(dentry->d_full_path);
2550                         dentry->d_full_path = NULL;
2551
2552                         if (!incompatible)
2553                                 continue;
2554
2555                         warned = (ctx->num_system_compression_exclusions++ > 0);
2556
2557                         if (is_image_windows_10_or_later(ctx)) {
2558                                 /* Force to XPRESS4K  */
2559                                 if (!warned) {
2560                                         WARNING("For compatibility with the "
2561                                                 "Windows bootloader, some "
2562                                                 "files are being\n"
2563                                                 "          compacted "
2564                                                 "using the XPRESS4K format "
2565                                                 "instead of the %"TS" format\n"
2566                                                 "          you requested.",
2567                                                 get_system_compression_format_string(format));
2568                                 }
2569                                 format = FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K;
2570                                 break;
2571                         } else {
2572                                 /* Force to uncompressed  */
2573                                 if (!warned) {
2574                                         WARNING("For compatibility with the "
2575                                                 "Windows bootloader, some "
2576                                                 "files will not\n"
2577                                                 "          be compressed with"
2578                                                 " system compression "
2579                                                 "(\"compacted\").");
2580                                 }
2581                                 return STATUS_SUCCESS;
2582                         }
2583
2584                 }
2585         }
2586
2587         /* Open the extracted file.  */
2588         status = create_file(&h, GENERIC_READ | GENERIC_WRITE, NULL,
2589                              0, FILE_OPEN, 0,
2590                              inode_first_extraction_dentry(inode), ctx);
2591
2592         if (!NT_SUCCESS(status))
2593                 return status;
2594 retry:
2595         /* Compress the file.  If the attempt fails with "invalid device
2596          * request", then attach wof.sys (or wofadk.sys) and retry.  */
2597         status = set_system_compression(h, format);
2598         if (unlikely(status == STATUS_INVALID_DEVICE_REQUEST && !retried)) {
2599                 wchar_t drive_path[7];
2600                 if (!win32_get_drive_path(ctx->common.target, drive_path) &&
2601                     win32_try_to_attach_wof(drive_path + 4)) {
2602                         retried = true;
2603                         goto retry;
2604                 }
2605         }
2606
2607         NtClose(h);
2608         return status;
2609 }
2610
2611 /*
2612  * This function is called when doing a "compact-mode" extraction and we just
2613  * finished extracting a blob to one or more locations.  For each location that
2614  * was the unnamed data stream of a file, this function compresses the
2615  * corresponding file using System Compression, if allowed.
2616  *
2617  * Note: we're doing the compression immediately after extracting the data
2618  * rather than during a separate compression pass.  This way should be faster
2619  * since the operating system should still have the file's data cached.
2620  *
2621  * Note: we're having the operating system do the compression, which is not
2622  * ideal because wimlib could create the compressed data faster and more
2623  * efficiently (the compressed data format is identical to a WIM resource).  But
2624  * we seemingly don't have a choice because WOF prevents applications from
2625  * creating its reparse points.
2626  */
2627 static void
2628 handle_system_compression(struct blob_descriptor *blob, struct win32_apply_ctx *ctx)
2629 {
2630         const struct blob_extraction_target *targets = blob_extraction_targets(blob);
2631
2632         const int format = get_system_compression_format(ctx->common.extract_flags);
2633
2634         for (u32 i = 0; i < blob->out_refcnt; i++) {
2635                 struct wim_inode *inode = targets[i].inode;
2636                 struct wim_inode_stream *strm = targets[i].stream;
2637                 NTSTATUS status;
2638
2639                 if (!stream_is_unnamed_data_stream(strm))
2640                         continue;
2641
2642                 if (will_externally_back_inode(inode, ctx, NULL, false) != 0)
2643                         continue;
2644
2645                 status = set_system_compression_on_inode(inode, format, ctx);
2646                 if (likely(NT_SUCCESS(status)))
2647                         continue;
2648
2649                 if (status == STATUS_INVALID_DEVICE_REQUEST) {
2650                         WARNING(
2651           "The request to compress the extracted files using System Compression\n"
2652 "          will not be honored because the operating system or target volume\n"
2653 "          does not support it.  System Compression is only supported on\n"
2654 "          Windows 10 and later, and only on NTFS volumes.");
2655                         ctx->common.extract_flags &= ~COMPACT_FLAGS;
2656                         return;
2657                 }
2658
2659                 ctx->num_system_compression_failures++;
2660                 if (ctx->num_system_compression_failures < 10) {
2661                         winnt_warning(status, L"\"%ls\": Failed to compress "
2662                                       "extracted file using System Compression",
2663                                       current_path(ctx));
2664                 } else if (ctx->num_system_compression_failures == 10) {
2665                         WARNING("Suppressing further warnings about "
2666                                 "System Compression failures.");
2667                 }
2668         }
2669 }
2670
2671 /* Called when a blob has been fully read for extraction */
2672 static int
2673 win32_end_extract_blob(struct blob_descriptor *blob, int status, void *_ctx)
2674 {
2675         struct win32_apply_ctx *ctx = _ctx;
2676         int ret;
2677         const struct wim_dentry *dentry;
2678
2679         /* Extend sparse streams to their final size. */
2680         if (ctx->any_sparse_streams && !status) {
2681                 for (unsigned i = 0; i < ctx->num_open_handles; i++) {
2682                         FILE_END_OF_FILE_INFORMATION info =
2683                                 { .EndOfFile = { .QuadPart = blob->size } };
2684                         NTSTATUS ntstatus;
2685
2686                         if (!ctx->is_sparse_stream[i])
2687                                 continue;
2688
2689                         ntstatus = NtSetInformationFile(ctx->open_handles[i],
2690                                                         &ctx->iosb,
2691                                                         &info, sizeof(info),
2692                                                         FileEndOfFileInformation);
2693                         if (!NT_SUCCESS(ntstatus)) {
2694                                 winnt_error(ntstatus, L"Error writing data to "
2695                                             "target volume (while extending)");
2696                                 status = WIMLIB_ERR_WRITE;
2697                                 break;
2698                         }
2699                 }
2700         }
2701
2702         close_handles(ctx);
2703
2704         if (status)
2705                 return status;
2706
2707         if (unlikely(ctx->common.extract_flags & COMPACT_FLAGS))
2708                 handle_system_compression(blob, ctx);
2709
2710         if (likely(!ctx->data_buffer_ptr))
2711                 return 0;
2712
2713         if (!list_empty(&ctx->reparse_dentries)) {
2714                 if (blob->size > REPARSE_DATA_MAX_SIZE) {
2715                         dentry = list_first_entry(&ctx->reparse_dentries,
2716                                                   struct wim_dentry, d_tmp_list);
2717                         build_extraction_path(dentry, ctx);
2718                         ERROR("Reparse data of \"%ls\" has size "
2719                               "%"PRIu64" bytes (exceeds %u bytes)",
2720                               current_path(ctx), blob->size,
2721                               REPARSE_DATA_MAX_SIZE);
2722                         ret = WIMLIB_ERR_INVALID_REPARSE_DATA;
2723                         return check_apply_error(dentry, ctx, ret);
2724                 }
2725                 /* Reparse data  */
2726                 memcpy(ctx->rpbuf.rpdata, ctx->data_buffer, blob->size);
2727
2728                 list_for_each_entry(dentry, &ctx->reparse_dentries, d_tmp_list) {
2729
2730                         /* Reparse point header  */
2731                         complete_reparse_point(&ctx->rpbuf, dentry->d_inode,
2732                                                blob->size);
2733
2734                         ret = set_reparse_point(dentry, &ctx->rpbuf,
2735                                                 REPARSE_DATA_OFFSET + blob->size,
2736                                                 ctx);
2737                         ret = check_apply_error(dentry, ctx, ret);
2738                         if (ret)
2739                                 return ret;
2740                 }
2741         }
2742
2743         if (!list_empty(&ctx->encrypted_dentries)) {
2744                 ctx->encrypted_size = blob->size;
2745                 list_for_each_entry(dentry, &ctx->encrypted_dentries, d_tmp_list) {
2746                         ret = extract_encrypted_file(dentry, ctx);
2747                         ret = check_apply_error(dentry, ctx, ret);
2748                         if (ret)
2749                                 return ret;
2750                         /* Re-open the target directory if needed.  */
2751                         ret = open_target_directory(ctx);
2752                         if (ret)
2753                                 return ret;
2754                 }
2755         }
2756
2757         return 0;
2758 }
2759
2760 /* Attributes that can't be set directly  */
2761 #define SPECIAL_ATTRIBUTES                      \
2762         (FILE_ATTRIBUTE_REPARSE_POINT   |       \
2763          FILE_ATTRIBUTE_DIRECTORY       |       \
2764          FILE_ATTRIBUTE_ENCRYPTED       |       \
2765          FILE_ATTRIBUTE_SPARSE_FILE     |       \
2766          FILE_ATTRIBUTE_COMPRESSED)
2767
2768 static void
2769 set_object_id(HANDLE h, const struct wim_inode *inode,
2770               struct win32_apply_ctx *ctx)
2771 {
2772         const void *object_id;
2773         u32 len;
2774         NTSTATUS status;
2775
2776         if (!ctx->common.supported_features.object_ids)
2777                 return;
2778
2779         object_id = inode_get_object_id(inode, &len);
2780         if (likely(object_id == NULL))  /* No object ID?  */
2781                 return;
2782
2783         status = winnt_fsctl(h, FSCTL_SET_OBJECT_ID,
2784                              object_id, len, NULL, 0, NULL);
2785         if (NT_SUCCESS(status))
2786                 return;
2787
2788         /* Object IDs must be unique within the filesystem.  A duplicate might
2789          * occur if an image containing object IDs is applied twice to the same
2790          * filesystem.  Arguably, the user should be warned in this case; but
2791          * the reality seems to be that nothing important cares about object IDs
2792          * except the Distributed Link Tracking Service... so for now these
2793          * failures are just ignored.  */
2794         if (status == STATUS_DUPLICATE_NAME ||
2795             status == STATUS_OBJECT_NAME_COLLISION)
2796                 return;
2797
2798         ctx->num_object_id_failures++;
2799         if (ctx->num_object_id_failures < 10) {
2800                 winnt_warning(status, L"Can't set object ID on \"%ls\"",
2801                               current_path(ctx));
2802         } else if (ctx->num_object_id_failures == 10) {
2803                 WARNING("Suppressing further warnings about failure to set "
2804                         "object IDs.");
2805         }
2806 }
2807
2808 /* Set the security descriptor @desc, of @desc_size bytes, on the file with open
2809  * handle @h.  */
2810 static NTSTATUS
2811 set_security_descriptor(HANDLE h, const void *_desc,
2812                         size_t desc_size, struct win32_apply_ctx *ctx)
2813 {
2814         SECURITY_INFORMATION info;
2815         NTSTATUS status;
2816         SECURITY_DESCRIPTOR_RELATIVE *desc;
2817
2818         /*
2819          * Ideally, we would just pass in the security descriptor buffer as-is.
2820          * But it turns out that Windows can mess up the security descriptor
2821          * even when using the low-level NtSetSecurityObject() function:
2822          *
2823          * - Windows will clear SE_DACL_AUTO_INHERITED if it is set in the
2824          *   passed buffer.  To actually get Windows to set
2825          *   SE_DACL_AUTO_INHERITED, the application must set the non-persistent
2826          *   flag SE_DACL_AUTO_INHERIT_REQ.  As usual, Microsoft didn't bother
2827          *   to properly document either of these flags.  It's unclear how
2828          *   important SE_DACL_AUTO_INHERITED actually is, but to be safe we use
2829          *   the SE_DACL_AUTO_INHERIT_REQ workaround to set it if needed.
2830          *
2831          * - The above also applies to the equivalent SACL flags,
2832          *   SE_SACL_AUTO_INHERITED and SE_SACL_AUTO_INHERIT_REQ.
2833          *
2834          * - If the application says that it's setting
2835          *   DACL_SECURITY_INFORMATION, then Windows sets SE_DACL_PRESENT in the
2836          *   resulting security descriptor, even if the security descriptor the
2837          *   application provided did not have a DACL.  This seems to be
2838          *   unavoidable, since omitting DACL_SECURITY_INFORMATION would cause a
2839          *   default DACL to remain.  Fortunately, this behavior seems harmless,
2840          *   since the resulting DACL will still be "null" --- but it will be
2841          *   "the other representation of null".
2842          *
2843          * - The above also applies to SACL_SECURITY_INFORMATION and
2844          *   SE_SACL_PRESENT.  Again, it's seemingly unavoidable but "harmless"
2845          *   that Windows changes the representation of a "null SACL".
2846          */
2847         if (likely(desc_size <= STACK_MAX)) {
2848                 desc = alloca(desc_size);
2849         } else {
2850                 desc = MALLOC(desc_size);
2851                 if (!desc)
2852                         return STATUS_NO_MEMORY;
2853         }
2854
2855         memcpy(desc, _desc, desc_size);
2856
2857         if (likely(desc_size >= 4)) {
2858
2859                 if (desc->Control & SE_DACL_AUTO_INHERITED)
2860                         desc->Control |= SE_DACL_AUTO_INHERIT_REQ;
2861
2862                 if (desc->Control & SE_SACL_AUTO_INHERITED)
2863                         desc->Control |= SE_SACL_AUTO_INHERIT_REQ;
2864         }
2865
2866         /*
2867          * More API insanity.  We want to set the entire security descriptor
2868          * as-is.  But all available APIs require specifying the specific parts
2869          * of the security descriptor being set.  Especially annoying is that
2870          * mandatory integrity labels are part of the SACL, but they aren't set
2871          * with SACL_SECURITY_INFORMATION.  Instead, applications must also
2872          * specify LABEL_SECURITY_INFORMATION (Windows Vista, Windows 7) or
2873          * BACKUP_SECURITY_INFORMATION (Windows 8).  But at least older versions
2874          * of Windows don't error out if you provide these newer flags...
2875          *
2876          * Also, if the process isn't running as Administrator, then it probably
2877          * doesn't have SE_RESTORE_PRIVILEGE.  In this case, it will always get
2878          * the STATUS_PRIVILEGE_NOT_HELD error by trying to set the SACL, even
2879          * if the security descriptor it provided did not have a SACL.  By
2880          * default, in this case we try to recover and set as much of the
2881          * security descriptor as possible --- potentially excluding the DACL, and
2882          * even the owner, as well as the SACL.
2883          */
2884
2885         info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
2886                DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION |
2887                LABEL_SECURITY_INFORMATION | BACKUP_SECURITY_INFORMATION;
2888
2889
2890         /*
2891          * It's also worth noting that SetFileSecurity() is unusable because it
2892          * doesn't request "backup semantics" when it opens the file internally.
2893          * NtSetSecurityObject() seems to be the best function to use in backup
2894          * applications.  (SetSecurityInfo() should also work, but it's harder
2895          * to use and must call NtSetSecurityObject() internally anyway.
2896          * BackupWrite() is theoretically usable as well, but it's inflexible
2897          * and poorly documented.)
2898          */
2899
2900 retry:
2901         status = NtSetSecurityObject(h, info, desc);
2902         if (NT_SUCCESS(status))
2903                 goto out_maybe_free_desc;
2904
2905         /* Failed to set the requested parts of the security descriptor.  If the
2906          * error was permissions-related, try to set fewer parts of the security
2907          * descriptor, unless WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled.  */
2908         if ((status == STATUS_PRIVILEGE_NOT_HELD ||
2909              status == STATUS_ACCESS_DENIED) &&
2910             !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2911         {
2912                 if (info & SACL_SECURITY_INFORMATION) {
2913                         info &= ~(SACL_SECURITY_INFORMATION |
2914                                   LABEL_SECURITY_INFORMATION |
2915                                   BACKUP_SECURITY_INFORMATION);
2916                         ctx->partial_security_descriptors++;
2917                         goto retry;
2918                 }
2919                 if (info & DACL_SECURITY_INFORMATION) {
2920                         info &= ~DACL_SECURITY_INFORMATION;
2921                         goto retry;
2922                 }
2923                 if (info & OWNER_SECURITY_INFORMATION) {
2924                         info &= ~OWNER_SECURITY_INFORMATION;
2925                         goto retry;
2926                 }
2927                 /* Nothing left except GROUP, and if we removed it we
2928                  * wouldn't have anything at all.  */
2929         }
2930
2931         /* No part of the security descriptor could be set, or
2932          * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled and the full security
2933          * descriptor could not be set.  */
2934         if (!(info & SACL_SECURITY_INFORMATION))
2935                 ctx->partial_security_descriptors--;
2936         ctx->no_security_descriptors++;
2937
2938 out_maybe_free_desc:
2939         if (unlikely(desc_size > STACK_MAX))
2940                 FREE(desc);
2941         return status;
2942 }
2943
2944 /* Set metadata on the open file @h from the WIM inode @inode.  */
2945 static int
2946 do_apply_metadata_to_file(HANDLE h, const struct wim_inode *inode,
2947                           struct win32_apply_ctx *ctx)
2948 {
2949         FILE_BASIC_INFORMATION info;
2950         NTSTATUS status;
2951
2952         /* Set the file's object ID if present and object IDs are supported by
2953          * the filesystem.  */
2954         set_object_id(h, inode, ctx);
2955
2956         /* Set the file's security descriptor if present and we're not in
2957          * NO_ACLS mode  */
2958         if (inode_has_security_descriptor(inode) &&
2959             !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
2960         {
2961                 const struct wim_security_data *sd;
2962                 const void *desc;
2963                 size_t desc_size;
2964
2965                 sd = wim_get_current_security_data(ctx->common.wim);
2966                 desc = sd->descriptors[inode->i_security_id];
2967                 desc_size = sd->sizes[inode->i_security_id];
2968
2969                 status = set_security_descriptor(h, desc, desc_size, ctx);
2970                 if (!NT_SUCCESS(status) &&
2971                     (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2972                 {
2973                         winnt_error(status,
2974                                     L"Can't set security descriptor on \"%ls\"",
2975                                     current_path(ctx));
2976                         return WIMLIB_ERR_SET_SECURITY;
2977                 }
2978         }
2979
2980         /* Set attributes and timestamps  */
2981         info.CreationTime.QuadPart = inode->i_creation_time;
2982         info.LastAccessTime.QuadPart = inode->i_last_access_time;
2983         info.LastWriteTime.QuadPart = inode->i_last_write_time;
2984         info.ChangeTime.QuadPart = 0;
2985         if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES) {
2986                 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
2987         } else {
2988                 info.FileAttributes = inode->i_attributes & ~SPECIAL_ATTRIBUTES;
2989                 if (info.FileAttributes == 0)
2990                         info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
2991         }
2992
2993         status = NtSetInformationFile(h, &ctx->iosb, &info, sizeof(info),
2994                                       FileBasicInformation);
2995         /* On FAT volumes we get STATUS_INVALID_PARAMETER if we try to set
2996          * attributes on the root directory.  (Apparently because FAT doesn't
2997          * actually have a place to store those attributes!)  */
2998         if (!NT_SUCCESS(status)
2999             && !(status == STATUS_INVALID_PARAMETER &&
3000                  dentry_is_root(inode_first_extraction_dentry(inode))))
3001         {
3002                 winnt_error(status, L"Can't set basic metadata on \"%ls\"",
3003                             current_path(ctx));
3004                 return WIMLIB_ERR_SET_ATTRIBUTES;
3005         }
3006
3007         return 0;
3008 }
3009
3010 static int
3011 apply_metadata_to_file(const struct wim_dentry *dentry,
3012                        struct win32_apply_ctx *ctx)
3013 {
3014         const struct wim_inode *inode = dentry->d_inode;
3015         DWORD perms;
3016         HANDLE h;
3017         NTSTATUS status;
3018         int ret;
3019
3020         perms = FILE_WRITE_ATTRIBUTES | WRITE_DAC |
3021                 WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
3022
3023         build_extraction_path(dentry, ctx);
3024
3025         /* Open a handle with as many relevant permissions as possible.  */
3026         while (!NT_SUCCESS(status = do_create_file(&h, perms, NULL,
3027                                                    0, FILE_OPEN, 0, ctx)))
3028         {
3029                 if (status == STATUS_PRIVILEGE_NOT_HELD ||
3030                     status == STATUS_ACCESS_DENIED)
3031                 {
3032                         if (perms & ACCESS_SYSTEM_SECURITY) {
3033                                 perms &= ~ACCESS_SYSTEM_SECURITY;
3034                                 continue;
3035                         }
3036                         if (perms & WRITE_DAC) {
3037                                 perms &= ~WRITE_DAC;
3038                                 continue;
3039                         }
3040                         if (perms & WRITE_OWNER) {
3041                                 perms &= ~WRITE_OWNER;
3042                                 continue;
3043                         }
3044                 }
3045                 winnt_error(status, L"Can't open \"%ls\" to set metadata",
3046                             current_path(ctx));
3047                 return WIMLIB_ERR_OPEN;
3048         }
3049
3050         ret = do_apply_metadata_to_file(h, inode, ctx);
3051
3052         NtClose(h);
3053
3054         return ret;
3055 }
3056
3057 static int
3058 apply_metadata(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
3059 {
3060         const struct wim_dentry *dentry;
3061         int ret;
3062
3063         /* We go in reverse so that metadata is set on all a directory's
3064          * children before the directory itself.  This avoids any potential
3065          * problems with attributes, timestamps, or security descriptors.  */
3066         list_for_each_entry_reverse(dentry, dentry_list, d_extraction_list_node)
3067         {
3068                 ret = apply_metadata_to_file(dentry, ctx);
3069                 ret = check_apply_error(dentry, ctx, ret);
3070                 if (ret)
3071                         return ret;
3072                 ret = report_file_metadata_applied(&ctx->common);
3073                 if (ret)
3074                         return ret;
3075         }
3076         return 0;
3077 }
3078
3079 /* Issue warnings about problems during the extraction for which warnings were
3080  * not already issued (due to the high number of potential warnings if we issued
3081  * them per-file).  */
3082 static void
3083 do_warnings(const struct win32_apply_ctx *ctx)
3084 {
3085         if (ctx->partial_security_descriptors == 0
3086             && ctx->no_security_descriptors == 0
3087             && ctx->num_set_short_name_failures == 0
3088         #if 0
3089             && ctx->num_remove_short_name_failures == 0
3090         #endif
3091             )
3092                 return;
3093
3094         WARNING("Extraction to \"%ls\" complete, but with one or more warnings:",
3095                 ctx->common.target);
3096         if (ctx->num_set_short_name_failures) {
3097                 WARNING("- Could not set short names on %lu files or directories",
3098                         ctx->num_set_short_name_failures);
3099         }
3100 #if 0
3101         if (ctx->num_remove_short_name_failures) {
3102                 WARNING("- Could not remove short names on %lu files or directories"
3103                         "          (This is expected on Vista and earlier)",
3104                         ctx->num_remove_short_name_failures);
3105         }
3106 #endif
3107         if (ctx->partial_security_descriptors) {
3108                 WARNING("- Could only partially set the security descriptor\n"
3109                         "            on %lu files or directories.",
3110                         ctx->partial_security_descriptors);
3111         }
3112         if (ctx->no_security_descriptors) {
3113                 WARNING("- Could not set security descriptor at all\n"
3114                         "            on %lu files or directories.",
3115                         ctx->no_security_descriptors);
3116         }
3117         if (ctx->partial_security_descriptors || ctx->no_security_descriptors) {
3118                 WARNING("To fully restore all security descriptors, run the program\n"
3119                         "          with Administrator rights.");
3120         }
3121 }
3122
3123 static u64
3124 count_dentries(const struct list_head *dentry_list)
3125 {
3126         const struct list_head *cur;
3127         u64 count = 0;
3128
3129         list_for_each(cur, dentry_list)
3130                 count++;
3131
3132         return count;
3133 }
3134
3135 /* Extract files from a WIM image to a directory on Windows  */
3136 static int
3137 win32_extract(struct list_head *dentry_list, struct apply_ctx *_ctx)
3138 {
3139         int ret;
3140         struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
3141         u64 dentry_count;
3142
3143         ret = prepare_target(dentry_list, ctx);
3144         if (ret)
3145                 goto out;
3146
3147         if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
3148                 ret = start_wimboot_extraction(dentry_list, ctx);
3149                 if (ret)
3150                         goto out;
3151         }
3152
3153         ctx->windows_build_number = xml_get_windows_build_number(ctx->common.wim->xml_info,
3154                                                                  ctx->common.wim->current_image);
3155
3156         dentry_count = count_dentries(dentry_list);
3157
3158         ret = start_file_structure_phase(&ctx->common, dentry_count);
3159         if (ret)
3160                 goto out;
3161
3162         ret = create_directories(dentry_list, ctx);
3163         if (ret)
3164                 goto out;
3165
3166         ret = create_nondirectories(dentry_list, ctx);
3167         if (ret)
3168                 goto out;
3169
3170         ret = end_file_structure_phase(&ctx->common);
3171         if (ret)
3172                 goto out;
3173
3174         struct read_blob_callbacks cbs = {
3175                 .begin_blob     = win32_begin_extract_blob,
3176                 .continue_blob  = win32_extract_chunk,
3177                 .end_blob       = win32_end_extract_blob,
3178                 .ctx            = ctx,
3179         };
3180         ret = extract_blob_list(&ctx->common, &cbs);
3181         if (ret)
3182                 goto out;
3183
3184         ret = start_file_metadata_phase(&ctx->common, dentry_count);
3185         if (ret)
3186                 goto out;
3187
3188         ret = apply_metadata(dentry_list, ctx);
3189         if (ret)
3190                 goto out;
3191
3192         ret = end_file_metadata_phase(&ctx->common);
3193         if (ret)
3194                 goto out;
3195
3196         if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
3197                 ret = end_wimboot_extraction(ctx);
3198                 if (ret)
3199                         goto out;
3200         }
3201
3202         do_warnings(ctx);
3203 out:
3204         close_target_directory(ctx);
3205         if (ctx->target_ntpath.Buffer)
3206                 HeapFree(GetProcessHeap(), 0, ctx->target_ntpath.Buffer);
3207         FREE(ctx->pathbuf.Buffer);
3208         FREE(ctx->print_buffer);
3209         FREE(ctx->wimboot.wims);
3210         if (ctx->prepopulate_pats) {
3211                 FREE(ctx->prepopulate_pats->strings);
3212                 FREE(ctx->prepopulate_pats);
3213         }
3214         FREE(ctx->mem_prepopulate_pats);
3215         FREE(ctx->data_buffer);
3216         return ret;
3217 }
3218
3219 const struct apply_operations win32_apply_ops = {
3220         .name                   = "Windows",
3221         .get_supported_features = win32_get_supported_features,
3222         .extract                = win32_extract,
3223         .will_back_from_wim     = win32_will_back_from_wim,
3224         .context_size           = sizeof(struct win32_apply_ctx),
3225 };
3226
3227 #endif /* __WIN32__ */