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