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