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