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