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