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