win32_capture.c: Random cleanups
[wimlib] / src / win32_capture.c
1 /*
2  * win32_capture.c - Windows-specific code for capturing files into a WIM image.
3  *
4  * This now uses the native Windows NT API a lot and not just Win32.
5  */
6
7 /*
8  * Copyright (C) 2013, 2014 Eric Biggers
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
12  * wimlib is free software; you can redistribute it and/or modify it under the
13  * terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your option)
15  * any later version.
16  *
17  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19  * A PARTICULAR PURPOSE. See the GNU General Public License for more
20  * details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with wimlib; if not, see http://www.gnu.org/licenses/.
24  */
25
26 #ifdef __WIN32__
27
28 #ifdef HAVE_CONFIG_H
29 #  include "config.h"
30 #endif
31
32 #include "wimlib/win32_common.h"
33
34 #include "wimlib/capture.h"
35 #include "wimlib/dentry.h"
36 #include "wimlib/encoding.h"
37 #include "wimlib/endianness.h"
38 #include "wimlib/error.h"
39 #include "wimlib/lookup_table.h"
40 #include "wimlib/paths.h"
41 #include "wimlib/reparse.h"
42
43 #include <errno.h>
44
45 struct winnt_scan_stats {
46         unsigned long num_get_sd_access_denied;
47         unsigned long num_get_sacl_priv_notheld;
48 };
49
50 static inline const wchar_t *
51 printable_path(const wchar_t *full_path)
52 {
53         /* Skip over \\?\ or \??\  */
54         return full_path + 4;
55 }
56
57 /*
58  * If cur_dir is not NULL, open an existing file relative to the already-open
59  * directory cur_dir.
60  *
61  * Otherwise, open the file specified by @path, which must be a Windows NT
62  * namespace path.
63  */
64 static NTSTATUS
65 winnt_openat(HANDLE cur_dir, const wchar_t *path, size_t path_nchars,
66              ACCESS_MASK perms, HANDLE *h_ret)
67 {
68         UNICODE_STRING name;
69         OBJECT_ATTRIBUTES attr;
70         IO_STATUS_BLOCK iosb;
71         NTSTATUS status;
72
73         name.Length = path_nchars * sizeof(wchar_t);
74         name.MaximumLength = name.Length + sizeof(wchar_t);
75         name.Buffer = (wchar_t *)path;
76
77         attr.Length = sizeof(attr);
78         attr.RootDirectory = cur_dir;
79         attr.ObjectName = &name;
80         attr.Attributes = 0;
81         attr.SecurityDescriptor = NULL;
82         attr.SecurityQualityOfService = NULL;
83
84 retry:
85         status = (*func_NtOpenFile)(h_ret, perms, &attr, &iosb,
86                                     FILE_SHARE_VALID_FLAGS,
87                                     FILE_OPEN_REPARSE_POINT |
88                                             FILE_OPEN_FOR_BACKUP_INTENT |
89                                             FILE_SYNCHRONOUS_IO_NONALERT |
90                                             FILE_SEQUENTIAL_ONLY);
91         if (!NT_SUCCESS(status)) {
92                 /* Try requesting fewer permissions  */
93                 if (status == STATUS_ACCESS_DENIED ||
94                     status == STATUS_PRIVILEGE_NOT_HELD) {
95                         if (perms & ACCESS_SYSTEM_SECURITY) {
96                                 perms &= ~ACCESS_SYSTEM_SECURITY;
97                                 goto retry;
98                         }
99                         if (perms & READ_CONTROL) {
100                                 perms &= ~READ_CONTROL;
101                                 goto retry;
102                         }
103                 }
104         }
105         return status;
106 }
107
108 /* Read the first @size bytes from the file, or named data stream of a file,
109  * from which the stream entry @lte was created.  */
110 int
111 read_winnt_file_prefix(const struct wim_lookup_table_entry *lte, u64 size,
112                        consume_data_callback_t cb, void *cb_ctx)
113 {
114         const wchar_t *path;
115         HANDLE h;
116         NTSTATUS status;
117         u8 buf[BUFFER_SIZE];
118         u64 bytes_remaining;
119         int ret;
120
121         /* This is an NT namespace path.  */
122         path = lte->file_on_disk;
123
124         status = winnt_openat(NULL, path, wcslen(path),
125                               FILE_READ_DATA | SYNCHRONIZE, &h);
126         if (!NT_SUCCESS(status)) {
127                 set_errno_from_nt_status(status);
128                 ERROR_WITH_ERRNO("\"%ls\": Can't open for reading "
129                                  "(status=0x%08"PRIx32")",
130                                  printable_path(path), (u32)status);
131                 return WIMLIB_ERR_OPEN;
132         }
133
134         ret = 0;
135         bytes_remaining = size;
136         while (bytes_remaining) {
137                 IO_STATUS_BLOCK iosb;
138                 ULONG count;
139                 ULONG bytes_read;
140
141                 count = min(sizeof(buf), bytes_remaining);
142
143                 status = (*func_NtReadFile)(h, NULL, NULL, NULL,
144                                             &iosb, buf, count, NULL, NULL);
145                 if (!NT_SUCCESS(status)) {
146                         set_errno_from_nt_status(status);
147                         ERROR_WITH_ERRNO("\"%ls\": Error reading data "
148                                          "(status=0x%08"PRIx32")",
149                                          printable_path(path), (u32)status);
150                         ret = WIMLIB_ERR_READ;
151                         break;
152                 }
153
154                 bytes_read = iosb.Information;
155
156                 bytes_remaining -= bytes_read;
157                 ret = (*cb)(buf, bytes_read, cb_ctx);
158                 if (ret)
159                         break;
160         }
161         (*func_NtClose)(h);
162         return ret;
163 }
164
165 struct win32_encrypted_read_ctx {
166         consume_data_callback_t read_prefix_cb;
167         void *read_prefix_ctx;
168         int wimlib_err_code;
169         u64 bytes_remaining;
170 };
171
172 static DWORD WINAPI
173 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
174 {
175         struct win32_encrypted_read_ctx *ctx = _ctx;
176         int ret;
177         size_t bytes_to_consume = min(len, ctx->bytes_remaining);
178
179         if (bytes_to_consume == 0)
180                 return ERROR_SUCCESS;
181
182         ret = (*ctx->read_prefix_cb)(data, bytes_to_consume, ctx->read_prefix_ctx);
183         if (ret) {
184                 ctx->wimlib_err_code = ret;
185                 /* Shouldn't matter what error code is returned here, as long as
186                  * it isn't ERROR_SUCCESS.  */
187                 return ERROR_READ_FAULT;
188         }
189         ctx->bytes_remaining -= bytes_to_consume;
190         return ERROR_SUCCESS;
191 }
192
193 int
194 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
195                                  u64 size,
196                                  consume_data_callback_t cb, void *cb_ctx)
197 {
198         struct win32_encrypted_read_ctx export_ctx;
199         DWORD err;
200         void *file_ctx;
201         int ret;
202
203         export_ctx.read_prefix_cb = cb;
204         export_ctx.read_prefix_ctx = cb_ctx;
205         export_ctx.wimlib_err_code = 0;
206         export_ctx.bytes_remaining = size;
207
208         err = OpenEncryptedFileRaw(lte->file_on_disk, 0, &file_ctx);
209         if (err != ERROR_SUCCESS) {
210                 set_errno_from_win32_error(err);
211                 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
212                                  "for raw read",
213                                  printable_path(lte->file_on_disk));
214                 return WIMLIB_ERR_OPEN;
215         }
216         err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
217                                    &export_ctx, file_ctx);
218         if (err != ERROR_SUCCESS) {
219                 set_errno_from_win32_error(err);
220                 ERROR_WITH_ERRNO("Failed to read encrypted file \"%ls\"",
221                                  printable_path(lte->file_on_disk));
222                 ret = export_ctx.wimlib_err_code;
223                 if (ret == 0)
224                         ret = WIMLIB_ERR_READ;
225         } else if (export_ctx.bytes_remaining != 0) {
226                 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
227                       "encrypted file \"%ls\"",
228                       size - export_ctx.bytes_remaining, size,
229                       printable_path(lte->file_on_disk));
230                 ret = WIMLIB_ERR_READ;
231         } else {
232                 ret = 0;
233         }
234         CloseEncryptedFileRaw(file_ctx);
235         return ret;
236 }
237
238 /*
239  * Load the short name of a file into a WIM dentry.
240  */
241 static NTSTATUS
242 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
243 {
244         /* It's not any harder to just make the NtQueryInformationFile() system
245          * call ourselves, and it saves a dumb call to FindFirstFile() which of
246          * course has to create its own handle.  */
247         NTSTATUS status;
248         IO_STATUS_BLOCK iosb;
249         u8 buf[128] _aligned_attribute(8);
250         const FILE_NAME_INFORMATION *info;
251
252         status = (*func_NtQueryInformationFile)(h, &iosb, buf, sizeof(buf),
253                                                 FileAlternateNameInformation);
254         info = (const FILE_NAME_INFORMATION *)buf;
255         if (NT_SUCCESS(status) && info->FileNameLength != 0) {
256                 dentry->short_name = utf16le_dupz(info->FileName,
257                                                   info->FileNameLength);
258                 if (!dentry->short_name)
259                         return STATUS_NO_MEMORY;
260                 dentry->short_name_nbytes = info->FileNameLength;
261         }
262         return status;
263 }
264
265 /*
266  * Load the security descriptor of a file into the corresponding inode, and the
267  * WIM image's security descriptor set.
268  */
269 static NTSTATUS
270 winnt_get_security_descriptor(HANDLE h, struct wim_inode *inode,
271                               struct wim_sd_set *sd_set,
272                               struct winnt_scan_stats *stats, int add_flags)
273 {
274         SECURITY_INFORMATION requestedInformation;
275         u8 _buf[4096] _aligned_attribute(8);
276         u8 *buf;
277         ULONG bufsize;
278         ULONG len_needed;
279         NTSTATUS status;
280
281         requestedInformation = DACL_SECURITY_INFORMATION |
282                                SACL_SECURITY_INFORMATION |
283                                OWNER_SECURITY_INFORMATION |
284                                GROUP_SECURITY_INFORMATION;
285         buf = _buf;
286         bufsize = sizeof(_buf);
287
288         /*
289          * We need the file's security descriptor in
290          * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
291          * opened with as many relevant permissions as possible.  At this point,
292          * on Windows there are a number of options for reading a file's
293          * security descriptor:
294          *
295          * GetFileSecurity():  This takes in a path and returns the
296          * SECURITY_DESCRIPTOR_RELATIVE.  Problem: this uses an internal handle,
297          * not ours, and the handle created internally doesn't specify
298          * FILE_FLAG_BACKUP_SEMANTICS.  Therefore there can be access denied
299          * errors on some files and directories, even when running as the
300          * Administrator.
301          *
302          * GetSecurityInfo():  This takes in a handle and returns the security
303          * descriptor split into a bunch of different parts.  This should work,
304          * but it's dumb because we have to put the security descriptor back
305          * together again.
306          *
307          * BackupRead():  This can read the security descriptor, but this is a
308          * difficult-to-use API, probably only works as the Administrator, and
309          * the format of the returned data is not well documented.
310          *
311          * NtQuerySecurityObject():  This is exactly what we need, as it takes
312          * in a handle and returns the security descriptor in
313          * SECURITY_DESCRIPTOR_RELATIVE format.  Only problem is that it's a
314          * ntdll function and therefore not officially part of the Win32 API.
315          * Oh well.
316          */
317         while (!(NT_SUCCESS(status = (*func_NtQuerySecurityObject)(h,
318                                                                    requestedInformation,
319                                                                    (PSECURITY_DESCRIPTOR)buf,
320                                                                    bufsize,
321                                                                    &len_needed))))
322         {
323                 switch (status) {
324                 case STATUS_BUFFER_TOO_SMALL:
325                         wimlib_assert(buf == _buf);
326                         buf = MALLOC(len_needed);
327                         if (!buf)
328                                 return STATUS_NO_MEMORY;
329                         bufsize = len_needed;
330                         break;
331                 case STATUS_PRIVILEGE_NOT_HELD:
332                 case STATUS_ACCESS_DENIED:
333                         if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
334                 default:
335                                 /* Permission denied in STRICT_ACLS mode, or
336                                  * unknown error.  */
337                                 goto out_free_buf;
338                         }
339                         if (requestedInformation & SACL_SECURITY_INFORMATION) {
340                                 /* Try again without the SACL.  */
341                                 stats->num_get_sacl_priv_notheld++;
342                                 requestedInformation &= ~SACL_SECURITY_INFORMATION;
343                                 break;
344                         }
345                         /* Fake success (useful when capturing as
346                          * non-Administrator).  */
347                         stats->num_get_sd_access_denied++;
348                         status = STATUS_SUCCESS;
349                         goto out_free_buf;
350                 }
351         }
352
353         /* Add the security descriptor to the WIM image, and save its ID in
354          * file's inode.  */
355         inode->i_security_id = sd_set_add_sd(sd_set, buf, len_needed);
356         if (unlikely(inode->i_security_id < 0))
357                 status = STATUS_NO_MEMORY;
358 out_free_buf:
359         if (unlikely(buf != _buf))
360                 FREE(buf);
361         return status;
362 }
363
364 static int
365 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
366                                   HANDLE cur_dir,
367                                   wchar_t *full_path,
368                                   size_t full_path_nchars,
369                                   const wchar_t *filename,
370                                   size_t filename_nchars,
371                                   struct add_image_params *params,
372                                   struct winnt_scan_stats *stats,
373                                   u32 vol_flags);
374
375 static int
376 winnt_recurse_directory(HANDLE h,
377                         wchar_t *full_path,
378                         size_t full_path_nchars,
379                         struct wim_dentry *parent,
380                         struct add_image_params *params,
381                         struct winnt_scan_stats *stats,
382                         u32 vol_flags)
383 {
384         void *buf;
385         const size_t bufsize = 8192;
386         IO_STATUS_BLOCK iosb;
387         NTSTATUS status;
388         int ret;
389
390         buf = MALLOC(bufsize);
391         if (!buf)
392                 return WIMLIB_ERR_NOMEM;
393
394         /* Using NtQueryDirectoryFile() we can re-use the same open handle,
395          * which we opened with FILE_FLAG_BACKUP_SEMANTICS.  */
396
397         while (NT_SUCCESS(status = (*func_NtQueryDirectoryFile)(h, NULL, NULL, NULL,
398                                                                 &iosb, buf, bufsize,
399                                                                 FileNamesInformation,
400                                                                 FALSE, NULL, FALSE)))
401         {
402                 const FILE_NAMES_INFORMATION *info = buf;
403                 for (;;) {
404                         if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
405                             !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
406                                                            info->FileName[1] == L'.'))
407                         {
408                                 wchar_t *p;
409                                 wchar_t *filename;
410                                 struct wim_dentry *child;
411
412                                 p = full_path + full_path_nchars;
413                                 /* Only add a backslash if we don't already have
414                                  * one.  This prevents a duplicate backslash
415                                  * from being added when the path to the capture
416                                  * dir had a trailing backslash.  */
417                                 if (*(p - 1) != L'\\')
418                                         *p++ = L'\\';
419                                 filename = p;
420                                 p = wmempcpy(filename, info->FileName,
421                                              info->FileNameLength / 2);
422                                 *p = '\0';
423
424                                 ret = winnt_build_dentry_tree_recursive(
425                                                         &child,
426                                                         h,
427                                                         full_path,
428                                                         p - full_path,
429                                                         filename,
430                                                         info->FileNameLength / 2,
431                                                         params,
432                                                         stats,
433                                                         vol_flags);
434
435                                 full_path[full_path_nchars] = L'\0';
436
437                                 if (ret)
438                                         goto out_free_buf;
439                                 if (child)
440                                         dentry_add_child(parent, child);
441                         }
442                         if (info->NextEntryOffset == 0)
443                                 break;
444                         info = (const FILE_NAMES_INFORMATION *)
445                                         ((const u8 *)info + info->NextEntryOffset);
446                 }
447         }
448
449         if (unlikely(status != STATUS_NO_MORE_FILES)) {
450                 set_errno_from_nt_status(status);
451                 ERROR_WITH_ERRNO("\"%ls\": Can't read directory "
452                                  "(status=0x%08"PRIx32")",
453                                  printable_path(full_path), (u32)status);
454                 ret = WIMLIB_ERR_READ;
455         }
456 out_free_buf:
457         FREE(buf);
458         return ret;
459 }
460
461 /* Reparse point fixup status code  */
462 enum rp_status {
463         /* Reparse point will be captured literally (no fixup)  */
464         RP_NOT_FIXED    = -1,
465
466         /* Reparse point will be captured with fixup  */
467         RP_FIXED        = -2,
468 };
469
470 static bool
471 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
472 {
473         NTSTATUS status;
474         IO_STATUS_BLOCK iosb;
475         FILE_INTERNAL_INFORMATION int_info;
476         FILE_FS_VOLUME_INFORMATION vol_info;
477
478         status = (*func_NtQueryInformationFile)(h, &iosb,
479                                                 &int_info, sizeof(int_info),
480                                                 FileInternalInformation);
481         if (!NT_SUCCESS(status))
482                 return false;
483
484         if (int_info.IndexNumber.QuadPart != ino)
485                 return false;
486
487         status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
488                                                       &vol_info, sizeof(vol_info),
489                                                       FileFsVolumeInformation);
490         if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
491                 return false;
492
493         if (iosb.Information <
494              offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
495              sizeof(vol_info.VolumeSerialNumber))
496                 return false;
497
498         return (vol_info.VolumeSerialNumber == dev);
499 }
500
501 /*
502  * Given an (expected) NT namespace symbolic link or junction target @target of
503  * length @target_nbytes, determine if a prefix of the target points to a file
504  * identified by @capture_root_ino and @capture_root_dev.
505  *
506  * If yes, return a pointer to the portion of the link following this prefix.
507  *
508  * If no, return NULL.
509  *
510  * If the link target does not appear to be a valid NT namespace path, return
511  * @target itself.
512  */
513 static const wchar_t *
514 winnt_get_root_relative_target(const wchar_t *target, size_t target_nbytes,
515                                u64 capture_root_ino, u64 capture_root_dev)
516 {
517         UNICODE_STRING name;
518         OBJECT_ATTRIBUTES attr;
519         IO_STATUS_BLOCK iosb;
520         NTSTATUS status;
521         const wchar_t *target_end;
522         const wchar_t *p;
523
524         target_end = target + (target_nbytes / sizeof(wchar_t));
525
526         /* Empty path??? */
527         if (target_end == target)
528                 return target;
529
530         /* No leading slash???  */
531         if (target[0] != L'\\')
532                 return target;
533
534         /* UNC path???  */
535         if ((target_end - target) >= 2 &&
536             target[0] == L'\\' && target[1] == L'\\')
537                 return target;
538
539         attr.Length = sizeof(attr);
540         attr.RootDirectory = NULL;
541         attr.ObjectName = &name;
542         attr.Attributes = 0;
543         attr.SecurityDescriptor = NULL;
544         attr.SecurityQualityOfService = NULL;
545
546         name.Buffer = (wchar_t *)target;
547         name.Length = 0;
548         p = target;
549         do {
550                 HANDLE h;
551                 const wchar_t *orig_p = p;
552
553                 /* Skip non-backslashes  */
554                 while (p != target_end && *p != L'\\')
555                         p++;
556
557                 /* Skip backslashes  */
558                 while (p != target_end && *p == L'\\')
559                         p++;
560
561                 /* Append path component  */
562                 name.Length += (p - orig_p) * sizeof(wchar_t);
563                 name.MaximumLength = name.Length;
564
565                 /* Try opening the file  */
566                 status = (*func_NtOpenFile) (&h,
567                                              FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
568                                              &attr,
569                                              &iosb,
570                                              FILE_SHARE_VALID_FLAGS,
571                                              FILE_OPEN_FOR_BACKUP_INTENT);
572
573                 if (NT_SUCCESS(status)) {
574                         /* Reset root directory  */
575                         if (attr.RootDirectory)
576                                 (*func_NtClose)(attr.RootDirectory);
577                         attr.RootDirectory = h;
578                         name.Buffer = (wchar_t *)p;
579                         name.Length = 0;
580
581                         if (file_has_ino_and_dev(h, capture_root_ino,
582                                                  capture_root_dev))
583                                 goto out_close_root_dir;
584                 }
585         } while (p != target_end);
586
587         p = NULL;
588
589 out_close_root_dir:
590         if (attr.RootDirectory)
591                 (*func_NtClose)(attr.RootDirectory);
592         return p;
593 }
594
595 static int
596 winnt_rpfix_progress(struct add_image_params *params, const wchar_t *path,
597                      const struct reparse_data *rpdata, int scan_status)
598 {
599         size_t print_name_nchars = rpdata->print_name_nbytes / sizeof(wchar_t);
600         wchar_t print_name0[print_name_nchars + 1];
601
602         wmemcpy(print_name0, rpdata->print_name, print_name_nchars);
603         print_name0[print_name_nchars] = L'\0';
604
605         params->progress.scan.cur_path = printable_path(path);
606         params->progress.scan.symlink_target = print_name0;
607         return do_capture_progress(params, scan_status, NULL);
608 }
609
610 static int
611 winnt_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
612                 u64 capture_root_ino, u64 capture_root_dev,
613                 const wchar_t *path, struct add_image_params *params)
614 {
615         struct reparse_data rpdata;
616         const wchar_t *rel_target;
617         int ret;
618
619         if (parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata)) {
620                 /* Couldn't even understand the reparse data.  Don't try the
621                  * fixup.  */
622                 return RP_NOT_FIXED;
623         }
624
625         /*
626          * Don't do reparse point fixups on relative symbolic links.
627          *
628          * On Windows, a relative symbolic link is supposed to be identifiable
629          * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
630          * SYMBOLIC_LINK_RELATIVE.  We will use this information, although this
631          * may not always do what the user expects, since drive-relative
632          * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
633          * set, in addition to truely relative symbolic links such as "Users" or
634          * "Users\Public".  However, WIMGAPI (as of Windows 8.1) has this same
635          * behavior.
636          *
637          * Otherwise, as far as I can tell, the targets of symbolic links that
638          * are NOT relative, as well as junctions (note: a mountpoint is the
639          * sames thing as a junction), must be NT namespace paths, for example:
640          *
641          *     - \??\e:\Users\Public
642          *     - \DosDevices\e:\Users\Public
643          *     - \Device\HardDiskVolume4\Users\Public
644          *     - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
645          *     - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
646          */
647         if (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
648             (rpdata.rpflags & SYMBOLIC_LINK_RELATIVE))
649                 return RP_NOT_FIXED;
650
651         rel_target = winnt_get_root_relative_target(rpdata.substitute_name,
652                                                     rpdata.substitute_name_nbytes,
653                                                     capture_root_ino,
654                                                     capture_root_dev);
655         if (!rel_target) {
656                 /* Target points outside of the tree being captured.  Don't
657                  * adjust it.  */
658                 ret = winnt_rpfix_progress(params, path, &rpdata,
659                                            WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK);
660                 if (ret)
661                         return ret;
662                 return RP_NOT_FIXED;
663         }
664
665         if (rel_target == rpdata.substitute_name) {
666                 /* Weird target --- keep the reparse point and don't mess with
667                  * it.  */
668                 return RP_NOT_FIXED;
669         }
670
671         /* We have an absolute target pointing within the directory being
672          * captured. @rel_target is the suffix of the link target that is the
673          * part relative to the directory being captured.
674          *
675          * We will cut off the prefix before this part (which is the path to the
676          * directory being captured) and add a dummy prefix.  Since the process
677          * will need to be reversed when applying the image, it shouldn't matter
678          * what exactly the prefix is, as long as it looks like an absolute
679          * path.
680          */
681
682         {
683                 size_t rel_target_nbytes =
684                         rpdata.substitute_name_nbytes - ((const u8 *)rel_target -
685                                                          (const u8 *)rpdata.substitute_name);
686                 size_t rel_target_nchars = rel_target_nbytes / sizeof(wchar_t);
687
688                 wchar_t tmp[rel_target_nchars + 7];
689
690                 wmemcpy(tmp, L"\\??\\X:\\", 7);
691                 wmemcpy(tmp + 7, rel_target, rel_target_nchars);
692
693                 rpdata.substitute_name = tmp;
694                 rpdata.substitute_name_nbytes = rel_target_nbytes + (7 * sizeof(wchar_t));
695                 rpdata.print_name = tmp + 4;
696                 rpdata.print_name_nbytes = rel_target_nbytes + (3 * sizeof(wchar_t));
697
698                 if (make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p))
699                         return RP_NOT_FIXED;
700         }
701         ret = winnt_rpfix_progress(params, path, &rpdata,
702                                    WIMLIB_SCAN_DENTRY_FIXED_SYMLINK);
703         if (ret)
704                 return ret;
705         return RP_FIXED;
706 }
707
708 /*
709  * Loads the reparse point data from a reparse point into memory, optionally
710  * fixing the targets of absolute symbolic links and junction points to be
711  * relative to the root of capture.
712  *
713  * @h:
714  *      Open handle to the reparse point file.
715  * @path:
716  *      Path to the reparse point file.
717  * @params:
718  *      Capture parameters.  add_flags, capture_root_ino, capture_root_dev,
719  *      progfunc, progctx, and progress are used.
720  * @rpbuf:
721  *      Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which the
722  *      reparse point buffer will be loaded.
723  * @rpbuflen_ret:
724  *      On success, the length of the reparse point buffer in bytes is written
725  *      to this location.
726  *
727  * On success, returns a negative `enum rp_status' value.
728  * On failure, returns a positive error code.
729  */
730 static int
731 winnt_get_reparse_data(HANDLE h, const wchar_t *path,
732                        struct add_image_params *params,
733                        u8 *rpbuf, u16 *rpbuflen_ret)
734 {
735         DWORD bytes_returned;
736         u32 reparse_tag;
737         int ret;
738         u16 rpbuflen;
739
740         if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
741                              NULL, 0, rpbuf, REPARSE_POINT_MAX_SIZE,
742                              &bytes_returned, NULL))
743         {
744                 set_errno_from_GetLastError();
745                 return WIMLIB_ERR_READ;
746         }
747
748         if (unlikely(bytes_returned < 8)) {
749                 errno = EINVAL;
750                 return WIMLIB_ERR_INVALID_REPARSE_DATA;
751         }
752
753         rpbuflen = bytes_returned;
754         reparse_tag = le32_to_cpu(*(le32*)rpbuf);
755         ret = RP_NOT_FIXED;
756         if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
757             (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
758              reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
759         {
760                 ret = winnt_try_rpfix(rpbuf, &rpbuflen,
761                                       params->capture_root_ino,
762                                       params->capture_root_dev,
763                                       path, params);
764         }
765         *rpbuflen_ret = rpbuflen;
766         return ret;
767 }
768
769 static DWORD WINAPI
770 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
771                               unsigned long len)
772 {
773         *(u64*)_size_ret += len;
774         return ERROR_SUCCESS;
775 }
776
777 static int
778 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
779 {
780         DWORD err;
781         void *file_ctx;
782         int ret;
783
784         err = OpenEncryptedFileRaw(path, 0, &file_ctx);
785         if (err != ERROR_SUCCESS) {
786                 set_errno_from_win32_error(err);
787                 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
788                                  "for raw read", printable_path(path));
789                 return WIMLIB_ERR_OPEN;
790         }
791         *size_ret = 0;
792         err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
793                                    size_ret, file_ctx);
794         if (err != ERROR_SUCCESS) {
795                 set_errno_from_win32_error(err);
796                 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
797                                  "\"%ls\"", printable_path(path));
798                 ret = WIMLIB_ERR_READ;
799         } else {
800                 ret = 0;
801         }
802         CloseEncryptedFileRaw(file_ctx);
803         return ret;
804 }
805
806 static bool
807 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
808                      const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
809 {
810         const wchar_t *sep, *type, *end;
811
812         /* The stream name should be returned as :NAME:TYPE  */
813         if (raw_stream_name_nchars < 1)
814                 return false;
815         if (raw_stream_name[0] != L':')
816                 return false;
817
818         raw_stream_name++;
819         raw_stream_name_nchars--;
820
821         end = raw_stream_name + raw_stream_name_nchars;
822
823         sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
824         if (!sep)
825                 return false;
826
827         type = sep + 1;
828         if (end - type != 5)
829                 return false;
830
831         if (wmemcmp(type, L"$DATA", 5))
832                 return false;
833
834         *stream_name_ret = raw_stream_name;
835         *stream_name_nchars_ret = sep - raw_stream_name;
836         return true;
837 }
838
839 static wchar_t *
840 build_stream_path(const wchar_t *path, size_t path_nchars,
841                   const wchar_t *stream_name, size_t stream_name_nchars)
842 {
843         size_t stream_path_nchars;
844         wchar_t *stream_path;
845         wchar_t *p;
846
847         stream_path_nchars = path_nchars;
848         if (stream_name_nchars)
849                 stream_path_nchars += 1 + stream_name_nchars;
850
851         stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
852         if (stream_path) {
853                 p = wmempcpy(stream_path, path, path_nchars);
854                 if (stream_name_nchars) {
855                         *p++ = L':';
856                         p = wmempcpy(p, stream_name, stream_name_nchars);
857                 }
858                 *p++ = L'\0';
859         }
860         return stream_path;
861 }
862
863 static int
864 winnt_scan_stream(const wchar_t *path, size_t path_nchars,
865                   const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
866                   u64 stream_size,
867                   struct wim_inode *inode, struct list_head *unhashed_streams)
868 {
869         const wchar_t *stream_name;
870         size_t stream_name_nchars;
871         struct wim_ads_entry *ads_entry;
872         wchar_t *stream_path;
873         struct wim_lookup_table_entry *lte;
874         u32 stream_id;
875
876         /* Given the raw stream name (which is something like
877          * :streamname:$DATA), extract just the stream name part.
878          * Ignore any non-$DATA streams.  */
879         if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
880                                   &stream_name, &stream_name_nchars))
881                 return 0;
882
883         /* If this is a named stream, allocate an ADS entry for it.  */
884         if (stream_name_nchars) {
885                 ads_entry = inode_add_ads_utf16le(inode, stream_name,
886                                                   stream_name_nchars *
887                                                         sizeof(wchar_t));
888                 if (!ads_entry)
889                         return WIMLIB_ERR_NOMEM;
890         } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
891                 /* Ignore unnamed data stream of reparse point  */
892                 return 0;
893         } else {
894                 ads_entry = NULL;
895         }
896
897         /* If the stream is empty, no lookup table entry is needed. */
898         if (stream_size == 0)
899                 return 0;
900
901         /* Build the path to the stream.  For unnamed streams, this is simply
902          * the path to the file.  For named streams, this is the path to the
903          * file, followed by a colon, followed by the stream name.  */
904         stream_path = build_stream_path(path, path_nchars,
905                                         stream_name, stream_name_nchars);
906         if (!stream_path)
907                 return WIMLIB_ERR_NOMEM;
908
909         /* Set up the lookup table entry for the stream.  */
910         lte = new_lookup_table_entry();
911         if (!lte) {
912                 FREE(stream_path);
913                 return WIMLIB_ERR_NOMEM;
914         }
915         lte->file_on_disk = stream_path;
916         lte->resource_location = RESOURCE_IN_WINNT_FILE_ON_DISK;
917         lte->size = stream_size;
918         if ((inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) && !ads_entry) {
919                 /* Special case for encrypted file.  */
920
921                 /* OpenEncryptedFileRaw() expects Win32 name, not NT name.
922                  * Change \??\ into \\?\  */
923                 lte->file_on_disk[1] = L'\\';
924                 wimlib_assert(!wmemcmp(lte->file_on_disk, L"\\\\?\\", 4));
925
926                 u64 encrypted_size;
927                 int ret;
928
929                 ret = win32_get_encrypted_file_size(lte->file_on_disk,
930                                                     &encrypted_size);
931                 if (ret) {
932                         free_lookup_table_entry(lte);
933                         return ret;
934                 }
935                 lte->size = encrypted_size;
936                 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
937         }
938
939         if (ads_entry) {
940                 stream_id = ads_entry->stream_id;
941                 ads_entry->lte = lte;
942         } else {
943                 stream_id = 0;
944                 inode->i_lte = lte;
945         }
946         add_unhashed_stream(lte, inode, stream_id, unhashed_streams);
947         return 0;
948 }
949
950 /*
951  * Load information about the streams of an open file into a WIM inode.
952  *
953  * We use the NtQueryInformationFile() system call instead of FindFirstStream()
954  * and FindNextStream().  This is done for two reasons:
955  *
956  * - FindFirstStream() opens its own handle to the file or directory and
957  *   apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
958  *   causing access denied errors on certain files (even when running as the
959  *   Administrator).
960  * - FindFirstStream() and FindNextStream() is only available on Windows Vista
961  *   and later, whereas the stream support in NtQueryInformationFile() was
962  *   already present in Windows XP.
963  */
964 static int
965 winnt_scan_streams(HANDLE *hFile_p, const wchar_t *path, size_t path_nchars,
966                    struct wim_inode *inode, struct list_head *unhashed_streams,
967                    u64 file_size, u32 vol_flags)
968 {
969         int ret;
970         u8 _buf[1024] _aligned_attribute(8);
971         u8 *buf;
972         size_t bufsize;
973         IO_STATUS_BLOCK iosb;
974         NTSTATUS status;
975         const FILE_STREAM_INFORMATION *info;
976
977         buf = _buf;
978         bufsize = sizeof(_buf);
979
980         if (!(vol_flags & FILE_NAMED_STREAMS))
981                 goto unnamed_only;
982
983         /* Get a buffer containing the stream information.  */
984         while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(*hFile_p,
985                                                                    &iosb,
986                                                                    buf,
987                                                                    bufsize,
988                                                                    FileStreamInformation)))
989         {
990
991                 switch (status) {
992                 case STATUS_BUFFER_OVERFLOW:
993                         {
994                                 u8 *newbuf;
995
996                                 bufsize *= 2;
997                                 if (buf == _buf)
998                                         newbuf = MALLOC(bufsize);
999                                 else
1000                                         newbuf = REALLOC(buf, bufsize);
1001                                 if (!newbuf) {
1002                                         ret = WIMLIB_ERR_NOMEM;
1003                                         goto out_free_buf;
1004                                 }
1005                                 buf = newbuf;
1006                         }
1007                         break;
1008                 case STATUS_NOT_IMPLEMENTED:
1009                 case STATUS_NOT_SUPPORTED:
1010                 case STATUS_INVALID_INFO_CLASS:
1011                         goto unnamed_only;
1012                 default:
1013                         set_errno_from_nt_status(status);
1014                         ERROR_WITH_ERRNO("\"%ls\": Failed to query stream "
1015                                          "information (status=0x%08"PRIx32")",
1016                                          printable_path(path), (u32)status);
1017                         ret = WIMLIB_ERR_READ;
1018                         goto out_free_buf;
1019                 }
1020         }
1021
1022         if (iosb.Information == 0) {
1023                 /* No stream information.  */
1024                 ret = 0;
1025                 goto out_free_buf;
1026         }
1027
1028         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1029                 /* OpenEncryptedFileRaw() seems to fail with
1030                  * ERROR_SHARING_VIOLATION if there are any handles opened to
1031                  * the file.  */
1032                 (*func_NtClose)(*hFile_p);
1033                 *hFile_p = INVALID_HANDLE_VALUE;
1034         }
1035
1036         /* Parse one or more stream information structures.  */
1037         info = (const FILE_STREAM_INFORMATION *)buf;
1038         for (;;) {
1039                 /* Load the stream information.  */
1040                 ret = winnt_scan_stream(path, path_nchars,
1041                                         info->StreamName,
1042                                         info->StreamNameLength / 2,
1043                                         info->StreamSize.QuadPart,
1044                                         inode, unhashed_streams);
1045                 if (ret)
1046                         goto out_free_buf;
1047
1048                 if (info->NextEntryOffset == 0) {
1049                         /* No more stream information.  */
1050                         break;
1051                 }
1052                 /* Advance to next stream information.  */
1053                 info = (const FILE_STREAM_INFORMATION *)
1054                                 ((const u8 *)info + info->NextEntryOffset);
1055         }
1056         ret = 0;
1057         goto out_free_buf;
1058
1059 unnamed_only:
1060         /* The volume does not support named streams.  Only capture the unnamed
1061          * data stream.  */
1062         if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1063                                    FILE_ATTRIBUTE_REPARSE_POINT))
1064         {
1065                 ret = 0;
1066                 goto out_free_buf;
1067         }
1068
1069         ret = winnt_scan_stream(path, path_nchars, L"::$DATA", 7,
1070                                 file_size, inode, unhashed_streams);
1071 out_free_buf:
1072         /* Free buffer if allocated on heap.  */
1073         if (unlikely(buf != _buf))
1074                 FREE(buf);
1075         return ret;
1076 }
1077
1078 static int
1079 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1080                                   HANDLE cur_dir,
1081                                   wchar_t *full_path,
1082                                   size_t full_path_nchars,
1083                                   const wchar_t *filename,
1084                                   size_t filename_nchars,
1085                                   struct add_image_params *params,
1086                                   struct winnt_scan_stats *stats,
1087                                   u32 vol_flags)
1088 {
1089         struct wim_dentry *root = NULL;
1090         struct wim_inode *inode = NULL;
1091         HANDLE h = INVALID_HANDLE_VALUE;
1092         int ret;
1093         NTSTATUS status;
1094         FILE_ALL_INFORMATION file_info;
1095         u8 *rpbuf;
1096         u16 rpbuflen;
1097         u16 not_rpfixed;
1098
1099         ret = try_exclude(full_path, full_path_nchars, params);
1100         if (ret < 0) /* Excluded? */
1101                 goto out_progress;
1102         if (ret > 0) /* Error? */
1103                 goto out;
1104
1105         /* Open the file.  */
1106         status = winnt_openat(cur_dir,
1107                               (cur_dir ? filename : full_path),
1108                               (cur_dir ? filename_nchars : full_path_nchars),
1109                               FILE_READ_DATA |
1110                                         FILE_READ_ATTRIBUTES |
1111                                         READ_CONTROL |
1112                                         ACCESS_SYSTEM_SECURITY |
1113                                         SYNCHRONIZE,
1114                               &h);
1115         if (unlikely(!NT_SUCCESS(status))) {
1116                 if (status == STATUS_DELETE_PENDING) {
1117                         WARNING("\"%ls\": Deletion pending; skipping file",
1118                                 printable_path(full_path));
1119                         ret = 0;
1120                 } else {
1121                         set_errno_from_nt_status(status);
1122                         ERROR_WITH_ERRNO("\"%ls\": Can't open file "
1123                                          "(status=0x%08"PRIx32")",
1124                                          printable_path(full_path), (u32)status);
1125                         if (status == STATUS_FVE_LOCKED_VOLUME)
1126                                 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1127                         else
1128                                 ret = WIMLIB_ERR_OPEN;
1129                 }
1130                 /* XXX: Provide option to exclude files that fail with
1131                  * STATUS_SHARING_VIOLATION?  */
1132                 goto out;
1133         }
1134
1135         /* Get information about the file.  */
1136         {
1137                 IO_STATUS_BLOCK iosb;
1138
1139                 status = (*func_NtQueryInformationFile)(h, &iosb,
1140                                                         &file_info,
1141                                                         sizeof(file_info),
1142                                                         FileAllInformation);
1143
1144                 if (unlikely(!NT_SUCCESS(status) &&
1145                              status != STATUS_BUFFER_OVERFLOW))
1146                 {
1147                         set_errno_from_nt_status(status);
1148                         ERROR_WITH_ERRNO("\"%ls\": Can't get file information "
1149                                          "(status=0x%08"PRIx32")",
1150                                          printable_path(full_path), (u32)status);
1151                         ret = WIMLIB_ERR_STAT;
1152                         goto out;
1153                 }
1154         }
1155
1156         if (unlikely(!cur_dir)) {
1157
1158                 /* Root of tree being captured; get volume information.  */
1159
1160                 FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1161                 FILE_FS_VOLUME_INFORMATION vol_info;
1162                 IO_STATUS_BLOCK iosb;
1163
1164                 /* Get volume flags  */
1165                 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1166                                                               &attr_info,
1167                                                               sizeof(attr_info),
1168                                                               FileFsAttributeInformation);
1169                 if (likely((NT_SUCCESS(status) ||
1170                             (status == STATUS_BUFFER_OVERFLOW)) &&
1171                            (iosb.Information >=
1172                                 offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1173                                          FileSystemAttributes) +
1174                                 sizeof(attr_info.FileSystemAttributes))))
1175                 {
1176                         vol_flags = attr_info.FileSystemAttributes;
1177                 } else {
1178                         set_errno_from_nt_status(status);
1179                         WARNING_WITH_ERRNO("\"%ls\": Can't get volume attributes "
1180                                            "(status=0x%08"PRIx32")",
1181                                            printable_path(full_path),
1182                                            (u32)status);
1183                         vol_flags = 0;
1184                 }
1185
1186                 /* Set inode number of root directory  */
1187                 params->capture_root_ino =
1188                         file_info.InternalInformation.IndexNumber.QuadPart;
1189
1190                 /* Get volume ID.  */
1191                 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1192                                                               &vol_info,
1193                                                               sizeof(vol_info),
1194                                                               FileFsVolumeInformation);
1195                 if (likely((NT_SUCCESS(status) ||
1196                             (status == STATUS_BUFFER_OVERFLOW)) &&
1197                            (iosb.Information >=
1198                                 offsetof(FILE_FS_VOLUME_INFORMATION,
1199                                          VolumeSerialNumber) +
1200                                 sizeof(vol_info.VolumeSerialNumber))))
1201                 {
1202                         params->capture_root_dev = vol_info.VolumeSerialNumber;
1203                 } else {
1204                         set_errno_from_nt_status(status);
1205                         WARNING_WITH_ERRNO("\"%ls\": Can't get volume ID "
1206                                            "(status=0x%08"PRIx32")",
1207                                            printable_path(full_path),
1208                                            (u32)status);
1209                         params->capture_root_dev = 0;
1210                 }
1211         }
1212
1213         /* If this is a reparse point, read the reparse data.  */
1214         if (unlikely(file_info.BasicInformation.FileAttributes &
1215                      FILE_ATTRIBUTE_REPARSE_POINT))
1216         {
1217                 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1218                 ret = winnt_get_reparse_data(h, full_path, params,
1219                                              rpbuf, &rpbuflen);
1220                 switch (ret) {
1221                 case RP_FIXED:
1222                         not_rpfixed = 0;
1223                         break;
1224                 case RP_NOT_FIXED:
1225                         not_rpfixed = 1;
1226                         break;
1227                 default:
1228                         ERROR_WITH_ERRNO("\"%ls\": Can't get reparse data",
1229                                          printable_path(full_path));
1230                         goto out;
1231                 }
1232         }
1233
1234         /* Create a WIM dentry with an associated inode, which may be shared.
1235          *
1236          * However, we need to explicitly check for directories and files with
1237          * only 1 link and refuse to hard link them.  This is because Windows
1238          * has a bug where it can return duplicate File IDs for files and
1239          * directories on the FAT filesystem.
1240          *
1241          * Since we don't follow mount points on Windows, we don't need to query
1242          * the volume ID per-file.  Just once, for the root, is enough.  But we
1243          * can't simply pass 0, because then there could be inode collisions
1244          * among multiple calls to win32_build_dentry_tree() that are scanning
1245          * files on different volumes.  */
1246         ret = inode_table_new_dentry(params->inode_table,
1247                                      filename,
1248                                      file_info.InternalInformation.IndexNumber.QuadPart,
1249                                      params->capture_root_dev,
1250                                      (file_info.StandardInformation.NumberOfLinks <= 1 ||
1251                                         (file_info.BasicInformation.FileAttributes &
1252                                          FILE_ATTRIBUTE_DIRECTORY)),
1253                                      &root);
1254         if (ret)
1255                 goto out;
1256
1257         /* Get the short (DOS) name of the file.  */
1258         status = winnt_get_short_name(h, root);
1259
1260         /* If we can't read the short filename for any reason other than
1261          * out-of-memory, just ignore the error and assume the file has no short
1262          * name.  This shouldn't be an issue, since the short names are
1263          * essentially obsolete anyway.  */
1264         if (unlikely(status == STATUS_NO_MEMORY)) {
1265                 ret = WIMLIB_ERR_NOMEM;
1266                 goto out;
1267         }
1268
1269         inode = root->d_inode;
1270
1271         if (inode->i_nlink > 1) {
1272                 /* Shared inode (hard link); skip reading per-inode information.
1273                  */
1274                 goto out_progress;
1275         }
1276
1277         inode->i_attributes = file_info.BasicInformation.FileAttributes;
1278         inode->i_creation_time = file_info.BasicInformation.CreationTime.QuadPart;
1279         inode->i_last_write_time = file_info.BasicInformation.LastWriteTime.QuadPart;
1280         inode->i_last_access_time = file_info.BasicInformation.LastAccessTime.QuadPart;
1281         inode->i_resolved = 1;
1282
1283         /* Get the file's security descriptor, unless we are capturing in
1284          * NO_ACLS mode or the volume does not support security descriptors.  */
1285         if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1286             && (vol_flags & FILE_PERSISTENT_ACLS))
1287         {
1288                 status = winnt_get_security_descriptor(h, inode,
1289                                                        params->sd_set, stats,
1290                                                        params->add_flags);
1291                 if (!NT_SUCCESS(status)) {
1292                         set_errno_from_nt_status(status);
1293                         ERROR_WITH_ERRNO("\"%ls\": Can't read security "
1294                                          "descriptor (status=0x%08"PRIx32")",
1295                                          printable_path(full_path),
1296                                          (u32)status);
1297                         ret = WIMLIB_ERR_STAT;
1298                         goto out;
1299                 }
1300         }
1301
1302         /* Load information about the unnamed data stream and any named data
1303          * streams.  */
1304         ret = winnt_scan_streams(&h,
1305                                  full_path,
1306                                  full_path_nchars,
1307                                  inode,
1308                                  params->unhashed_streams,
1309                                  file_info.StandardInformation.EndOfFile.QuadPart,
1310                                  vol_flags);
1311         if (ret)
1312                 goto out;
1313
1314         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1315
1316                 /* Reparse point: set the reparse data (already read).  */
1317
1318                 inode->i_not_rpfixed = not_rpfixed;
1319                 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1320                 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1321                                                params->lookup_table);
1322                 if (ret)
1323                         goto out;
1324         } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1325
1326                 /* Directory: recurse to children.  */
1327
1328                 if (unlikely(h == INVALID_HANDLE_VALUE)) {
1329                         /* Re-open handle that was closed to read raw encrypted
1330                          * data.  */
1331                         status = winnt_openat(cur_dir,
1332                                               (cur_dir ?
1333                                                filename : full_path),
1334                                               (cur_dir ?
1335                                                filename_nchars : full_path_nchars),
1336                                               FILE_LIST_DIRECTORY | SYNCHRONIZE,
1337                                               &h);
1338                         if (!NT_SUCCESS(status)) {
1339                                 set_errno_from_nt_status(status);
1340                                 ERROR_WITH_ERRNO("\"%ls\": Can't re-open file "
1341                                                  "(status=0x%08"PRIx32")",
1342                                                  printable_path(full_path),
1343                                                  (u32)status);
1344                                 ret = WIMLIB_ERR_OPEN;
1345                                 goto out;
1346                         }
1347                 }
1348                 ret = winnt_recurse_directory(h,
1349                                               full_path,
1350                                               full_path_nchars,
1351                                               root,
1352                                               params,
1353                                               stats,
1354                                               vol_flags);
1355                 if (ret)
1356                         goto out;
1357         }
1358
1359 out_progress:
1360         params->progress.scan.cur_path = printable_path(full_path);
1361         if (likely(root))
1362                 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1363         else
1364                 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1365 out:
1366         if (likely(h != INVALID_HANDLE_VALUE))
1367                 (*func_NtClose)(h);
1368         if (likely(ret == 0))
1369                 *root_ret = root;
1370         else
1371                 free_dentry_tree(root, params->lookup_table);
1372         return ret;
1373 }
1374
1375 static void
1376 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_stats *stats)
1377 {
1378         if (likely(stats->num_get_sacl_priv_notheld == 0 &&
1379                    stats->num_get_sd_access_denied == 0))
1380                 return;
1381
1382         WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1383         if (stats->num_get_sacl_priv_notheld != 0) {
1384                 WARNING("- Could not capture SACL (System Access Control List)\n"
1385                         "            on %lu files or directories.",
1386                         stats->num_get_sacl_priv_notheld);
1387         }
1388         if (stats->num_get_sd_access_denied != 0) {
1389                 WARNING("- Could not capture security descriptor at all\n"
1390                         "            on %lu files or directories.",
1391                         stats->num_get_sd_access_denied);
1392         }
1393         WARNING("To fully capture all security descriptors, run the program\n"
1394                 "          with Administrator rights.");
1395 }
1396
1397 #define WINDOWS_NT_MAX_PATH 32768
1398
1399 /* Win32 version of capturing a directory tree.  */
1400 int
1401 win32_build_dentry_tree(struct wim_dentry **root_ret,
1402                         const wchar_t *root_disk_path,
1403                         struct add_image_params *params)
1404 {
1405         wchar_t *path;
1406         int ret;
1407         UNICODE_STRING ntpath;
1408         struct winnt_scan_stats stats;
1409         size_t ntpath_nchars;
1410
1411         /* WARNING: There is no check for overflow later when this buffer is
1412          * being used!  But it's as long as the maximum path length understood
1413          * by Windows NT (which is NOT the same as MAX_PATH).  */
1414         path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1415         if (!path)
1416                 return WIMLIB_ERR_NOMEM;
1417
1418         ret = win32_path_to_nt_path(root_disk_path, &ntpath);
1419         if (ret)
1420                 goto out_free_path;
1421
1422         if (ntpath.Length < 4 * sizeof(wchar_t) ||
1423             ntpath.Length > WINDOWS_NT_MAX_PATH * sizeof(wchar_t) ||
1424             wmemcmp(ntpath.Buffer, L"\\??\\", 4))
1425         {
1426                 ERROR("\"%ls\": unrecognized path format", root_disk_path);
1427                 ret = WIMLIB_ERR_INVALID_PARAM;
1428         } else {
1429                 ntpath_nchars = ntpath.Length / sizeof(wchar_t);
1430                 wmemcpy(path, ntpath.Buffer, ntpath_nchars);
1431                 path[ntpath_nchars] = L'\0';
1432
1433                 params->capture_root_nchars = ntpath_nchars;
1434                 if (path[ntpath_nchars - 1] == L'\\')
1435                         params->capture_root_nchars--;
1436                 ret = 0;
1437         }
1438         HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
1439         if (ret)
1440                 goto out_free_path;
1441
1442         memset(&stats, 0, sizeof(stats));
1443
1444         ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
1445                                                 path, ntpath_nchars,
1446                                                 L"", 0, params, &stats, 0);
1447 out_free_path:
1448         FREE(path);
1449         if (ret == 0)
1450                 winnt_do_scan_warnings(root_disk_path, &stats);
1451         return ret;
1452 }
1453
1454 #endif /* __WIN32__ */