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