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