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