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