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