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