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