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