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