]> wimlib.net Git - wimlib/blob - src/win32_capture.c
Add support for a data recovery mode
[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-2018 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/dentry.h"
35 #include "wimlib/encoding.h"
36 #include "wimlib/endianness.h"
37 #include "wimlib/error.h"
38 #include "wimlib/object_id.h"
39 #include "wimlib/paths.h"
40 #include "wimlib/reparse.h"
41 #include "wimlib/scan.h"
42 #include "wimlib/win32_vss.h"
43 #include "wimlib/wof.h"
44 #include "wimlib/xattr.h"
45
46 struct winnt_scan_ctx {
47         struct scan_params *params;
48         bool is_ntfs;
49         u32 vol_flags;
50         unsigned long num_get_sd_access_denied;
51         unsigned long num_get_sacl_priv_notheld;
52
53         /* True if WOF is definitely not attached to the volume being scanned;
54          * false if it may be  */
55         bool wof_not_attached;
56
57         /* A reference to the VSS snapshot being used, or NULL if none  */
58         struct vss_snapshot *snapshot;
59 };
60
61 static inline const wchar_t *
62 printable_path(const struct winnt_scan_ctx *ctx)
63 {
64         /* Skip over \\?\ or \??\  */
65         return ctx->params->cur_path + 4;
66 }
67
68 /* Description of where data is located on a Windows filesystem  */
69 struct windows_file {
70
71         /* Is the data the raw encrypted data of an EFS-encrypted file?  */
72         u64 is_encrypted : 1;
73
74         /* Is this file "open by file ID" rather than the regular "open by
75          * path"?  "Open by file ID" uses resources more efficiently.  */
76         u64 is_file_id : 1;
77
78         /* The file's LCN (logical cluster number) for sorting, or 0 if unknown.
79          */
80         u64 sort_key : 62;
81
82         /* Length of the path in bytes, excluding the null terminator if
83          * present.  */
84         size_t path_nbytes;
85
86         /* A reference to the VSS snapshot containing the file, or NULL if none.
87          */
88         struct vss_snapshot *snapshot;
89
90         /* The path to the file.  If 'is_encrypted=0' this is an NT namespace
91          * path; if 'is_encrypted=1' this is a Win32 namespace path.  If
92          * 'is_file_id=0', then the path is null-terminated.  If 'is_file_id=1'
93          * (only allowed with 'is_encrypted=0') the path ends with a binary file
94          * ID and may not be null-terminated.  */
95         wchar_t path[0];
96 };
97
98 /* Allocate a structure to describe the location of a data stream by path.  */
99 static struct windows_file *
100 alloc_windows_file(const wchar_t *path, size_t path_nchars,
101                    const wchar_t *stream_name, size_t stream_name_nchars,
102                    struct vss_snapshot *snapshot, bool is_encrypted)
103 {
104         size_t full_path_nbytes;
105         struct windows_file *file;
106         wchar_t *p;
107
108         full_path_nbytes = path_nchars * sizeof(wchar_t);
109         if (stream_name_nchars)
110                 full_path_nbytes += (1 + stream_name_nchars) * sizeof(wchar_t);
111
112         file = MALLOC(sizeof(struct windows_file) + full_path_nbytes +
113                       sizeof(wchar_t));
114         if (!file)
115                 return NULL;
116
117         file->is_encrypted = is_encrypted;
118         file->is_file_id = 0;
119         file->sort_key = 0;
120         file->path_nbytes = full_path_nbytes;
121         file->snapshot = vss_get_snapshot(snapshot);
122         p = wmempcpy(file->path, path, path_nchars);
123         if (stream_name_nchars) {
124                 /* Named data stream  */
125                 *p++ = L':';
126                 p = wmempcpy(p, stream_name, stream_name_nchars);
127         }
128         *p = L'\0';
129         return file;
130 }
131
132 /* Allocate a structure to describe the location of a file by ID.  */
133 static struct windows_file *
134 alloc_windows_file_for_file_id(u64 file_id, const wchar_t *root_path,
135                                size_t root_path_nchars,
136                                struct vss_snapshot *snapshot)
137 {
138         size_t full_path_nbytes;
139         struct windows_file *file;
140         wchar_t *p;
141
142         full_path_nbytes = (root_path_nchars * sizeof(wchar_t)) +
143                            sizeof(file_id);
144         file = MALLOC(sizeof(struct windows_file) + full_path_nbytes +
145                       sizeof(wchar_t));
146         if (!file)
147                 return NULL;
148
149         file->is_encrypted = 0;
150         file->is_file_id = 1;
151         file->sort_key = 0;
152         file->path_nbytes = full_path_nbytes;
153         file->snapshot = vss_get_snapshot(snapshot);
154         p = wmempcpy(file->path, root_path, root_path_nchars);
155         p = mempcpy(p, &file_id, sizeof(file_id));
156         *p = L'\0';
157         return file;
158 }
159
160 /* Add a stream, located on a Windows filesystem, to the specified WIM inode. */
161 static int
162 add_stream(struct wim_inode *inode, struct windows_file *windows_file,
163            u64 stream_size, int stream_type, const utf16lechar *stream_name,
164            struct list_head *unhashed_blobs)
165 {
166         struct blob_descriptor *blob = NULL;
167         struct wim_inode_stream *strm;
168         int ret;
169
170         if (!windows_file)
171                 goto err_nomem;
172
173         /* If the stream is nonempty, create a blob descriptor for it.  */
174         if (stream_size) {
175                 blob = new_blob_descriptor();
176                 if (!blob)
177                         goto err_nomem;
178                 blob->windows_file = windows_file;
179                 blob->blob_location = BLOB_IN_WINDOWS_FILE;
180                 blob->file_inode = inode;
181                 blob->size = stream_size;
182                 windows_file = NULL;
183         }
184
185         strm = inode_add_stream(inode, stream_type, stream_name, blob);
186         if (!strm)
187                 goto err_nomem;
188
189         prepare_unhashed_blob(blob, inode, strm->stream_id, unhashed_blobs);
190         ret = 0;
191 out:
192         if (windows_file)
193                 free_windows_file(windows_file);
194         return ret;
195
196 err_nomem:
197         free_blob_descriptor(blob);
198         ret = WIMLIB_ERR_NOMEM;
199         goto out;
200 }
201
202 struct windows_file *
203 clone_windows_file(const struct windows_file *file)
204 {
205         struct windows_file *new;
206
207         new = memdup(file, sizeof(*file) + file->path_nbytes + sizeof(wchar_t));
208         if (new)
209                 vss_get_snapshot(new->snapshot);
210         return new;
211 }
212
213 void
214 free_windows_file(struct windows_file *file)
215 {
216         vss_put_snapshot(file->snapshot);
217         FREE(file);
218 }
219
220 int
221 cmp_windows_files(const struct windows_file *file1,
222                   const struct windows_file *file2)
223 {
224         /* Compare by starting LCN (logical cluster number)  */
225         int v = cmp_u64(file1->sort_key, file2->sort_key);
226         if (v)
227                 return v;
228
229         /* Fall back to comparing files by path (arbitrary heuristic).  */
230         v = memcmp(file1->path, file2->path,
231                    min(file1->path_nbytes, file2->path_nbytes));
232         if (v)
233                 return v;
234
235         return cmp_u32(file1->path_nbytes, file2->path_nbytes);
236 }
237
238 const wchar_t *
239 get_windows_file_path(const struct windows_file *file)
240 {
241         return file->path;
242 }
243
244 /*
245  * Open the file named by the NT namespace path @path of length @path_nchars
246  * characters.  If @cur_dir is not NULL then the path is given relative to
247  * @cur_dir; otherwise the path is absolute.  @perms is the access mask of
248  * permissions to request on the handle.  SYNCHRONIZE permision is always added.
249  */
250 static NTSTATUS
251 winnt_openat(HANDLE cur_dir, const wchar_t *path, size_t path_nchars,
252              ACCESS_MASK perms, HANDLE *h_ret)
253 {
254         UNICODE_STRING name = {
255                 .Length = path_nchars * sizeof(wchar_t),
256                 .MaximumLength = path_nchars * sizeof(wchar_t),
257                 .Buffer = (wchar_t *)path,
258         };
259         OBJECT_ATTRIBUTES attr = {
260                 .Length = sizeof(attr),
261                 .RootDirectory = cur_dir,
262                 .ObjectName = &name,
263         };
264         IO_STATUS_BLOCK iosb;
265         NTSTATUS status;
266         ULONG options = FILE_OPEN_REPARSE_POINT | FILE_OPEN_FOR_BACKUP_INTENT;
267
268         perms |= SYNCHRONIZE;
269         if (perms & (FILE_READ_DATA | FILE_LIST_DIRECTORY)) {
270                 options |= FILE_SYNCHRONOUS_IO_NONALERT;
271                 options |= FILE_SEQUENTIAL_ONLY;
272         }
273 retry:
274         status = NtOpenFile(h_ret, perms, &attr, &iosb,
275                             FILE_SHARE_VALID_FLAGS, options);
276         if (!NT_SUCCESS(status)) {
277                 /* Try requesting fewer permissions  */
278                 if (status == STATUS_ACCESS_DENIED ||
279                     status == STATUS_PRIVILEGE_NOT_HELD) {
280                         if (perms & ACCESS_SYSTEM_SECURITY) {
281                                 perms &= ~ACCESS_SYSTEM_SECURITY;
282                                 goto retry;
283                         }
284                         if (perms & READ_CONTROL) {
285                                 perms &= ~READ_CONTROL;
286                                 goto retry;
287                         }
288                 }
289         }
290         return status;
291 }
292
293 static NTSTATUS
294 winnt_open(const wchar_t *path, size_t path_nchars, ACCESS_MASK perms,
295            HANDLE *h_ret)
296 {
297         return winnt_openat(NULL, path, path_nchars, perms, h_ret);
298 }
299
300 static const wchar_t *
301 windows_file_to_string(const struct windows_file *file, u8 *buf, size_t bufsize)
302 {
303         if (file->is_file_id) {
304                 u64 file_id;
305                 memcpy(&file_id,
306                        (u8 *)file->path + file->path_nbytes - sizeof(file_id),
307                        sizeof(file_id));
308                 swprintf((wchar_t *)buf, L"NTFS inode 0x%016"PRIx64, file_id);
309         } else if (file->path_nbytes + 3 * sizeof(wchar_t) <= bufsize) {
310                 swprintf((wchar_t *)buf, L"\"%ls\"", file->path);
311         } else {
312                 return L"(name too long)";
313         }
314         return (wchar_t *)buf;
315 }
316
317 static int
318 read_winnt_stream_prefix(const struct windows_file *file,
319                          u64 size, const struct consume_chunk_callback *cb)
320 {
321         IO_STATUS_BLOCK iosb;
322         UNICODE_STRING name = {
323                 .Buffer = (wchar_t *)file->path,
324                 .Length = file->path_nbytes,
325                 .MaximumLength = file->path_nbytes,
326         };
327         OBJECT_ATTRIBUTES attr = {
328                 .Length = sizeof(attr),
329                 .ObjectName = &name,
330         };
331         HANDLE h;
332         NTSTATUS status;
333         u8 buf[BUFFER_SIZE] _aligned_attribute(8);
334         u64 bytes_remaining;
335         int ret;
336
337         status = NtOpenFile(&h, FILE_READ_DATA | SYNCHRONIZE,
338                             &attr, &iosb,
339                             FILE_SHARE_VALID_FLAGS,
340                             FILE_OPEN_REPARSE_POINT |
341                                 FILE_OPEN_FOR_BACKUP_INTENT |
342                                 FILE_SYNCHRONOUS_IO_NONALERT |
343                                 FILE_SEQUENTIAL_ONLY |
344                                 (file->is_file_id ? FILE_OPEN_BY_FILE_ID : 0));
345         if (unlikely(!NT_SUCCESS(status))) {
346                 if (status == STATUS_SHARING_VIOLATION) {
347                         ERROR("Can't open %ls for reading:\n"
348                               "        File is in use by another process! "
349                               "Consider using snapshot (VSS) mode.",
350                               windows_file_to_string(file, buf, sizeof(buf)));
351                 } else {
352                         winnt_error(status, L"Can't open %ls for reading",
353                                     windows_file_to_string(file, buf, sizeof(buf)));
354                 }
355                 return WIMLIB_ERR_OPEN;
356         }
357
358         ret = 0;
359         bytes_remaining = size;
360         while (bytes_remaining) {
361                 IO_STATUS_BLOCK iosb;
362                 ULONG count;
363                 ULONG bytes_read;
364                 const unsigned max_tries = 5;
365                 unsigned tries_remaining = max_tries;
366
367                 count = min(sizeof(buf), bytes_remaining);
368
369         retry_read:
370                 status = NtReadFile(h, NULL, NULL, NULL,
371                                     &iosb, buf, count, NULL, NULL);
372                 if (unlikely(!NT_SUCCESS(status))) {
373                         if (status == STATUS_END_OF_FILE) {
374                                 ERROR("%ls: File was concurrently truncated",
375                                       windows_file_to_string(file, buf, sizeof(buf)));
376                                 ret = WIMLIB_ERR_CONCURRENT_MODIFICATION_DETECTED;
377                         } else {
378                                 winnt_warning(status, L"Error reading data from %ls",
379                                               windows_file_to_string(file, buf, sizeof(buf)));
380
381                                 /* Currently these retries are purely a guess;
382                                  * there is no reproducible problem that they solve.  */
383                                 if (--tries_remaining) {
384                                         int delay = 100;
385                                         if (status == STATUS_INSUFFICIENT_RESOURCES ||
386                                             status == STATUS_NO_MEMORY) {
387                                                 delay *= 25;
388                                         }
389                                         WARNING("Retrying after %dms...", delay);
390                                         Sleep(delay);
391                                         goto retry_read;
392                                 }
393                                 ERROR("Too many retries; returning failure");
394                                 ret = WIMLIB_ERR_READ;
395                         }
396                         break;
397                 } else if (unlikely(tries_remaining != max_tries)) {
398                         WARNING("A read request had to be retried multiple times "
399                                 "before it succeeded!");
400                 }
401
402                 bytes_read = iosb.Information;
403
404                 bytes_remaining -= bytes_read;
405                 ret = consume_chunk(cb, buf, bytes_read);
406                 if (ret)
407                         break;
408         }
409         NtClose(h);
410         return ret;
411 }
412
413 struct win32_encrypted_read_ctx {
414         const struct consume_chunk_callback *cb;
415         int wimlib_err_code;
416         u64 bytes_remaining;
417 };
418
419 static DWORD WINAPI
420 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
421 {
422         struct win32_encrypted_read_ctx *ctx = _ctx;
423         int ret;
424         size_t bytes_to_consume = min(len, ctx->bytes_remaining);
425
426         if (bytes_to_consume == 0)
427                 return ERROR_SUCCESS;
428
429         ret = consume_chunk(ctx->cb, data, bytes_to_consume);
430         if (ret) {
431                 ctx->wimlib_err_code = ret;
432                 /* It doesn't matter what error code is returned here, as long
433                  * as it isn't ERROR_SUCCESS.  */
434                 return ERROR_READ_FAULT;
435         }
436         ctx->bytes_remaining -= bytes_to_consume;
437         return ERROR_SUCCESS;
438 }
439
440 static int
441 read_win32_encrypted_file_prefix(const wchar_t *path, bool is_dir, u64 size,
442                                  const struct consume_chunk_callback *cb)
443 {
444         struct win32_encrypted_read_ctx export_ctx;
445         DWORD err;
446         void *file_ctx;
447         int ret;
448         DWORD flags = 0;
449
450         if (is_dir)
451                 flags |= CREATE_FOR_DIR;
452
453         export_ctx.cb = cb;
454         export_ctx.wimlib_err_code = 0;
455         export_ctx.bytes_remaining = size;
456
457         err = OpenEncryptedFileRaw(path, flags, &file_ctx);
458         if (err != ERROR_SUCCESS) {
459                 win32_error(err,
460                             L"Failed to open encrypted file \"%ls\" for raw read",
461                             path);
462                 return WIMLIB_ERR_OPEN;
463         }
464         err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
465                                    &export_ctx, file_ctx);
466         if (err != ERROR_SUCCESS) {
467                 ret = export_ctx.wimlib_err_code;
468                 if (ret == 0) {
469                         win32_error(err,
470                                     L"Failed to read encrypted file \"%ls\"",
471                                     path);
472                         ret = WIMLIB_ERR_READ;
473                 }
474         } else if (export_ctx.bytes_remaining != 0) {
475                 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
476                       "encrypted file \"%ls\"",
477                       size - export_ctx.bytes_remaining, size,
478                       path);
479                 ret = WIMLIB_ERR_READ;
480         } else {
481                 ret = 0;
482         }
483         CloseEncryptedFileRaw(file_ctx);
484         return ret;
485 }
486
487 /* Read the first @size bytes from the file, or named data stream of a file,
488  * described by @blob.  */
489 int
490 read_windows_file_prefix(const struct blob_descriptor *blob, u64 size,
491                          const struct consume_chunk_callback *cb,
492                          bool recover_data)
493 {
494         const struct windows_file *file = blob->windows_file;
495
496         if (unlikely(file->is_encrypted)) {
497                 bool is_dir = (blob->file_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY);
498                 return read_win32_encrypted_file_prefix(file->path, is_dir, size, cb);
499         }
500
501         return read_winnt_stream_prefix(file, size, cb);
502 }
503
504 /*
505  * Load the short name of a file into a WIM dentry.
506  */
507 static noinline_for_stack NTSTATUS
508 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
509 {
510         /* It's not any harder to just make the NtQueryInformationFile() system
511          * call ourselves, and it saves a dumb call to FindFirstFile() which of
512          * course has to create its own handle.  */
513         NTSTATUS status;
514         IO_STATUS_BLOCK iosb;
515         u8 buf[128] _aligned_attribute(8);
516         const FILE_NAME_INFORMATION *info;
517
518         status = NtQueryInformationFile(h, &iosb, buf, sizeof(buf),
519                                         FileAlternateNameInformation);
520         info = (const FILE_NAME_INFORMATION *)buf;
521         if (NT_SUCCESS(status) && info->FileNameLength != 0) {
522                 dentry->d_short_name = utf16le_dupz(info->FileName,
523                                                     info->FileNameLength);
524                 if (!dentry->d_short_name)
525                         return STATUS_NO_MEMORY;
526                 dentry->d_short_name_nbytes = info->FileNameLength;
527         }
528         return status;
529 }
530
531 /*
532  * Load the security descriptor of a file into the corresponding inode and the
533  * WIM image's security descriptor set.
534  */
535 static noinline_for_stack int
536 winnt_load_security_descriptor(HANDLE h, struct wim_inode *inode,
537                                struct winnt_scan_ctx *ctx)
538 {
539         SECURITY_INFORMATION requestedInformation;
540         u8 _buf[4096] _aligned_attribute(8);
541         u8 *buf;
542         ULONG bufsize;
543         ULONG len_needed;
544         NTSTATUS status;
545
546         /*
547          * LABEL_SECURITY_INFORMATION is needed on Windows Vista and 7 because
548          * Microsoft decided to add mandatory integrity labels to the SACL but
549          * not have them returned by SACL_SECURITY_INFORMATION.
550          *
551          * BACKUP_SECURITY_INFORMATION is needed on Windows 8 because Microsoft
552          * decided to add even more stuff to the SACL and still not have it
553          * returned by SACL_SECURITY_INFORMATION; but they did remember that
554          * backup applications exist and simply want to read the stupid thing
555          * once and for all, so they added a flag to read the entire security
556          * descriptor.
557          *
558          * Older versions of Windows tolerate these new flags being passed in.
559          */
560         requestedInformation = OWNER_SECURITY_INFORMATION |
561                                GROUP_SECURITY_INFORMATION |
562                                DACL_SECURITY_INFORMATION |
563                                SACL_SECURITY_INFORMATION |
564                                LABEL_SECURITY_INFORMATION |
565                                BACKUP_SECURITY_INFORMATION;
566
567         buf = _buf;
568         bufsize = sizeof(_buf);
569
570         /*
571          * We need the file's security descriptor in
572          * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
573          * opened with as many relevant permissions as possible.  At this point,
574          * on Windows there are a number of options for reading a file's
575          * security descriptor:
576          *
577          * GetFileSecurity():  This takes in a path and returns the
578          * SECURITY_DESCRIPTOR_RELATIVE.  Problem: this uses an internal handle,
579          * not ours, and the handle created internally doesn't specify
580          * FILE_FLAG_BACKUP_SEMANTICS.  Therefore there can be access denied
581          * errors on some files and directories, even when running as the
582          * Administrator.
583          *
584          * GetSecurityInfo():  This takes in a handle and returns the security
585          * descriptor split into a bunch of different parts.  This should work,
586          * but it's dumb because we have to put the security descriptor back
587          * together again.
588          *
589          * BackupRead():  This can read the security descriptor, but this is a
590          * difficult-to-use API, probably only works as the Administrator, and
591          * the format of the returned data is not well documented.
592          *
593          * NtQuerySecurityObject():  This is exactly what we need, as it takes
594          * in a handle and returns the security descriptor in
595          * SECURITY_DESCRIPTOR_RELATIVE format.  Only problem is that it's a
596          * ntdll function and therefore not officially part of the Win32 API.
597          * Oh well.
598          */
599         while (!NT_SUCCESS(status = NtQuerySecurityObject(h,
600                                                           requestedInformation,
601                                                           (PSECURITY_DESCRIPTOR)buf,
602                                                           bufsize,
603                                                           &len_needed)))
604         {
605                 switch (status) {
606                 case STATUS_BUFFER_TOO_SMALL:
607                         wimlib_assert(buf == _buf);
608                         buf = MALLOC(len_needed);
609                         if (!buf) {
610                                 status = STATUS_NO_MEMORY;
611                                 goto out;
612                         }
613                         bufsize = len_needed;
614                         break;
615                 case STATUS_PRIVILEGE_NOT_HELD:
616                 case STATUS_ACCESS_DENIED:
617                         if (ctx->params->add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
618                 default:
619                                 /* Permission denied in STRICT_ACLS mode, or
620                                  * unknown error.  */
621                                 goto out;
622                         }
623                         if (requestedInformation & SACL_SECURITY_INFORMATION) {
624                                 /* Try again without the SACL.  */
625                                 ctx->num_get_sacl_priv_notheld++;
626                                 requestedInformation &= ~(SACL_SECURITY_INFORMATION |
627                                                           LABEL_SECURITY_INFORMATION |
628                                                           BACKUP_SECURITY_INFORMATION);
629                                 break;
630                         }
631                         /* Fake success (useful when capturing as
632                          * non-Administrator).  */
633                         ctx->num_get_sd_access_denied++;
634                         status = STATUS_SUCCESS;
635                         goto out;
636                 }
637         }
638
639         /* We can get a length of 0 with Samba.  Assume that means "no security
640          * descriptor".  */
641         if (len_needed == 0)
642                 goto out;
643
644         /* Add the security descriptor to the WIM image, and save its ID in
645          * the file's inode.  */
646         inode->i_security_id = sd_set_add_sd(ctx->params->sd_set, buf, len_needed);
647         if (unlikely(inode->i_security_id < 0))
648                 status = STATUS_NO_MEMORY;
649 out:
650         if (unlikely(buf != _buf))
651                 FREE(buf);
652         if (!NT_SUCCESS(status)) {
653                 winnt_error(status, L"\"%ls\": Can't read security descriptor",
654                             printable_path(ctx));
655                 return WIMLIB_ERR_STAT;
656         }
657         return 0;
658 }
659
660 /* Load a file's object ID into the corresponding WIM inode.  */
661 static noinline_for_stack int
662 winnt_load_object_id(HANDLE h, struct wim_inode *inode,
663                      struct winnt_scan_ctx *ctx)
664 {
665         FILE_OBJECTID_BUFFER buffer;
666         NTSTATUS status;
667         u32 len;
668
669         if (!(ctx->vol_flags & FILE_SUPPORTS_OBJECT_IDS))
670                 return 0;
671
672         status = winnt_fsctl(h, FSCTL_GET_OBJECT_ID, NULL, 0,
673                              &buffer, sizeof(buffer), &len);
674
675         if (status == STATUS_OBJECTID_NOT_FOUND) /* No object ID  */
676                 return 0;
677
678         if (status == STATUS_INVALID_DEVICE_REQUEST ||
679             status == STATUS_NOT_SUPPORTED /* Samba volume, WinXP */) {
680                 /* The filesystem claimed to support object IDs, but we can't
681                  * actually read them.  This happens with Samba.  */
682                 ctx->vol_flags &= ~FILE_SUPPORTS_OBJECT_IDS;
683                 return 0;
684         }
685
686         if (!NT_SUCCESS(status)) {
687                 winnt_error(status, L"\"%ls\": Can't read object ID",
688                             printable_path(ctx));
689                 return WIMLIB_ERR_STAT;
690         }
691
692         if (len == 0) /* No object ID (for directories)  */
693                 return 0;
694
695         if (!inode_set_object_id(inode, &buffer, len))
696                 return WIMLIB_ERR_NOMEM;
697
698         return 0;
699 }
700
701 /* Load a file's extended attributes into the corresponding WIM inode.  */
702 static noinline_for_stack int
703 winnt_load_xattrs(HANDLE h, struct wim_inode *inode,
704                   struct winnt_scan_ctx *ctx, u32 ea_size)
705 {
706         IO_STATUS_BLOCK iosb;
707         NTSTATUS status;
708         u8 _buf[1024] _aligned_attribute(4);
709         u8 *buf = _buf;
710         const FILE_FULL_EA_INFORMATION *ea;
711         struct wim_xattr_entry *entry;
712         int ret;
713
714
715         /*
716          * EaSize from FILE_EA_INFORMATION is apparently supposed to give the
717          * size of the buffer required for NtQueryEaFile(), but it doesn't
718          * actually work correctly; it can be off by about 4 bytes per xattr.
719          *
720          * So just start out by doubling the advertised size, and also handle
721          * STATUS_BUFFER_OVERFLOW just in case.
722          */
723 retry:
724         if (unlikely(ea_size * 2 < ea_size))
725                 ea_size = UINT32_MAX;
726         else
727                 ea_size *= 2;
728         if (unlikely(ea_size > sizeof(_buf))) {
729                 buf = MALLOC(ea_size);
730                 if (!buf) {
731                         if (ea_size >= (1 << 20)) {
732                                 WARNING("\"%ls\": EaSize was extremely large (%u)",
733                                         printable_path(ctx), ea_size);
734                         }
735                         return WIMLIB_ERR_NOMEM;
736                 }
737         }
738
739         status = NtQueryEaFile(h, &iosb, buf, ea_size,
740                                FALSE, NULL, 0, NULL, TRUE);
741
742         if (unlikely(!NT_SUCCESS(status))) {
743                 if (status == STATUS_BUFFER_OVERFLOW) {
744                         if (buf != _buf) {
745                                 FREE(buf);
746                                 buf = NULL;
747                         }
748                         goto retry;
749                 }
750                 if (status == STATUS_NO_EAS_ON_FILE) {
751                         /*
752                          * FILE_EA_INFORMATION.EaSize was nonzero so this
753                          * shouldn't happen, but just in case...
754                          */
755                         ret = 0;
756                         goto out;
757                 }
758                 winnt_error(status, L"\"%ls\": Can't read extended attributes",
759                             printable_path(ctx));
760                 ret = WIMLIB_ERR_STAT;
761                 goto out;
762         }
763
764         ea = (const FILE_FULL_EA_INFORMATION *)buf;
765         entry = (struct wim_xattr_entry *)buf;
766         for (;;) {
767                 /*
768                  * wim_xattr_entry is not larger than FILE_FULL_EA_INFORMATION,
769                  * so we can reuse the same buffer by overwriting the
770                  * FILE_FULL_EA_INFORMATION with the wim_xattr_entry in-place.
771                  */
772                 FILE_FULL_EA_INFORMATION _ea;
773
774                 STATIC_ASSERT(offsetof(struct wim_xattr_entry, name) <=
775                               offsetof(FILE_FULL_EA_INFORMATION, EaName));
776                 wimlib_assert((u8 *)entry <= (const u8 *)ea);
777
778                 memcpy(&_ea, ea, sizeof(_ea));
779
780                 entry->value_len = cpu_to_le16(_ea.EaValueLength);
781                 entry->name_len = _ea.EaNameLength;
782                 entry->flags = _ea.Flags;
783                 memmove(entry->name, ea->EaName, _ea.EaNameLength);
784                 entry->name[_ea.EaNameLength] = '\0';
785                 memmove(&entry->name[_ea.EaNameLength + 1],
786                         &ea->EaName[_ea.EaNameLength + 1], _ea.EaValueLength);
787                 entry = (struct wim_xattr_entry *)
788                          &entry->name[_ea.EaNameLength + 1 + _ea.EaValueLength];
789                 if (_ea.NextEntryOffset == 0)
790                         break;
791                 ea = (const FILE_FULL_EA_INFORMATION *)
792                         ((const u8 *)ea + _ea.NextEntryOffset);
793         }
794         wimlib_assert((u8 *)entry - buf <= ea_size);
795
796         ret = WIMLIB_ERR_NOMEM;
797         if (!inode_set_xattrs(inode, buf, (u8 *)entry - buf))
798                 goto out;
799         ret = 0;
800 out:
801         if (unlikely(buf != _buf))
802                 FREE(buf);
803         return ret;
804 }
805
806 static int
807 winnt_build_dentry_tree(struct wim_dentry **root_ret,
808                         HANDLE cur_dir,
809                         const wchar_t *relative_path,
810                         size_t relative_path_nchars,
811                         const wchar_t *filename,
812                         struct winnt_scan_ctx *ctx,
813                         bool recursive);
814
815 static int
816 winnt_recurse_directory(HANDLE h,
817                         struct wim_dentry *parent,
818                         struct winnt_scan_ctx *ctx)
819 {
820         void *buf;
821         const size_t bufsize = 8192;
822         IO_STATUS_BLOCK iosb;
823         NTSTATUS status;
824         int ret;
825
826         buf = MALLOC(bufsize);
827         if (!buf)
828                 return WIMLIB_ERR_NOMEM;
829
830         /* Using NtQueryDirectoryFile() we can re-use the same open handle,
831          * which we opened with FILE_FLAG_BACKUP_SEMANTICS.  */
832
833         while (NT_SUCCESS(status = NtQueryDirectoryFile(h, NULL, NULL, NULL,
834                                                         &iosb, buf, bufsize,
835                                                         FileNamesInformation,
836                                                         FALSE, NULL, FALSE)))
837         {
838                 const FILE_NAMES_INFORMATION *info = buf;
839                 for (;;) {
840                         if (!should_ignore_filename(info->FileName,
841                                                     info->FileNameLength / 2))
842                         {
843                                 struct wim_dentry *child;
844                                 size_t orig_path_nchars;
845                                 const wchar_t *filename;
846
847                                 ret = WIMLIB_ERR_NOMEM;
848                                 filename = pathbuf_append_name(ctx->params,
849                                                                info->FileName,
850                                                                info->FileNameLength / 2,
851                                                                &orig_path_nchars);
852                                 if (!filename)
853                                         goto out_free_buf;
854
855                                 ret = winnt_build_dentry_tree(
856                                                         &child,
857                                                         h,
858                                                         filename,
859                                                         info->FileNameLength / 2,
860                                                         filename,
861                                                         ctx,
862                                                         true);
863
864                                 pathbuf_truncate(ctx->params, orig_path_nchars);
865
866                                 if (ret)
867                                         goto out_free_buf;
868                                 attach_scanned_tree(parent, child,
869                                                     ctx->params->blob_table);
870                         }
871                         if (info->NextEntryOffset == 0)
872                                 break;
873                         info = (const FILE_NAMES_INFORMATION *)
874                                         ((const u8 *)info + info->NextEntryOffset);
875                 }
876         }
877
878         if (unlikely(status != STATUS_NO_MORE_FILES)) {
879                 winnt_error(status, L"\"%ls\": Can't read directory",
880                             printable_path(ctx));
881                 ret = WIMLIB_ERR_READ;
882         }
883 out_free_buf:
884         FREE(buf);
885         return ret;
886 }
887
888 /* Reparse point fixup status code  */
889 #define RP_FIXED        (-1)
890
891 static bool
892 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
893 {
894         NTSTATUS status;
895         IO_STATUS_BLOCK iosb;
896         FILE_INTERNAL_INFORMATION int_info;
897         FILE_FS_VOLUME_INFORMATION vol_info;
898
899         status = NtQueryInformationFile(h, &iosb, &int_info, sizeof(int_info),
900                                         FileInternalInformation);
901         if (!NT_SUCCESS(status))
902                 return false;
903
904         if (int_info.IndexNumber.QuadPart != ino)
905                 return false;
906
907         status = NtQueryVolumeInformationFile(h, &iosb,
908                                               &vol_info, sizeof(vol_info),
909                                               FileFsVolumeInformation);
910         if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
911                 return false;
912
913         if (iosb.Information <
914              offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
915              sizeof(vol_info.VolumeSerialNumber))
916                 return false;
917
918         return (vol_info.VolumeSerialNumber == dev);
919 }
920
921 /*
922  * This is the Windows equivalent of unix_relativize_link_target(); see there
923  * for general details.  This version works with an "absolute" Windows link
924  * target, specified from the root of the Windows kernel object namespace.  Note
925  * that we have to open directories with a trailing slash when present because
926  * \??\E: opens the E: device itself and not the filesystem root directory.
927  */
928 static const wchar_t *
929 winnt_relativize_link_target(const wchar_t *target, size_t target_nbytes,
930                              u64 ino, u64 dev)
931 {
932         UNICODE_STRING name;
933         OBJECT_ATTRIBUTES attr;
934         IO_STATUS_BLOCK iosb;
935         NTSTATUS status;
936         const wchar_t *target_end;
937         const wchar_t *p;
938
939         target_end = target + (target_nbytes / sizeof(wchar_t));
940
941         /* Empty path??? */
942         if (target_end == target)
943                 return target;
944
945         /* No leading slash???  */
946         if (target[0] != L'\\')
947                 return target;
948
949         /* UNC path???  */
950         if ((target_end - target) >= 2 &&
951             target[0] == L'\\' && target[1] == L'\\')
952                 return target;
953
954         attr.Length = sizeof(attr);
955         attr.RootDirectory = NULL;
956         attr.ObjectName = &name;
957         attr.Attributes = 0;
958         attr.SecurityDescriptor = NULL;
959         attr.SecurityQualityOfService = NULL;
960
961         name.Buffer = (wchar_t *)target;
962         name.Length = 0;
963         p = target;
964         do {
965                 HANDLE h;
966                 const wchar_t *orig_p = p;
967
968                 /* Skip non-backslashes  */
969                 while (p != target_end && *p != L'\\')
970                         p++;
971
972                 /* Skip backslashes  */
973                 while (p != target_end && *p == L'\\')
974                         p++;
975
976                 /* Append path component  */
977                 name.Length += (p - orig_p) * sizeof(wchar_t);
978                 name.MaximumLength = name.Length;
979
980                 /* Try opening the file  */
981                 status = NtOpenFile(&h,
982                                     FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
983                                     &attr,
984                                     &iosb,
985                                     FILE_SHARE_VALID_FLAGS,
986                                     FILE_OPEN_FOR_BACKUP_INTENT);
987
988                 if (NT_SUCCESS(status)) {
989                         /* Reset root directory  */
990                         if (attr.RootDirectory)
991                                 NtClose(attr.RootDirectory);
992                         attr.RootDirectory = h;
993                         name.Buffer = (wchar_t *)p;
994                         name.Length = 0;
995
996                         if (file_has_ino_and_dev(h, ino, dev))
997                                 goto out_close_root_dir;
998                 }
999         } while (p != target_end);
1000
1001         p = target;
1002
1003 out_close_root_dir:
1004         if (attr.RootDirectory)
1005                 NtClose(attr.RootDirectory);
1006         while (p > target && *(p - 1) == L'\\')
1007                 p--;
1008         return p;
1009 }
1010
1011 static int
1012 winnt_rpfix_progress(struct scan_params *params,
1013                      const struct link_reparse_point *link, int scan_status)
1014 {
1015         size_t print_name_nchars = link->print_name_nbytes / sizeof(wchar_t);
1016         wchar_t print_name0[print_name_nchars + 1];
1017
1018         wmemcpy(print_name0, link->print_name, print_name_nchars);
1019         print_name0[print_name_nchars] = L'\0';
1020
1021         params->progress.scan.symlink_target = print_name0;
1022         return do_scan_progress(params, scan_status, NULL);
1023 }
1024
1025 static int
1026 winnt_try_rpfix(struct reparse_buffer_disk *rpbuf, u16 *rpbuflen_p,
1027                 struct scan_params *params)
1028 {
1029         struct link_reparse_point link;
1030         const wchar_t *rel_target;
1031         int ret;
1032
1033         if (parse_link_reparse_point(rpbuf, *rpbuflen_p, &link)) {
1034                 /* Couldn't understand the reparse data; don't do the fixup.  */
1035                 return 0;
1036         }
1037
1038         /*
1039          * Don't do reparse point fixups on relative symbolic links.
1040          *
1041          * On Windows, a relative symbolic link is supposed to be identifiable
1042          * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
1043          * SYMBOLIC_LINK_RELATIVE.  We will use this information, although this
1044          * may not always do what the user expects, since drive-relative
1045          * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
1046          * set, in addition to truly relative symbolic links such as "Users" or
1047          * "Users\Public".  However, WIMGAPI (as of Windows 8.1) has this same
1048          * behavior.
1049          *
1050          * Otherwise, as far as I can tell, the targets of symbolic links that
1051          * are NOT relative, as well as junctions (note: a mountpoint is the
1052          * sames thing as a junction), must be NT namespace paths, for example:
1053          *
1054          *     - \??\e:\Users\Public
1055          *     - \DosDevices\e:\Users\Public
1056          *     - \Device\HardDiskVolume4\Users\Public
1057          *     - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
1058          *     - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
1059          */
1060         if (link_is_relative_symlink(&link))
1061                 return 0;
1062
1063         rel_target = winnt_relativize_link_target(link.substitute_name,
1064                                                   link.substitute_name_nbytes,
1065                                                   params->capture_root_ino,
1066                                                   params->capture_root_dev);
1067
1068         if (rel_target == link.substitute_name) {
1069                 /* Target points outside of the tree being captured or had an
1070                  * unrecognized path format.  Don't adjust it.  */
1071                 return winnt_rpfix_progress(params, &link,
1072                                             WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK);
1073         }
1074
1075         /* We have an absolute target pointing within the directory being
1076          * captured. @rel_target is the suffix of the link target that is the
1077          * part relative to the directory being captured.
1078          *
1079          * We will cut off the prefix before this part (which is the path to the
1080          * directory being captured) and add a dummy prefix.  Since the process
1081          * will need to be reversed when applying the image, it doesn't matter
1082          * what exactly the prefix is, as long as it looks like an absolute
1083          * path.  */
1084
1085         static const wchar_t prefix[6] = L"\\??\\X:";
1086         static const size_t num_unprintable_chars = 4;
1087
1088         size_t rel_target_nbytes =
1089                 link.substitute_name_nbytes - ((const u8 *)rel_target -
1090                                                (const u8 *)link.substitute_name);
1091
1092         wchar_t tmp[(sizeof(prefix) + rel_target_nbytes) / sizeof(wchar_t)];
1093
1094         memcpy(tmp, prefix, sizeof(prefix));
1095         memcpy(tmp + ARRAY_LEN(prefix), rel_target, rel_target_nbytes);
1096
1097         link.substitute_name = tmp;
1098         link.substitute_name_nbytes = sizeof(tmp);
1099
1100         link.print_name = link.substitute_name + num_unprintable_chars;
1101         link.print_name_nbytes = link.substitute_name_nbytes -
1102                                  (num_unprintable_chars * sizeof(wchar_t));
1103
1104         if (make_link_reparse_point(&link, rpbuf, rpbuflen_p))
1105                 return 0;
1106
1107         ret = winnt_rpfix_progress(params, &link,
1108                                    WIMLIB_SCAN_DENTRY_FIXED_SYMLINK);
1109         if (ret)
1110                 return ret;
1111         return RP_FIXED;
1112 }
1113
1114 /* Load the reparse data of a file into the corresponding WIM inode.  If the
1115  * reparse point is a symbolic link or junction with an absolute target and
1116  * RPFIX mode is enabled, then also rewrite its target to be relative to the
1117  * capture root.  */
1118 static noinline_for_stack int
1119 winnt_load_reparse_data(HANDLE h, struct wim_inode *inode,
1120                         struct winnt_scan_ctx *ctx)
1121 {
1122         struct reparse_buffer_disk rpbuf;
1123         NTSTATUS status;
1124         u32 len;
1125         u16 rpbuflen;
1126         int ret;
1127
1128         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1129                 /* See comment above assign_stream_types_encrypted()  */
1130                 WARNING("Ignoring reparse data of encrypted file \"%ls\"",
1131                         printable_path(ctx));
1132                 return 0;
1133         }
1134
1135         status = winnt_fsctl(h, FSCTL_GET_REPARSE_POINT,
1136                              NULL, 0, &rpbuf, sizeof(rpbuf), &len);
1137         if (!NT_SUCCESS(status)) {
1138                 winnt_error(status, L"\"%ls\": Can't get reparse point",
1139                             printable_path(ctx));
1140                 return WIMLIB_ERR_READLINK;
1141         }
1142
1143         rpbuflen = len;
1144
1145         if (unlikely(rpbuflen < REPARSE_DATA_OFFSET)) {
1146                 ERROR("\"%ls\": reparse point buffer is too short",
1147                       printable_path(ctx));
1148                 return WIMLIB_ERR_INVALID_REPARSE_DATA;
1149         }
1150
1151         if (le32_to_cpu(rpbuf.rptag) == WIM_IO_REPARSE_TAG_DEDUP) {
1152                 /*
1153                  * Windows treats Data Deduplication reparse points specially.
1154                  * Reads from the unnamed data stream actually return the
1155                  * redirected file contents, even with FILE_OPEN_REPARSE_POINT.
1156                  * Deduplicated files also cannot be properly restored without
1157                  * also restoring the "System Volume Information" directory,
1158                  * which wimlib excludes by default.  Therefore, the logical
1159                  * behavior for us seems to be to ignore the reparse point and
1160                  * treat the file as a normal file.
1161                  */
1162                 inode->i_attributes &= ~FILE_ATTRIBUTE_REPARSE_POINT;
1163                 return 0;
1164         }
1165
1166         if (ctx->params->add_flags & WIMLIB_ADD_FLAG_RPFIX) {
1167                 ret = winnt_try_rpfix(&rpbuf, &rpbuflen, ctx->params);
1168                 if (ret == RP_FIXED)
1169                         inode->i_rp_flags &= ~WIM_RP_FLAG_NOT_FIXED;
1170                 else if (ret)
1171                         return ret;
1172         }
1173
1174         inode->i_reparse_tag = le32_to_cpu(rpbuf.rptag);
1175         inode->i_rp_reserved = le16_to_cpu(rpbuf.rpreserved);
1176
1177         if (!inode_add_stream_with_data(inode,
1178                                         STREAM_TYPE_REPARSE_POINT,
1179                                         NO_STREAM_NAME,
1180                                         rpbuf.rpdata,
1181                                         rpbuflen - REPARSE_DATA_OFFSET,
1182                                         ctx->params->blob_table))
1183                 return WIMLIB_ERR_NOMEM;
1184
1185         return 0;
1186 }
1187
1188 static DWORD WINAPI
1189 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
1190                               unsigned long len)
1191 {
1192         *(u64*)_size_ret += len;
1193         return ERROR_SUCCESS;
1194 }
1195
1196 static int
1197 win32_get_encrypted_file_size(const wchar_t *path, bool is_dir, u64 *size_ret)
1198 {
1199         DWORD err;
1200         void *file_ctx;
1201         int ret;
1202         DWORD flags = 0;
1203
1204         if (is_dir)
1205                 flags |= CREATE_FOR_DIR;
1206
1207         err = OpenEncryptedFileRaw(path, flags, &file_ctx);
1208         if (err != ERROR_SUCCESS) {
1209                 win32_error(err,
1210                             L"Failed to open encrypted file \"%ls\" for raw read",
1211                             path);
1212                 return WIMLIB_ERR_OPEN;
1213         }
1214         *size_ret = 0;
1215         err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
1216                                    size_ret, file_ctx);
1217         if (err != ERROR_SUCCESS) {
1218                 win32_error(err,
1219                             L"Failed to read raw encrypted data from \"%ls\"",
1220                             path);
1221                 ret = WIMLIB_ERR_READ;
1222         } else {
1223                 ret = 0;
1224         }
1225         CloseEncryptedFileRaw(file_ctx);
1226         return ret;
1227 }
1228
1229 static int
1230 winnt_scan_efsrpc_raw_data(struct wim_inode *inode,
1231                            struct winnt_scan_ctx *ctx)
1232 {
1233         wchar_t *path = ctx->params->cur_path;
1234         size_t path_nchars = ctx->params->cur_path_nchars;
1235         const bool is_dir = (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY);
1236         struct windows_file *windows_file;
1237         u64 size;
1238         int ret;
1239
1240         /* OpenEncryptedFileRaw() expects a Win32 name.  */
1241         wimlib_assert(!wmemcmp(path, L"\\??\\", 4));
1242         path[1] = L'\\';
1243
1244         ret = win32_get_encrypted_file_size(path, is_dir, &size);
1245         if (ret)
1246                 goto out;
1247
1248         /* Empty EFSRPC data does not make sense  */
1249         wimlib_assert(size != 0);
1250
1251         windows_file = alloc_windows_file(path, path_nchars, NULL, 0,
1252                                           ctx->snapshot, true);
1253         ret = add_stream(inode, windows_file, size, STREAM_TYPE_EFSRPC_RAW_DATA,
1254                          NO_STREAM_NAME, ctx->params->unhashed_blobs);
1255 out:
1256         path[1] = L'?';
1257         return ret;
1258 }
1259
1260 static bool
1261 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1262                      const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
1263 {
1264         const wchar_t *sep, *type, *end;
1265
1266         /* The stream name should be returned as :NAME:TYPE  */
1267         if (raw_stream_name_nchars < 1)
1268                 return false;
1269         if (raw_stream_name[0] != L':')
1270                 return false;
1271
1272         raw_stream_name++;
1273         raw_stream_name_nchars--;
1274
1275         end = raw_stream_name + raw_stream_name_nchars;
1276
1277         sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
1278         if (!sep)
1279                 return false;
1280
1281         type = sep + 1;
1282         if (end - type != 5)
1283                 return false;
1284
1285         if (wmemcmp(type, L"$DATA", 5))
1286                 return false;
1287
1288         *stream_name_ret = raw_stream_name;
1289         *stream_name_nchars_ret = sep - raw_stream_name;
1290         return true;
1291 }
1292
1293 static int
1294 winnt_scan_data_stream(wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1295                        u64 stream_size, struct wim_inode *inode,
1296                        struct winnt_scan_ctx *ctx)
1297 {
1298         wchar_t *stream_name;
1299         size_t stream_name_nchars;
1300         struct windows_file *windows_file;
1301
1302         /* Given the raw stream name (which is something like
1303          * :streamname:$DATA), extract just the stream name part (streamname).
1304          * Ignore any non-$DATA streams.  */
1305         if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
1306                                   (const wchar_t **)&stream_name,
1307                                   &stream_name_nchars))
1308                 return 0;
1309
1310         stream_name[stream_name_nchars] = L'\0';
1311
1312         windows_file = alloc_windows_file(ctx->params->cur_path,
1313                                           ctx->params->cur_path_nchars,
1314                                           stream_name, stream_name_nchars,
1315                                           ctx->snapshot, false);
1316         return add_stream(inode, windows_file, stream_size, STREAM_TYPE_DATA,
1317                           stream_name, ctx->params->unhashed_blobs);
1318 }
1319
1320 /*
1321  * Load information about the data streams of an open file into a WIM inode.
1322  *
1323  * We use the NtQueryInformationFile() system call instead of FindFirstStream()
1324  * and FindNextStream().  This is done for two reasons:
1325  *
1326  * - FindFirstStream() opens its own handle to the file or directory and
1327  *   apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
1328  *   causing access denied errors on certain files (even when running as the
1329  *   Administrator).
1330  * - FindFirstStream() and FindNextStream() is only available on Windows Vista
1331  *   and later, whereas the stream support in NtQueryInformationFile() was
1332  *   already present in Windows XP.
1333  */
1334 static noinline_for_stack int
1335 winnt_scan_data_streams(HANDLE h, struct wim_inode *inode, u64 file_size,
1336                         struct winnt_scan_ctx *ctx)
1337 {
1338         int ret;
1339         u8 _buf[4096] _aligned_attribute(8);
1340         u8 *buf;
1341         size_t bufsize;
1342         IO_STATUS_BLOCK iosb;
1343         NTSTATUS status;
1344         FILE_STREAM_INFORMATION *info;
1345
1346         buf = _buf;
1347         bufsize = sizeof(_buf);
1348
1349         if (!(ctx->vol_flags & FILE_NAMED_STREAMS))
1350                 goto unnamed_only;
1351
1352         /* Get a buffer containing the stream information.  */
1353         while (!NT_SUCCESS(status = NtQueryInformationFile(h,
1354                                                            &iosb,
1355                                                            buf,
1356                                                            bufsize,
1357                                                            FileStreamInformation)))
1358         {
1359
1360                 switch (status) {
1361                 case STATUS_BUFFER_OVERFLOW:
1362                         {
1363                                 u8 *newbuf;
1364
1365                                 bufsize *= 2;
1366                                 if (buf == _buf)
1367                                         newbuf = MALLOC(bufsize);
1368                                 else
1369                                         newbuf = REALLOC(buf, bufsize);
1370                                 if (!newbuf) {
1371                                         ret = WIMLIB_ERR_NOMEM;
1372                                         goto out_free_buf;
1373                                 }
1374                                 buf = newbuf;
1375                         }
1376                         break;
1377                 case STATUS_NOT_IMPLEMENTED:
1378                 case STATUS_NOT_SUPPORTED:
1379                 case STATUS_INVALID_INFO_CLASS:
1380                         goto unnamed_only;
1381                 default:
1382                         winnt_error(status,
1383                                     L"\"%ls\": Failed to query stream information",
1384                                     printable_path(ctx));
1385                         ret = WIMLIB_ERR_READ;
1386                         goto out_free_buf;
1387                 }
1388         }
1389
1390         if (iosb.Information == 0) {
1391                 /* No stream information.  */
1392                 ret = 0;
1393                 goto out_free_buf;
1394         }
1395
1396         /* Parse one or more stream information structures.  */
1397         info = (FILE_STREAM_INFORMATION *)buf;
1398         for (;;) {
1399                 /* Load the stream information.  */
1400                 ret = winnt_scan_data_stream(info->StreamName,
1401                                              info->StreamNameLength / 2,
1402                                              info->StreamSize.QuadPart,
1403                                              inode, ctx);
1404                 if (ret)
1405                         goto out_free_buf;
1406
1407                 if (info->NextEntryOffset == 0) {
1408                         /* No more stream information.  */
1409                         break;
1410                 }
1411                 /* Advance to next stream information.  */
1412                 info = (FILE_STREAM_INFORMATION *)
1413                                 ((u8 *)info + info->NextEntryOffset);
1414         }
1415         ret = 0;
1416         goto out_free_buf;
1417
1418 unnamed_only:
1419         /* The volume does not support named streams.  Only capture the unnamed
1420          * data stream.  */
1421         if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1422                                    FILE_ATTRIBUTE_REPARSE_POINT))
1423         {
1424                 ret = 0;
1425                 goto out_free_buf;
1426         }
1427
1428         {
1429                 wchar_t stream_name[] = L"::$DATA";
1430                 ret = winnt_scan_data_stream(stream_name, 7, file_size,
1431                                              inode, ctx);
1432         }
1433 out_free_buf:
1434         /* Free buffer if allocated on heap.  */
1435         if (unlikely(buf != _buf))
1436                 FREE(buf);
1437         return ret;
1438 }
1439
1440 static u64
1441 extract_starting_lcn(const RETRIEVAL_POINTERS_BUFFER *extents)
1442 {
1443         if (extents->ExtentCount < 1)
1444                 return 0;
1445
1446         return extents->Extents[0].Lcn.QuadPart;
1447 }
1448
1449 static noinline_for_stack u64
1450 get_sort_key(HANDLE h)
1451 {
1452         STARTING_VCN_INPUT_BUFFER in = { .StartingVcn.QuadPart = 0 };
1453         RETRIEVAL_POINTERS_BUFFER out;
1454
1455         if (!NT_SUCCESS(winnt_fsctl(h, FSCTL_GET_RETRIEVAL_POINTERS,
1456                                     &in, sizeof(in), &out, sizeof(out), NULL)))
1457                 return 0;
1458
1459         return extract_starting_lcn(&out);
1460 }
1461
1462 static void
1463 set_sort_key(struct wim_inode *inode, u64 sort_key)
1464 {
1465         for (unsigned i = 0; i < inode->i_num_streams; i++) {
1466                 struct wim_inode_stream *strm = &inode->i_streams[i];
1467                 struct blob_descriptor *blob = stream_blob_resolved(strm);
1468                 if (blob && blob->blob_location == BLOB_IN_WINDOWS_FILE)
1469                         blob->windows_file->sort_key = sort_key;
1470         }
1471 }
1472
1473 static inline bool
1474 should_try_to_use_wimboot_hash(const struct wim_inode *inode,
1475                                const struct winnt_scan_ctx *ctx)
1476 {
1477         /* Directories and encrypted files aren't valid for external backing. */
1478         if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1479                                    FILE_ATTRIBUTE_ENCRYPTED))
1480                 return false;
1481
1482         /* If the file is a reparse point, then try the hash fixup if it's a WOF
1483          * reparse point and we're in WIMBOOT mode.  Otherwise, try the hash
1484          * fixup if WOF may be attached. */
1485         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1486                 return (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_WOF) &&
1487                         (ctx->params->add_flags & WIMLIB_ADD_FLAG_WIMBOOT);
1488         return !ctx->wof_not_attached;
1489 }
1490
1491 /*
1492  * This function implements an optimization for capturing files from a
1493  * filesystem with a backing WIM(s).  If a file is WIM-backed, then we can
1494  * retrieve the SHA-1 message digest of its original contents from its reparse
1495  * point.  This may eliminate the need to read the file's data and/or allow the
1496  * file's data to be immediately deduplicated with existing data in the WIM.
1497  *
1498  * If WOF is attached, then this function is merely an optimization, but
1499  * potentially a very effective one.  If WOF is detached, then this function
1500  * really causes WIM-backed files to be, effectively, automatically
1501  * "dereferenced" when possible; the unnamed data stream is updated to reference
1502  * the original contents and the reparse point is removed.
1503  *
1504  * This function returns 0 if the fixup succeeded or was intentionally not
1505  * executed.  Otherwise it returns an error code.
1506  */
1507 static noinline_for_stack int
1508 try_to_use_wimboot_hash(HANDLE h, struct wim_inode *inode,
1509                         struct winnt_scan_ctx *ctx)
1510 {
1511         struct blob_table *blob_table = ctx->params->blob_table;
1512         struct wim_inode_stream *reparse_strm = NULL;
1513         struct wim_inode_stream *strm;
1514         struct blob_descriptor *blob;
1515         u8 hash[SHA1_HASH_SIZE];
1516         int ret;
1517
1518         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1519                 struct reparse_buffer_disk rpbuf;
1520                 struct {
1521                         struct wof_external_info wof_info;
1522                         struct wim_provider_rpdata wim_info;
1523                 } *rpdata = (void *)rpbuf.rpdata;
1524                 struct blob_descriptor *reparse_blob;
1525
1526                 /* The file has a WOF reparse point, so WOF must be detached.
1527                  * We can read the reparse point directly.  */
1528                 ctx->wof_not_attached = true;
1529                 reparse_strm = inode_get_unnamed_stream(inode, STREAM_TYPE_REPARSE_POINT);
1530                 reparse_blob = stream_blob_resolved(reparse_strm);
1531
1532                 if (!reparse_blob || reparse_blob->size < sizeof(*rpdata))
1533                         return 0;  /* Not a WIM-backed file  */
1534
1535                 ret = read_blob_into_buf(reparse_blob, rpdata);
1536                 if (ret)
1537                         return ret;
1538
1539                 if (rpdata->wof_info.version != WOF_CURRENT_VERSION ||
1540                     rpdata->wof_info.provider != WOF_PROVIDER_WIM ||
1541                     rpdata->wim_info.version != 2)
1542                         return 0;  /* Not a WIM-backed file  */
1543
1544                 /* Okay, this is a WIM backed file.  Get its SHA-1 hash.  */
1545                 copy_hash(hash, rpdata->wim_info.unnamed_data_stream_hash);
1546         } else {
1547                 struct {
1548                         struct wof_external_info wof_info;
1549                         struct wim_provider_external_info wim_info;
1550                 } out;
1551                 NTSTATUS status;
1552
1553                 /* WOF may be attached.  Try reading this file's external
1554                  * backing info.  */
1555                 status = winnt_fsctl(h, FSCTL_GET_EXTERNAL_BACKING,
1556                                      NULL, 0, &out, sizeof(out), NULL);
1557
1558                 /* Is WOF not attached?  */
1559                 if (status == STATUS_INVALID_DEVICE_REQUEST ||
1560                     status == STATUS_NOT_SUPPORTED) {
1561                         ctx->wof_not_attached = true;
1562                         return 0;
1563                 }
1564
1565                 /* Is this file not externally backed?  */
1566                 if (status == STATUS_OBJECT_NOT_EXTERNALLY_BACKED)
1567                         return 0;
1568
1569                 /* Does this file have an unknown type of external backing that
1570                  * needed a larger information buffer?  */
1571                 if (status == STATUS_BUFFER_TOO_SMALL)
1572                         return 0;
1573
1574                 /* Was there some other failure?  */
1575                 if (status != STATUS_SUCCESS) {
1576                         winnt_error(status,
1577                                     L"\"%ls\": FSCTL_GET_EXTERNAL_BACKING failed",
1578                                     printable_path(ctx));
1579                         return WIMLIB_ERR_STAT;
1580                 }
1581
1582                 /* Is this file backed by a WIM?  */
1583                 if (out.wof_info.version != WOF_CURRENT_VERSION ||
1584                     out.wof_info.provider != WOF_PROVIDER_WIM ||
1585                     out.wim_info.version != WIM_PROVIDER_CURRENT_VERSION)
1586                         return 0;
1587
1588                 /* Okay, this is a WIM backed file.  Get its SHA-1 hash.  */
1589                 copy_hash(hash, out.wim_info.unnamed_data_stream_hash);
1590         }
1591
1592         /* If the file's unnamed data stream is nonempty, then fill in its hash
1593          * and deduplicate it if possible.
1594          *
1595          * With WOF detached, we require that the blob *must* de-duplicable for
1596          * any action can be taken, since without WOF we can't fall back to
1597          * getting the "dereferenced" data by reading the stream (the real
1598          * stream is sparse and contains all zeroes).  */
1599         strm = inode_get_unnamed_data_stream(inode);
1600         if (strm && (blob = stream_blob_resolved(strm))) {
1601                 struct blob_descriptor **back_ptr;
1602
1603                 if (reparse_strm && !lookup_blob(blob_table, hash))
1604                         return 0;
1605                 back_ptr = retrieve_pointer_to_unhashed_blob(blob);
1606                 copy_hash(blob->hash, hash);
1607                 if (after_blob_hashed(blob, back_ptr, blob_table) != blob)
1608                         free_blob_descriptor(blob);
1609         }
1610
1611         /* Remove the reparse point, if present.  */
1612         if (reparse_strm) {
1613                 inode_remove_stream(inode, reparse_strm, blob_table);
1614                 inode->i_attributes &= ~(FILE_ATTRIBUTE_REPARSE_POINT |
1615                                          FILE_ATTRIBUTE_SPARSE_FILE);
1616                 if (inode->i_attributes == 0)
1617                         inode->i_attributes = FILE_ATTRIBUTE_NORMAL;
1618         }
1619
1620         return 0;
1621 }
1622
1623 struct file_info {
1624         u32 attributes;
1625         u32 num_links;
1626         u64 creation_time;
1627         u64 last_write_time;
1628         u64 last_access_time;
1629         u64 ino;
1630         u64 end_of_file;
1631         u32 ea_size;
1632 };
1633
1634 static noinline_for_stack NTSTATUS
1635 get_file_info(HANDLE h, struct file_info *info)
1636 {
1637         IO_STATUS_BLOCK iosb;
1638         NTSTATUS status;
1639         FILE_ALL_INFORMATION all_info;
1640
1641         status = NtQueryInformationFile(h, &iosb, &all_info, sizeof(all_info),
1642                                         FileAllInformation);
1643
1644         if (unlikely(!NT_SUCCESS(status) && status != STATUS_BUFFER_OVERFLOW))
1645                 return status;
1646
1647         info->attributes = all_info.BasicInformation.FileAttributes;
1648         info->num_links = all_info.StandardInformation.NumberOfLinks;
1649         info->creation_time = all_info.BasicInformation.CreationTime.QuadPart;
1650         info->last_write_time = all_info.BasicInformation.LastWriteTime.QuadPart;
1651         info->last_access_time = all_info.BasicInformation.LastAccessTime.QuadPart;
1652         info->ino = all_info.InternalInformation.IndexNumber.QuadPart;
1653         info->end_of_file = all_info.StandardInformation.EndOfFile.QuadPart;
1654         info->ea_size = all_info.EaInformation.EaSize;
1655         return STATUS_SUCCESS;
1656 }
1657
1658 static void
1659 get_volume_information(HANDLE h, struct winnt_scan_ctx *ctx)
1660 {
1661         u8 _attr_info[sizeof(FILE_FS_ATTRIBUTE_INFORMATION) + 128] _aligned_attribute(8);
1662         FILE_FS_ATTRIBUTE_INFORMATION *attr_info = (void *)_attr_info;
1663         FILE_FS_VOLUME_INFORMATION vol_info;
1664         struct file_info file_info;
1665         IO_STATUS_BLOCK iosb;
1666         NTSTATUS status;
1667
1668         /* Get volume flags  */
1669         status = NtQueryVolumeInformationFile(h, &iosb, attr_info,
1670                                               sizeof(_attr_info),
1671                                               FileFsAttributeInformation);
1672         if (NT_SUCCESS(status)) {
1673                 ctx->vol_flags = attr_info->FileSystemAttributes;
1674                 ctx->is_ntfs = (attr_info->FileSystemNameLength == 4 * sizeof(wchar_t)) &&
1675                                 !wmemcmp(attr_info->FileSystemName, L"NTFS", 4);
1676         } else {
1677                 winnt_warning(status, L"\"%ls\": Can't get volume attributes",
1678                               printable_path(ctx));
1679         }
1680
1681         /* Get volume ID.  */
1682         status = NtQueryVolumeInformationFile(h, &iosb, &vol_info,
1683                                               sizeof(vol_info),
1684                                               FileFsVolumeInformation);
1685         if ((NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW) &&
1686             (iosb.Information >= offsetof(FILE_FS_VOLUME_INFORMATION,
1687                                           VolumeSerialNumber) +
1688              sizeof(vol_info.VolumeSerialNumber)))
1689         {
1690                 ctx->params->capture_root_dev = vol_info.VolumeSerialNumber;
1691         } else {
1692                 winnt_warning(status, L"\"%ls\": Can't get volume ID",
1693                               printable_path(ctx));
1694         }
1695
1696         /* Get inode number.  */
1697         status = get_file_info(h, &file_info);
1698         if (NT_SUCCESS(status)) {
1699                 ctx->params->capture_root_ino = file_info.ino;
1700         } else {
1701                 winnt_warning(status, L"\"%ls\": Can't get file information",
1702                               printable_path(ctx));
1703         }
1704 }
1705
1706 static int
1707 winnt_build_dentry_tree(struct wim_dentry **root_ret,
1708                         HANDLE cur_dir,
1709                         const wchar_t *relative_path,
1710                         size_t relative_path_nchars,
1711                         const wchar_t *filename,
1712                         struct winnt_scan_ctx *ctx,
1713                         bool recursive)
1714 {
1715         struct wim_dentry *root = NULL;
1716         struct wim_inode *inode = NULL;
1717         HANDLE h = NULL;
1718         int ret;
1719         NTSTATUS status;
1720         struct file_info file_info;
1721         u64 sort_key;
1722
1723         ret = try_exclude(ctx->params);
1724         if (unlikely(ret < 0)) /* Excluded? */
1725                 goto out_progress;
1726         if (unlikely(ret > 0)) /* Error? */
1727                 goto out;
1728
1729         /* Open the file with permission to read metadata.  Although we will
1730          * later need a handle with FILE_LIST_DIRECTORY permission (or,
1731          * equivalently, FILE_READ_DATA; they're the same numeric value) if the
1732          * file is a directory, it can significantly slow things down to request
1733          * this permission on all nondirectories.  Perhaps it causes Windows to
1734          * start prefetching the file contents...  */
1735         status = winnt_openat(cur_dir, relative_path, relative_path_nchars,
1736                               FILE_READ_ATTRIBUTES | FILE_READ_EA |
1737                                 READ_CONTROL | ACCESS_SYSTEM_SECURITY,
1738                               &h);
1739         if (unlikely(!NT_SUCCESS(status))) {
1740                 if (status == STATUS_DELETE_PENDING) {
1741                         WARNING("\"%ls\": Deletion pending; skipping file",
1742                                 printable_path(ctx));
1743                         ret = 0;
1744                         goto out;
1745                 }
1746                 if (status == STATUS_SHARING_VIOLATION) {
1747                         ERROR("Can't open \"%ls\":\n"
1748                               "        File is in use by another process! "
1749                               "Consider using snapshot (VSS) mode.",
1750                               printable_path(ctx));
1751                         ret = WIMLIB_ERR_OPEN;
1752                         goto out;
1753                 }
1754                 winnt_error(status, L"\"%ls\": Can't open file",
1755                             printable_path(ctx));
1756                 if (status == STATUS_FVE_LOCKED_VOLUME)
1757                         ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1758                 else
1759                         ret = WIMLIB_ERR_OPEN;
1760                 goto out;
1761         }
1762
1763         /* Get information about the file.  */
1764         status = get_file_info(h, &file_info);
1765         if (!NT_SUCCESS(status)) {
1766                 winnt_error(status, L"\"%ls\": Can't get file information",
1767                             printable_path(ctx));
1768                 ret = WIMLIB_ERR_STAT;
1769                 goto out;
1770         }
1771
1772         /* Create a WIM dentry with an associated inode, which may be shared.
1773          *
1774          * However, we need to explicitly check for directories and files with
1775          * only 1 link and refuse to hard link them.  This is because Windows
1776          * has a bug where it can return duplicate File IDs for files and
1777          * directories on the FAT filesystem.
1778          *
1779          * Since we don't follow mount points on Windows, we don't need to query
1780          * the volume ID per-file.  Just once, for the root, is enough.  But we
1781          * can't simply pass 0, because then there could be inode collisions
1782          * among multiple calls to win32_build_dentry_tree() that are scanning
1783          * files on different volumes.  */
1784         ret = inode_table_new_dentry(ctx->params->inode_table,
1785                                      filename,
1786                                      file_info.ino,
1787                                      ctx->params->capture_root_dev,
1788                                      (file_info.num_links <= 1),
1789                                      &root);
1790         if (ret)
1791                 goto out;
1792
1793         /* Get the short (DOS) name of the file.  */
1794         status = winnt_get_short_name(h, root);
1795
1796         /* If we can't read the short filename for any reason other than
1797          * out-of-memory, just ignore the error and assume the file has no short
1798          * name.  This shouldn't be an issue, since the short names are
1799          * essentially obsolete anyway.  */
1800         if (unlikely(status == STATUS_NO_MEMORY)) {
1801                 ret = WIMLIB_ERR_NOMEM;
1802                 goto out;
1803         }
1804
1805         inode = root->d_inode;
1806
1807         if (inode->i_nlink > 1) {
1808                 /* Shared inode (hard link); skip reading per-inode information.
1809                  */
1810                 goto out_progress;
1811         }
1812
1813         inode->i_attributes = file_info.attributes;
1814         inode->i_creation_time = file_info.creation_time;
1815         inode->i_last_write_time = file_info.last_write_time;
1816         inode->i_last_access_time = file_info.last_access_time;
1817
1818         /* Get the file's security descriptor, unless we are capturing in
1819          * NO_ACLS mode or the volume does not support security descriptors.  */
1820         if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1821             && (ctx->vol_flags & FILE_PERSISTENT_ACLS))
1822         {
1823                 ret = winnt_load_security_descriptor(h, inode, ctx);
1824                 if (ret)
1825                         goto out;
1826         }
1827
1828         /* Get the file's object ID.  */
1829         ret = winnt_load_object_id(h, inode, ctx);
1830         if (ret)
1831                 goto out;
1832
1833         /* Get the file's extended attributes.  */
1834         if (unlikely(file_info.ea_size != 0)) {
1835                 ret = winnt_load_xattrs(h, inode, ctx, file_info.ea_size);
1836                 if (ret)
1837                         goto out;
1838         }
1839
1840         /* If this is a reparse point, load the reparse data.  */
1841         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1842                 ret = winnt_load_reparse_data(h, inode, ctx);
1843                 if (ret)
1844                         goto out;
1845         }
1846
1847         sort_key = get_sort_key(h);
1848
1849         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1850                 /* Load information about the raw encrypted data.  This is
1851                  * needed for any directory or non-directory that has
1852                  * FILE_ATTRIBUTE_ENCRYPTED set.
1853                  *
1854                  * Note: since OpenEncryptedFileRaw() fails with
1855                  * ERROR_SHARING_VIOLATION if there are any open handles to the
1856                  * file, we have to close the file and re-open it later if
1857                  * needed.  */
1858                 NtClose(h);
1859                 h = NULL;
1860                 ret = winnt_scan_efsrpc_raw_data(inode, ctx);
1861                 if (ret)
1862                         goto out;
1863         } else {
1864                 /*
1865                  * Load information about data streams (unnamed and named).
1866                  *
1867                  * Skip this step for encrypted files, since the data from
1868                  * ReadEncryptedFileRaw() already contains all data streams (and
1869                  * they do in fact all get restored by WriteEncryptedFileRaw().)
1870                  *
1871                  * Note: WIMGAPI (as of Windows 8.1) gets wrong and stores both
1872                  * the EFSRPC data and the named data stream(s)...!
1873                  */
1874                 ret = winnt_scan_data_streams(h,
1875                                               inode,
1876                                               file_info.end_of_file,
1877                                               ctx);
1878                 if (ret)
1879                         goto out;
1880         }
1881
1882         if (unlikely(should_try_to_use_wimboot_hash(inode, ctx))) {
1883                 ret = try_to_use_wimboot_hash(h, inode, ctx);
1884                 if (ret)
1885                         goto out;
1886         }
1887
1888         set_sort_key(inode, sort_key);
1889
1890         if (inode_is_directory(inode) && recursive) {
1891
1892                 /* Directory: recurse to children.  */
1893
1894                 /* Re-open the directory with FILE_LIST_DIRECTORY access.  */
1895                 if (h) {
1896                         NtClose(h);
1897                         h = NULL;
1898                 }
1899                 status = winnt_openat(cur_dir, relative_path,
1900                                       relative_path_nchars, FILE_LIST_DIRECTORY,
1901                                       &h);
1902                 if (!NT_SUCCESS(status)) {
1903                         winnt_error(status, L"\"%ls\": Can't open directory",
1904                                     printable_path(ctx));
1905                         ret = WIMLIB_ERR_OPEN;
1906                         goto out;
1907                 }
1908                 ret = winnt_recurse_directory(h, root, ctx);
1909                 if (ret)
1910                         goto out;
1911         }
1912
1913 out_progress:
1914         ret = 0;
1915         if (recursive) { /* if !recursive, caller handles progress */
1916                 if (likely(root))
1917                         ret = do_scan_progress(ctx->params,
1918                                                WIMLIB_SCAN_DENTRY_OK, inode);
1919                 else
1920                         ret = do_scan_progress(ctx->params,
1921                                                WIMLIB_SCAN_DENTRY_EXCLUDED,
1922                                                NULL);
1923         }
1924 out:
1925         if (likely(h))
1926                 NtClose(h);
1927         if (unlikely(ret)) {
1928                 free_dentry_tree(root, ctx->params->blob_table);
1929                 root = NULL;
1930                 ret = report_scan_error(ctx->params, ret);
1931         }
1932         *root_ret = root;
1933         return ret;
1934 }
1935
1936 static void
1937 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_ctx *ctx)
1938 {
1939         if (likely(ctx->num_get_sacl_priv_notheld == 0 &&
1940                    ctx->num_get_sd_access_denied == 0))
1941                 return;
1942
1943         WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1944         if (ctx->num_get_sacl_priv_notheld != 0) {
1945                 WARNING("- Could not capture SACL (System Access Control List)\n"
1946                         "            on %lu files or directories.",
1947                         ctx->num_get_sacl_priv_notheld);
1948         }
1949         if (ctx->num_get_sd_access_denied != 0) {
1950                 WARNING("- Could not capture security descriptor at all\n"
1951                         "            on %lu files or directories.",
1952                         ctx->num_get_sd_access_denied);
1953         }
1954         WARNING("To fully capture all security descriptors, run the program\n"
1955                 "          with Administrator rights.");
1956 }
1957
1958 /*----------------------------------------------------------------------------*
1959  *                         Fast MFT scan implementation                       *
1960  *----------------------------------------------------------------------------*/
1961
1962 #define ENABLE_FAST_MFT_SCAN    1
1963
1964 #ifdef ENABLE_FAST_MFT_SCAN
1965
1966 typedef struct {
1967         u64 StartingCluster;
1968         u64 ClusterCount;
1969 } CLUSTER_RANGE;
1970
1971 typedef struct {
1972         u64 StartingFileReferenceNumber;
1973         u64 EndingFileReferenceNumber;
1974 } FILE_REFERENCE_RANGE;
1975
1976 /* The FSCTL_QUERY_FILE_LAYOUT ioctl.  This ioctl can be used on Windows 8 and
1977  * later to scan the MFT of an NTFS volume.  */
1978 #define FSCTL_QUERY_FILE_LAYOUT         CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 157, METHOD_NEITHER, FILE_ANY_ACCESS)
1979
1980 /* The input to FSCTL_QUERY_FILE_LAYOUT  */
1981 typedef struct {
1982         u32 NumberOfPairs;
1983 #define QUERY_FILE_LAYOUT_RESTART                                       0x00000001
1984 #define QUERY_FILE_LAYOUT_INCLUDE_NAMES                                 0x00000002
1985 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS                               0x00000004
1986 #define QUERY_FILE_LAYOUT_INCLUDE_EXTENTS                               0x00000008
1987 #define QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO                            0x00000010
1988 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED    0x00000020
1989         u32 Flags;
1990 #define QUERY_FILE_LAYOUT_FILTER_TYPE_NONE              0
1991 #define QUERY_FILE_LAYOUT_FILTER_TYPE_CLUSTERS          1
1992 #define QUERY_FILE_LAYOUT_FILTER_TYPE_FILEID            2
1993 #define QUERY_FILE_LAYOUT_NUM_FILTER_TYPES              3
1994         u32 FilterType;
1995         u32 Reserved;
1996         union {
1997                 CLUSTER_RANGE ClusterRanges[1];
1998                 FILE_REFERENCE_RANGE FileReferenceRanges[1];
1999         } Filter;
2000 } QUERY_FILE_LAYOUT_INPUT;
2001
2002 /* The header of the buffer returned by FSCTL_QUERY_FILE_LAYOUT  */
2003 typedef struct {
2004         u32 FileEntryCount;
2005         u32 FirstFileOffset;
2006 #define QUERY_FILE_LAYOUT_SINGLE_INSTANCED                              0x00000001
2007         u32 Flags;
2008         u32 Reserved;
2009 } QUERY_FILE_LAYOUT_OUTPUT;
2010
2011 /* Inode information returned by FSCTL_QUERY_FILE_LAYOUT  */
2012 typedef struct {
2013         u32 Version;
2014         u32 NextFileOffset;
2015         u32 Flags;
2016         u32 FileAttributes;
2017         u64 FileReferenceNumber;
2018         u32 FirstNameOffset;
2019         u32 FirstStreamOffset;
2020         u32 ExtraInfoOffset;
2021         u32 Reserved;
2022 } FILE_LAYOUT_ENTRY;
2023
2024 /* Extra inode information returned by FSCTL_QUERY_FILE_LAYOUT  */
2025 typedef struct {
2026         struct {
2027                 u64 CreationTime;
2028                 u64 LastAccessTime;
2029                 u64 LastWriteTime;
2030                 u64 ChangeTime;
2031                 u32 FileAttributes;
2032         } BasicInformation;
2033         u32 OwnerId;
2034         u32 SecurityId;
2035         s64 Usn;
2036 } FILE_LAYOUT_INFO_ENTRY;
2037
2038 /* Filename (or dentry) information returned by FSCTL_QUERY_FILE_LAYOUT  */
2039 typedef struct {
2040         u32 NextNameOffset;
2041 #define FILE_LAYOUT_NAME_ENTRY_PRIMARY  0x00000001
2042 #define FILE_LAYOUT_NAME_ENTRY_DOS      0x00000002
2043         u32 Flags;
2044         u64 ParentFileReferenceNumber;
2045         u32 FileNameLength;
2046         u32 Reserved;
2047         wchar_t FileName[1];
2048 } FILE_LAYOUT_NAME_ENTRY;
2049
2050 /* Stream information returned by FSCTL_QUERY_FILE_LAYOUT  */
2051 typedef struct {
2052         u32 Version;
2053         u32 NextStreamOffset;
2054 #define STREAM_LAYOUT_ENTRY_IMMOVABLE                   0x00000001
2055 #define STREAM_LAYOUT_ENTRY_PINNED                      0x00000002
2056 #define STREAM_LAYOUT_ENTRY_RESIDENT                    0x00000004
2057 #define STREAM_LAYOUT_ENTRY_NO_CLUSTERS_ALLOCATED       0x00000008
2058         u32 Flags;
2059         u32 ExtentInformationOffset;
2060         u64 AllocationSize;
2061         u64 EndOfFile;
2062         u64 Reserved;
2063         u32 AttributeFlags;
2064         u32 StreamIdentifierLength;
2065         wchar_t StreamIdentifier[1];
2066 } STREAM_LAYOUT_ENTRY;
2067
2068
2069 typedef struct {
2070 #define STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS       0x00000001
2071 #define STREAM_EXTENT_ENTRY_ALL_EXTENTS                 0x00000002
2072         u32 Flags;
2073         union {
2074                 RETRIEVAL_POINTERS_BUFFER RetrievalPointers;
2075         } ExtentInformation;
2076 } STREAM_EXTENT_ENTRY;
2077
2078 /* Extract the MFT number part of the full inode number  */
2079 #define NTFS_MFT_NO(ref)        ((ref) & (((u64)1 << 48) - 1))
2080
2081 /* Is the file the root directory of the NTFS volume?  The root directory always
2082  * occupies MFT record 5.  */
2083 #define NTFS_IS_ROOT_FILE(ino)  (NTFS_MFT_NO(ino) == 5)
2084
2085 /* Is the file a special NTFS file, other than the root directory?  The special
2086  * files are the first 16 records in the MFT.  */
2087 #define NTFS_IS_SPECIAL_FILE(ino)                       \
2088         (NTFS_MFT_NO(ino) <= 15 && !NTFS_IS_ROOT_FILE(ino))
2089
2090 #define NTFS_SPECIAL_STREAM_OBJECT_ID           0x00000001
2091 #define NTFS_SPECIAL_STREAM_EA                  0x00000002
2092 #define NTFS_SPECIAL_STREAM_EA_INFORMATION      0x00000004
2093
2094 /* Intermediate inode structure.  This is used to temporarily save information
2095  * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_inode'.  */
2096 struct ntfs_inode {
2097         struct avl_tree_node index_node;
2098         u64 ino;
2099         u64 creation_time;
2100         u64 last_access_time;
2101         u64 last_write_time;
2102         u64 starting_lcn;
2103         u32 attributes;
2104         u32 security_id;
2105         u32 num_aliases;
2106         u32 num_streams;
2107         u32 special_streams;
2108         u32 first_stream_offset;
2109         struct ntfs_dentry *first_child;
2110         wchar_t short_name[13];
2111 };
2112
2113 /* Intermediate dentry structure.  This is used to temporarily save information
2114  * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_dentry'. */
2115 struct ntfs_dentry {
2116         u32 offset_from_inode : 31;
2117         u32 is_primary : 1;
2118         union {
2119                 /* Note: build_children_lists() replaces 'parent_ino' with
2120                  * 'next_child'.  */
2121                 u64 parent_ino;
2122                 struct ntfs_dentry *next_child;
2123         };
2124         wchar_t name[0];
2125 };
2126
2127 /* Intermediate stream structure.  This is used to temporarily save information
2128  * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct
2129  * wim_inode_stream'.  */
2130 struct ntfs_stream {
2131         u64 size;
2132         wchar_t name[0];
2133 };
2134
2135 /* Map of all known NTFS inodes, keyed by inode number  */
2136 struct ntfs_inode_map {
2137         struct avl_tree_node *root;
2138 };
2139
2140 #define NTFS_INODE(node)                                \
2141         avl_tree_entry((node), struct ntfs_inode, index_node)
2142
2143 #define SKIP_ALIGNED(p, size)   ((void *)(p) + ALIGN((size), 8))
2144
2145 /* Get a pointer to the first dentry of the inode.  */
2146 #define FIRST_DENTRY(ni) SKIP_ALIGNED((ni), sizeof(struct ntfs_inode))
2147
2148 /* Get a pointer to the first stream of the inode.  */
2149 #define FIRST_STREAM(ni) ((const void *)ni + ni->first_stream_offset)
2150
2151 /* Advance to the next dentry of the inode.  */
2152 #define NEXT_DENTRY(nd)  SKIP_ALIGNED((nd), sizeof(struct ntfs_dentry) +   \
2153                                 (wcslen((nd)->name) + 1) * sizeof(wchar_t))
2154
2155 /* Advance to the next stream of the inode.  */
2156 #define NEXT_STREAM(ns)  SKIP_ALIGNED((ns), sizeof(struct ntfs_stream) +   \
2157                                 (wcslen((ns)->name) + 1) * sizeof(wchar_t))
2158
2159 static int
2160 _avl_cmp_ntfs_inodes(const struct avl_tree_node *node1,
2161                      const struct avl_tree_node *node2)
2162 {
2163         return cmp_u64(NTFS_INODE(node1)->ino, NTFS_INODE(node2)->ino);
2164 }
2165
2166 /* Adds an NTFS inode to the map.  */
2167 static void
2168 ntfs_inode_map_add_inode(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2169 {
2170         if (avl_tree_insert(&map->root, &ni->index_node, _avl_cmp_ntfs_inodes)) {
2171                 WARNING("Inode 0x%016"PRIx64" is a duplicate!", ni->ino);
2172                 FREE(ni);
2173         }
2174 }
2175
2176 /* Find an ntfs_inode in the map by inode number.  Returns NULL if not found. */
2177 static struct ntfs_inode *
2178 ntfs_inode_map_lookup(struct ntfs_inode_map *map, u64 ino)
2179 {
2180         struct ntfs_inode tmp;
2181         struct avl_tree_node *res;
2182
2183         tmp.ino = ino;
2184         res = avl_tree_lookup_node(map->root, &tmp.index_node, _avl_cmp_ntfs_inodes);
2185         if (!res)
2186                 return NULL;
2187         return NTFS_INODE(res);
2188 }
2189
2190 /* Remove an ntfs_inode from the map and free it.  */
2191 static void
2192 ntfs_inode_map_remove(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2193 {
2194         avl_tree_remove(&map->root, &ni->index_node);
2195         FREE(ni);
2196 }
2197
2198 /* Free all ntfs_inodes in the map.  */
2199 static void
2200 ntfs_inode_map_destroy(struct ntfs_inode_map *map)
2201 {
2202         struct ntfs_inode *ni;
2203
2204         avl_tree_for_each_in_postorder(ni, map->root, struct ntfs_inode, index_node)
2205                 FREE(ni);
2206 }
2207
2208 static bool
2209 file_has_streams(const FILE_LAYOUT_ENTRY *file)
2210 {
2211         return (file->FirstStreamOffset != 0) &&
2212                 !(file->FileAttributes & FILE_ATTRIBUTE_ENCRYPTED);
2213 }
2214
2215 static bool
2216 is_valid_name_entry(const FILE_LAYOUT_NAME_ENTRY *name)
2217 {
2218         return name->FileNameLength > 0 &&
2219                 name->FileNameLength % 2 == 0 &&
2220                 !wmemchr(name->FileName, L'\0', name->FileNameLength / 2) &&
2221                 (!(name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) ||
2222                  name->FileNameLength <= 24);
2223 }
2224
2225 /* Validate the FILE_LAYOUT_NAME_ENTRYs of the specified file and compute the
2226  * total length in bytes of the ntfs_dentry structures needed to hold the name
2227  * information.  */
2228 static int
2229 validate_names_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2230                                         size_t *total_length_ret)
2231 {
2232         const FILE_LAYOUT_NAME_ENTRY *name =
2233                 (const void *)file + file->FirstNameOffset;
2234         size_t total = 0;
2235         size_t num_long_names = 0;
2236
2237         for (;;) {
2238                 if (unlikely(!is_valid_name_entry(name))) {
2239                         ERROR("Invalid FILE_LAYOUT_NAME_ENTRY! "
2240                               "FileReferenceNumber=0x%016"PRIx64", "
2241                               "FileNameLength=%"PRIu32", "
2242                               "FileName=%.*ls, Flags=0x%08"PRIx32,
2243                               file->FileReferenceNumber,
2244                               name->FileNameLength,
2245                               (int)(name->FileNameLength / 2),
2246                               name->FileName, name->Flags);
2247                         return WIMLIB_ERR_UNSUPPORTED;
2248                 }
2249                 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2250                         num_long_names++;
2251                         total += ALIGN(sizeof(struct ntfs_dentry) +
2252                                        name->FileNameLength + sizeof(wchar_t),
2253                                        8);
2254                 }
2255                 if (name->NextNameOffset == 0)
2256                         break;
2257                 name = (const void *)name + name->NextNameOffset;
2258         }
2259
2260         if (unlikely(num_long_names == 0)) {
2261                 ERROR("Inode 0x%016"PRIx64" has no long names!",
2262                       file->FileReferenceNumber);
2263                 return WIMLIB_ERR_UNSUPPORTED;
2264         }
2265
2266         *total_length_ret = total;
2267         return 0;
2268 }
2269
2270 static bool
2271 is_valid_stream_entry(const STREAM_LAYOUT_ENTRY *stream)
2272 {
2273         return stream->StreamIdentifierLength % 2 == 0 &&
2274                 !wmemchr(stream->StreamIdentifier , L'\0',
2275                          stream->StreamIdentifierLength / 2);
2276 }
2277
2278 /* assumes that 'id' is a wide string literal */
2279 #define stream_has_identifier(stream, id)                               \
2280         ((stream)->StreamIdentifierLength == sizeof(id) - 2 &&          \
2281          !memcmp((stream)->StreamIdentifier, id, sizeof(id) - 2))
2282 /*
2283  * If the specified STREAM_LAYOUT_ENTRY represents a DATA stream as opposed to
2284  * some other type of NTFS stream such as a STANDARD_INFORMATION stream, return
2285  * true and set *stream_name_ret and *stream_name_nchars_ret to specify just the
2286  * stream name.  For example, ":foo:$DATA" would become "foo" with length 3
2287  * characters.  Otherwise return false.
2288  */
2289 static bool
2290 use_stream(const FILE_LAYOUT_ENTRY *file, const STREAM_LAYOUT_ENTRY *stream,
2291            const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
2292 {
2293         const wchar_t *stream_name;
2294         size_t stream_name_nchars;
2295
2296         if (stream->StreamIdentifierLength == 0) {
2297                 /* The unnamed data stream may be given as an empty string
2298                  * rather than as "::$DATA".  Handle it both ways.  */
2299                 stream_name = L"";
2300                 stream_name_nchars = 0;
2301         } else if (!get_data_stream_name(stream->StreamIdentifier,
2302                                          stream->StreamIdentifierLength / 2,
2303                                          &stream_name, &stream_name_nchars))
2304                 return false;
2305
2306         /* Skip the unnamed data stream for directories.  */
2307         if (stream_name_nchars == 0 &&
2308             (file->FileAttributes & FILE_ATTRIBUTE_DIRECTORY))
2309                 return false;
2310
2311         *stream_name_ret = stream_name;
2312         *stream_name_nchars_ret = stream_name_nchars;
2313         return true;
2314 }
2315
2316 /* Validate the STREAM_LAYOUT_ENTRYs of the specified file and compute the total
2317  * length in bytes of the ntfs_stream structures needed to hold the stream
2318  * information.  In addition, set *special_streams_ret to a bitmask of special
2319  * stream types that were found.  */
2320 static int
2321 validate_streams_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2322                                           size_t *total_length_ret,
2323                                           u32 *special_streams_ret)
2324 {
2325         const STREAM_LAYOUT_ENTRY *stream =
2326                 (const void *)file + file->FirstStreamOffset;
2327         size_t total = 0;
2328         u32 special_streams = 0;
2329
2330         for (;;) {
2331                 const wchar_t *name;
2332                 size_t name_nchars;
2333
2334                 if (unlikely(!is_valid_stream_entry(stream))) {
2335                         WARNING("Invalid STREAM_LAYOUT_ENTRY! "
2336                                 "FileReferenceNumber=0x%016"PRIx64", "
2337                                 "StreamIdentifierLength=%"PRIu32", "
2338                                 "StreamIdentifier=%.*ls",
2339                                 file->FileReferenceNumber,
2340                                 stream->StreamIdentifierLength,
2341                                 (int)(stream->StreamIdentifierLength / 2),
2342                                 stream->StreamIdentifier);
2343                         return WIMLIB_ERR_UNSUPPORTED;
2344                 }
2345
2346                 if (use_stream(file, stream, &name, &name_nchars)) {
2347                         total += ALIGN(sizeof(struct ntfs_stream) +
2348                                        (name_nchars + 1) * sizeof(wchar_t), 8);
2349                 } else if (stream_has_identifier(stream, L"::$OBJECT_ID")) {
2350                         special_streams |= NTFS_SPECIAL_STREAM_OBJECT_ID;
2351                 } else if (stream_has_identifier(stream, L"::$EA")) {
2352                         special_streams |= NTFS_SPECIAL_STREAM_EA;
2353                 } else if (stream_has_identifier(stream, L"::$EA_INFORMATION")) {
2354                         special_streams |= NTFS_SPECIAL_STREAM_EA_INFORMATION;
2355                 }
2356                 if (stream->NextStreamOffset == 0)
2357                         break;
2358                 stream = (const void *)stream + stream->NextStreamOffset;
2359         }
2360
2361         *total_length_ret = total;
2362         *special_streams_ret = special_streams;
2363         return 0;
2364 }
2365
2366 static void *
2367 load_name_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2368                       void *p)
2369 {
2370         const FILE_LAYOUT_NAME_ENTRY *name =
2371                 (const void *)file + file->FirstNameOffset;
2372         for (;;) {
2373                 struct ntfs_dentry *nd = p;
2374                 /* Note that a name may be just a short (DOS) name, just a long
2375                  * name, or both a short name and a long name.  If there is a
2376                  * short name, one name should also be marked as "primary" to
2377                  * indicate which long name the short name is associated with.
2378                  * Also, there should be at most one short name per inode.  */
2379                 if (name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) {
2380                         memcpy(ni->short_name,
2381                                name->FileName, name->FileNameLength);
2382                         ni->short_name[name->FileNameLength / 2] = L'\0';
2383                 }
2384                 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2385                         ni->num_aliases++;
2386                         nd->offset_from_inode = (u8 *)nd - (u8 *)ni;
2387                         nd->is_primary = ((name->Flags &
2388                                            FILE_LAYOUT_NAME_ENTRY_PRIMARY) != 0);
2389                         nd->parent_ino = name->ParentFileReferenceNumber;
2390                         memcpy(nd->name, name->FileName, name->FileNameLength);
2391                         nd->name[name->FileNameLength / 2] = L'\0';
2392                         p += ALIGN(sizeof(struct ntfs_dentry) +
2393                                    name->FileNameLength + sizeof(wchar_t), 8);
2394                 }
2395                 if (name->NextNameOffset == 0)
2396                         break;
2397                 name = (const void *)name + name->NextNameOffset;
2398         }
2399         return p;
2400 }
2401
2402 static u64
2403 load_starting_lcn(const STREAM_LAYOUT_ENTRY *stream)
2404 {
2405         const STREAM_EXTENT_ENTRY *entry;
2406
2407         if (stream->ExtentInformationOffset == 0)
2408                 return 0;
2409
2410         entry = (const void *)stream + stream->ExtentInformationOffset;
2411
2412         if (!(entry->Flags & STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS))
2413                 return 0;
2414
2415         return extract_starting_lcn(&entry->ExtentInformation.RetrievalPointers);
2416 }
2417
2418 static void *
2419 load_stream_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2420                         void *p)
2421 {
2422         const STREAM_LAYOUT_ENTRY *stream =
2423                 (const void *)file + file->FirstStreamOffset;
2424         const u32 first_stream_offset = (const u8 *)p - (const u8 *)ni;
2425         for (;;) {
2426                 struct ntfs_stream *ns = p;
2427                 const wchar_t *name;
2428                 size_t name_nchars;
2429
2430                 if (use_stream(file, stream, &name, &name_nchars)) {
2431                         ni->first_stream_offset = first_stream_offset;
2432                         ni->num_streams++;
2433                         if (name_nchars == 0)
2434                                 ni->starting_lcn = load_starting_lcn(stream);
2435                         ns->size = stream->EndOfFile;
2436                         wmemcpy(ns->name, name, name_nchars);
2437                         ns->name[name_nchars] = L'\0';
2438                         p += ALIGN(sizeof(struct ntfs_stream) +
2439                                    (name_nchars + 1) * sizeof(wchar_t), 8);
2440                 }
2441                 if (stream->NextStreamOffset == 0)
2442                         break;
2443                 stream = (const void *)stream + stream->NextStreamOffset;
2444         }
2445         return p;
2446 }
2447
2448 /* Process the information for a file given by FSCTL_QUERY_FILE_LAYOUT.  */
2449 static int
2450 load_one_file(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode_map *inode_map)
2451 {
2452         const FILE_LAYOUT_INFO_ENTRY *info =
2453                 (const void *)file + file->ExtraInfoOffset;
2454         size_t inode_size;
2455         struct ntfs_inode *ni;
2456         size_t n;
2457         int ret;
2458         void *p;
2459         u32 special_streams = 0;
2460
2461         inode_size = ALIGN(sizeof(struct ntfs_inode), 8);
2462
2463         /* The root file should have no names, and all other files should have
2464          * at least one name.  But just in case, we ignore the names of the root
2465          * file, and we ignore any non-root file with no names.  */
2466         if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber)) {
2467                 if (file->FirstNameOffset == 0)
2468                         return 0;
2469                 ret = validate_names_and_compute_total_length(file, &n);
2470                 if (ret)
2471                         return ret;
2472                 inode_size += n;
2473         }
2474
2475         if (file_has_streams(file)) {
2476                 ret = validate_streams_and_compute_total_length(file, &n,
2477                                                                 &special_streams);
2478                 if (ret)
2479                         return ret;
2480                 inode_size += n;
2481         }
2482
2483         /* To save memory, we allocate the ntfs_dentry's and ntfs_stream's in
2484          * the same memory block as their ntfs_inode.  */
2485         ni = CALLOC(1, inode_size);
2486         if (!ni)
2487                 return WIMLIB_ERR_NOMEM;
2488
2489         ni->ino = file->FileReferenceNumber;
2490         ni->attributes = info->BasicInformation.FileAttributes;
2491         ni->creation_time = info->BasicInformation.CreationTime;
2492         ni->last_write_time = info->BasicInformation.LastWriteTime;
2493         ni->last_access_time = info->BasicInformation.LastAccessTime;
2494         ni->security_id = info->SecurityId;
2495         ni->special_streams = special_streams;
2496
2497         p = FIRST_DENTRY(ni);
2498
2499         if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber))
2500                 p = load_name_information(file, ni, p);
2501
2502         if (file_has_streams(file))
2503                 p = load_stream_information(file, ni, p);
2504
2505         wimlib_assert((u8 *)p - (u8 *)ni == inode_size);
2506
2507         ntfs_inode_map_add_inode(inode_map, ni);
2508         return 0;
2509 }
2510
2511 /*
2512  * Quickly find all files on an NTFS volume by using FSCTL_QUERY_FILE_LAYOUT to
2513  * scan the MFT.  The NTFS volume is specified by the NT namespace path @path.
2514  * For each file, allocate an 'ntfs_inode' structure for each file and add it to
2515  * 'inode_map' keyed by inode number.  Include NTFS special files such as
2516  * $Bitmap (they will be removed later).
2517  */
2518 static int
2519 load_files_from_mft(const wchar_t *path, struct ntfs_inode_map *inode_map)
2520 {
2521         HANDLE h = NULL;
2522         QUERY_FILE_LAYOUT_INPUT in = (QUERY_FILE_LAYOUT_INPUT) {
2523                 .NumberOfPairs = 0,
2524                 .Flags = QUERY_FILE_LAYOUT_RESTART |
2525                          QUERY_FILE_LAYOUT_INCLUDE_NAMES |
2526                          QUERY_FILE_LAYOUT_INCLUDE_STREAMS |
2527                          QUERY_FILE_LAYOUT_INCLUDE_EXTENTS |
2528                          QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO |
2529                          QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED,
2530                 .FilterType = QUERY_FILE_LAYOUT_FILTER_TYPE_NONE,
2531         };
2532         size_t outsize = 32768;
2533         QUERY_FILE_LAYOUT_OUTPUT *out = NULL;
2534         int ret;
2535         NTSTATUS status;
2536
2537         status = winnt_open(path, wcslen(path),
2538                             FILE_READ_DATA | FILE_READ_ATTRIBUTES, &h);
2539         if (!NT_SUCCESS(status)) {
2540                 ret = -1; /* Silently try standard recursive scan instead  */
2541                 goto out;
2542         }
2543
2544         for (;;) {
2545                 /* Allocate a buffer for the output of the ioctl.  */
2546                 out = MALLOC(outsize);
2547                 if (!out) {
2548                         ret = WIMLIB_ERR_NOMEM;
2549                         goto out;
2550                 }
2551
2552                 /* Execute FSCTL_QUERY_FILE_LAYOUT until it fails.  */
2553                 while (NT_SUCCESS(status = winnt_fsctl(h,
2554                                                        FSCTL_QUERY_FILE_LAYOUT,
2555                                                        &in, sizeof(in),
2556                                                        out, outsize, NULL)))
2557                 {
2558                         const FILE_LAYOUT_ENTRY *file =
2559                                 (const void *)out + out->FirstFileOffset;
2560                         for (;;) {
2561                                 ret = load_one_file(file, inode_map);
2562                                 if (ret)
2563                                         goto out;
2564                                 if (file->NextFileOffset == 0)
2565                                         break;
2566                                 file = (const void *)file + file->NextFileOffset;
2567                         }
2568                         in.Flags &= ~QUERY_FILE_LAYOUT_RESTART;
2569                 }
2570
2571                 /* Enlarge the buffer if needed.  */
2572                 if (status != STATUS_BUFFER_TOO_SMALL)
2573                         break;
2574                 FREE(out);
2575                 outsize *= 2;
2576         }
2577
2578         /* Normally, FSCTL_QUERY_FILE_LAYOUT fails with STATUS_END_OF_FILE after
2579          * all files have been enumerated.  */
2580         if (status != STATUS_END_OF_FILE) {
2581                 if (status == STATUS_INVALID_DEVICE_REQUEST /* old OS */ ||
2582                     status == STATUS_NOT_SUPPORTED /* Samba volume, WinXP */ ||
2583                     status == STATUS_INVALID_PARAMETER /* not root directory */ )
2584                 {
2585                         /* Silently try standard recursive scan instead  */
2586                         ret = -1;
2587                 } else {
2588                         winnt_error(status,
2589                                     L"Error enumerating files on volume \"%ls\"",
2590                                     path);
2591                         /* Try standard recursive scan instead  */
2592                         ret = WIMLIB_ERR_UNSUPPORTED;
2593                 }
2594                 goto out;
2595         }
2596         ret = 0;
2597 out:
2598         FREE(out);
2599         NtClose(h);
2600         return ret;
2601 }
2602
2603 /* Build the list of child dentries for each inode in @map.  This is done by
2604  * iterating through each name of each inode and adding it to its parent's
2605  * children list.  Note that every name should have a parent, i.e. should belong
2606  * to some directory.  The root directory does not have any names.  */
2607 static int
2608 build_children_lists(struct ntfs_inode_map *map, struct ntfs_inode **root_ret)
2609 {
2610         struct ntfs_inode *ni;
2611
2612         avl_tree_for_each_in_order(ni, map->root, struct ntfs_inode, index_node)
2613         {
2614                 struct ntfs_dentry *nd;
2615                 u32 n;
2616
2617                 if (NTFS_IS_ROOT_FILE(ni->ino)) {
2618                         *root_ret = ni;
2619                         continue;
2620                 }
2621
2622                 n = ni->num_aliases;
2623                 nd = FIRST_DENTRY(ni);
2624                 for (;;) {
2625                         struct ntfs_inode *parent;
2626
2627                         parent = ntfs_inode_map_lookup(map, nd->parent_ino);
2628                         if (unlikely(!parent)) {
2629                                 ERROR("Parent inode 0x%016"PRIx64" of"
2630                                       "directory entry \"%ls\" (inode "
2631                                       "0x%016"PRIx64") was missing from the "
2632                                       "MFT listing!",
2633                                       nd->parent_ino, nd->name, ni->ino);
2634                                 return WIMLIB_ERR_UNSUPPORTED;
2635                         }
2636                         nd->next_child = parent->first_child;
2637                         parent->first_child = nd;
2638                         if (!--n)
2639                                 break;
2640                         nd = NEXT_DENTRY(nd);
2641                 }
2642         }
2643         return 0;
2644 }
2645
2646 struct security_map_node {
2647         struct avl_tree_node index_node;
2648         u32 disk_security_id;
2649         u32 wim_security_id;
2650 };
2651
2652 /* Map from disk security IDs to WIM security IDs  */
2653 struct security_map {
2654         struct avl_tree_node *root;
2655 };
2656
2657 #define SECURITY_MAP_NODE(node)                         \
2658         avl_tree_entry((node), struct security_map_node, index_node)
2659
2660 static int
2661 _avl_cmp_security_map_nodes(const struct avl_tree_node *node1,
2662                             const struct avl_tree_node *node2)
2663 {
2664         return cmp_u32(SECURITY_MAP_NODE(node1)->disk_security_id,
2665                        SECURITY_MAP_NODE(node2)->disk_security_id);
2666 }
2667
2668 static s32
2669 security_map_lookup(struct security_map *map, u32 disk_security_id)
2670 {
2671         struct security_map_node tmp;
2672         const struct avl_tree_node *res;
2673
2674         if (disk_security_id == 0)  /* No on-disk security ID; uncacheable  */
2675                 return -1;
2676
2677         tmp.disk_security_id = disk_security_id;
2678         res = avl_tree_lookup_node(map->root, &tmp.index_node,
2679                                    _avl_cmp_security_map_nodes);
2680         if (!res)
2681                 return -1;
2682         return SECURITY_MAP_NODE(res)->wim_security_id;
2683 }
2684
2685 static int
2686 security_map_insert(struct security_map *map, u32 disk_security_id,
2687                     u32 wim_security_id)
2688 {
2689         struct security_map_node *node;
2690
2691         if (disk_security_id == 0)  /* No on-disk security ID; uncacheable  */
2692                 return 0;
2693
2694         node = MALLOC(sizeof(*node));
2695         if (!node)
2696                 return WIMLIB_ERR_NOMEM;
2697
2698         node->disk_security_id = disk_security_id;
2699         node->wim_security_id = wim_security_id;
2700         avl_tree_insert(&map->root, &node->index_node,
2701                         _avl_cmp_security_map_nodes);
2702         return 0;
2703 }
2704
2705 static void
2706 security_map_destroy(struct security_map *map)
2707 {
2708         struct security_map_node *node;
2709
2710         avl_tree_for_each_in_postorder(node, map->root,
2711                                        struct security_map_node, index_node)
2712                 FREE(node);
2713 }
2714
2715 /*
2716  * Turn our temporary NTFS structures into the final WIM structures:
2717  *
2718  *      ntfs_inode      => wim_inode
2719  *      ntfs_dentry     => wim_dentry
2720  *      ntfs_stream     => wim_inode_stream
2721  *
2722  * This also handles things such as exclusions and issuing progress messages.
2723  * It's similar to winnt_build_dentry_tree(), but this is much faster because
2724  * almost all information we need is already loaded in memory in the ntfs_*
2725  * structures.  However, in some cases we still fall back to
2726  * winnt_build_dentry_tree() and/or opening the file.
2727  */
2728 static int
2729 generate_wim_structures_recursive(struct wim_dentry **root_ret,
2730                                   const wchar_t *filename, bool is_primary_name,
2731                                   struct ntfs_inode *ni,
2732                                   struct winnt_scan_ctx *ctx,
2733                                   struct ntfs_inode_map *inode_map,
2734                                   struct security_map *security_map)
2735 {
2736         int ret = 0;
2737         struct wim_dentry *root = NULL;
2738         struct wim_inode *inode = NULL;
2739         const struct ntfs_stream *ns;
2740
2741         /* Completely ignore NTFS special files.  */
2742         if (NTFS_IS_SPECIAL_FILE(ni->ino))
2743                 goto out;
2744
2745         /* Fall back to the standard scan for unhandled cases.  Reparse points,
2746          * in particular, can't be properly handled here because a commonly used
2747          * filter driver (WOF) hides reparse points from regular filesystem APIs
2748          * but not from FSCTL_QUERY_FILE_LAYOUT.  */
2749         if (ni->attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
2750                               FILE_ATTRIBUTE_ENCRYPTED) ||
2751             ni->special_streams != 0)
2752         {
2753                 ret = winnt_build_dentry_tree(&root, NULL,
2754                                               ctx->params->cur_path,
2755                                               ctx->params->cur_path_nchars,
2756                                               filename, ctx, false);
2757                 if (ret) /* Error? */
2758                         goto out;
2759                 if (!root) /* Excluded? */
2760                         goto out_progress;
2761                 inode = root->d_inode;
2762                 goto process_children;
2763         }
2764
2765         /* Test for exclusion based on path.  */
2766         ret = try_exclude(ctx->params);
2767         if (unlikely(ret < 0)) /* Excluded? */
2768                 goto out_progress;
2769         if (unlikely(ret > 0)) /* Error? */
2770                 goto out;
2771
2772         /* Create the WIM dentry and possibly a new WIM inode  */
2773         ret = inode_table_new_dentry(ctx->params->inode_table, filename,
2774                                      ni->ino, ctx->params->capture_root_dev,
2775                                      false, &root);
2776         if (ret)
2777                 goto out;
2778
2779         inode = root->d_inode;
2780
2781         /* Set the short name if needed.  */
2782         if (is_primary_name && *ni->short_name) {
2783                 size_t nbytes = wcslen(ni->short_name) * sizeof(wchar_t);
2784                 root->d_short_name = memdup(ni->short_name,
2785                                             nbytes + sizeof(wchar_t));
2786                 if (!root->d_short_name) {
2787                         ret = WIMLIB_ERR_NOMEM;
2788                         goto out;
2789                 }
2790                 root->d_short_name_nbytes = nbytes;
2791         }
2792
2793         if (inode->i_nlink > 1) { /* Already seen this inode?  */
2794                 ret = 0;
2795                 goto out_progress;
2796         }
2797
2798         /* The file attributes and timestamps were cached from the MFT.  */
2799         inode->i_attributes = ni->attributes;
2800         inode->i_creation_time = ni->creation_time;
2801         inode->i_last_write_time = ni->last_write_time;
2802         inode->i_last_access_time = ni->last_access_time;
2803
2804         /* Set the security descriptor if needed.  */
2805         if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)) {
2806                 /* Look up the WIM security ID that corresponds to the on-disk
2807                  * security ID.  */
2808                 s32 wim_security_id =
2809                         security_map_lookup(security_map, ni->security_id);
2810                 if (likely(wim_security_id >= 0)) {
2811                         /* The mapping for this security ID is already cached.*/
2812                         inode->i_security_id = wim_security_id;
2813                 } else {
2814                         HANDLE h;
2815                         NTSTATUS status;
2816
2817                         /* Create a mapping for this security ID and insert it
2818                          * into the security map.  */
2819
2820                         status = winnt_open(ctx->params->cur_path,
2821                                             ctx->params->cur_path_nchars,
2822                                             READ_CONTROL |
2823                                                 ACCESS_SYSTEM_SECURITY, &h);
2824                         if (!NT_SUCCESS(status)) {
2825                                 winnt_error(status, L"Can't open \"%ls\" to "
2826                                             "read security descriptor",
2827                                             printable_path(ctx));
2828                                 ret = WIMLIB_ERR_OPEN;
2829                                 goto out;
2830                         }
2831                         ret = winnt_load_security_descriptor(h, inode, ctx);
2832                         NtClose(h);
2833                         if (ret)
2834                                 goto out;
2835
2836                         ret = security_map_insert(security_map, ni->security_id,
2837                                                   inode->i_security_id);
2838                         if (ret)
2839                                 goto out;
2840                 }
2841         }
2842
2843         /* Add data streams based on the cached information from the MFT.  */
2844         ns = FIRST_STREAM(ni);
2845         for (u32 i = 0; i < ni->num_streams; i++) {
2846                 struct windows_file *windows_file;
2847
2848                 /* Reference the stream by path if it's a named data stream, or
2849                  * if the volume doesn't support "open by file ID", or if the
2850                  * application hasn't explicitly opted in to "open by file ID".
2851                  * Otherwise, only save the inode number (file ID).  */
2852                 if (*ns->name ||
2853                     !(ctx->vol_flags & FILE_SUPPORTS_OPEN_BY_FILE_ID) ||
2854                     !(ctx->params->add_flags & WIMLIB_ADD_FLAG_FILE_PATHS_UNNEEDED))
2855                 {
2856                         windows_file = alloc_windows_file(ctx->params->cur_path,
2857                                                           ctx->params->cur_path_nchars,
2858                                                           ns->name,
2859                                                           wcslen(ns->name),
2860                                                           ctx->snapshot,
2861                                                           false);
2862                 } else {
2863                         windows_file = alloc_windows_file_for_file_id(ni->ino,
2864                                                                       ctx->params->cur_path,
2865                                                                       ctx->params->root_path_nchars,
2866                                                                       ctx->snapshot);
2867                 }
2868
2869                 ret = add_stream(inode, windows_file, ns->size,
2870                                  STREAM_TYPE_DATA, ns->name,
2871                                  ctx->params->unhashed_blobs);
2872                 if (ret)
2873                         goto out;
2874                 ns = NEXT_STREAM(ns);
2875         }
2876
2877         set_sort_key(inode, ni->starting_lcn);
2878
2879         /* If processing a directory, then recurse to its children.  In this
2880          * version there is no need to go to disk, as we already have the list
2881          * of children cached from the MFT.  */
2882 process_children:
2883         if (inode_is_directory(inode)) {
2884                 const struct ntfs_dentry *nd = ni->first_child;
2885
2886                 while (nd != NULL) {
2887                         size_t orig_path_nchars;
2888                         struct wim_dentry *child;
2889                         const struct ntfs_dentry *next = nd->next_child;
2890
2891                         ret = WIMLIB_ERR_NOMEM;
2892                         if (!pathbuf_append_name(ctx->params, nd->name,
2893                                                  wcslen(nd->name),
2894                                                  &orig_path_nchars))
2895                                 goto out;
2896
2897                         ret = generate_wim_structures_recursive(
2898                                         &child,
2899                                         nd->name,
2900                                         nd->is_primary,
2901                                         (void *)nd - nd->offset_from_inode,
2902                                         ctx,
2903                                         inode_map,
2904                                         security_map);
2905
2906                         pathbuf_truncate(ctx->params, orig_path_nchars);
2907
2908                         if (ret)
2909                                 goto out;
2910
2911                         attach_scanned_tree(root, child, ctx->params->blob_table);
2912                         nd = next;
2913                 }
2914         }
2915
2916 out_progress:
2917         if (likely(root))
2918                 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_OK, inode);
2919         else
2920                 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
2921 out:
2922         if (--ni->num_aliases == 0) {
2923                 /* Memory usage optimization: when we don't need the ntfs_inode
2924                  * (and its names and streams) anymore, free it.  */
2925                 ntfs_inode_map_remove(inode_map, ni);
2926         }
2927         if (unlikely(ret)) {
2928                 free_dentry_tree(root, ctx->params->blob_table);
2929                 root = NULL;
2930         }
2931         *root_ret = root;
2932         return ret;
2933 }
2934
2935 static int
2936 winnt_build_dentry_tree_fast(struct wim_dentry **root_ret,
2937                              struct winnt_scan_ctx *ctx)
2938 {
2939         struct ntfs_inode_map inode_map = { .root = NULL };
2940         struct security_map security_map = { .root = NULL };
2941         struct ntfs_inode *root = NULL;
2942         wchar_t *path = ctx->params->cur_path;
2943         size_t path_nchars = ctx->params->cur_path_nchars;
2944         bool adjust_path;
2945         int ret;
2946
2947         adjust_path = (path[path_nchars - 1] == L'\\');
2948         if (adjust_path)
2949                 path[path_nchars - 1] = L'\0';
2950
2951         ret = load_files_from_mft(path, &inode_map);
2952
2953         if (adjust_path)
2954                 path[path_nchars - 1] = L'\\';
2955
2956         if (ret)
2957                 goto out;
2958
2959         ret = build_children_lists(&inode_map, &root);
2960         if (ret)
2961                 goto out;
2962
2963         if (!root) {
2964                 ERROR("The MFT listing for volume \"%ls\" did not include a "
2965                       "root directory!", path);
2966                 ret = WIMLIB_ERR_UNSUPPORTED;
2967                 goto out;
2968         }
2969
2970         root->num_aliases = 1;
2971
2972         ret = generate_wim_structures_recursive(root_ret, L"", false, root, ctx,
2973                                                 &inode_map, &security_map);
2974 out:
2975         ntfs_inode_map_destroy(&inode_map);
2976         security_map_destroy(&security_map);
2977         return ret;
2978 }
2979
2980 #endif /* ENABLE_FAST_MFT_SCAN */
2981
2982 /*----------------------------------------------------------------------------*
2983  *                 Entry point for directory tree scans on Windows            *
2984  *----------------------------------------------------------------------------*/
2985
2986 int
2987 win32_build_dentry_tree(struct wim_dentry **root_ret,
2988                         const wchar_t *root_disk_path,
2989                         struct scan_params *params)
2990 {
2991         struct winnt_scan_ctx ctx = { .params = params };
2992         UNICODE_STRING ntpath;
2993         HANDLE h = NULL;
2994         NTSTATUS status;
2995         int ret;
2996
2997         if (params->add_flags & WIMLIB_ADD_FLAG_SNAPSHOT)
2998                 ret = vss_create_snapshot(root_disk_path, &ntpath, &ctx.snapshot);
2999         else
3000                 ret = win32_path_to_nt_path(root_disk_path, &ntpath);
3001
3002         if (ret)
3003                 goto out;
3004
3005         if (ntpath.Length < 4 * sizeof(wchar_t) ||
3006             wmemcmp(ntpath.Buffer, L"\\??\\", 4))
3007         {
3008                 ERROR("\"%ls\": unrecognized path format", root_disk_path);
3009                 ret = WIMLIB_ERR_INVALID_PARAM;
3010         } else {
3011                 ret = pathbuf_init(params, ntpath.Buffer);
3012         }
3013         HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
3014         if (ret)
3015                 goto out;
3016
3017         status = winnt_open(params->cur_path, params->cur_path_nchars,
3018                             FILE_READ_ATTRIBUTES, &h);
3019         if (!NT_SUCCESS(status)) {
3020                 winnt_error(status, L"Can't open \"%ls\"", root_disk_path);
3021                 if (status == STATUS_FVE_LOCKED_VOLUME)
3022                         ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
3023                 else
3024                         ret = WIMLIB_ERR_OPEN;
3025                 goto out;
3026         }
3027
3028         get_volume_information(h, &ctx);
3029
3030         NtClose(h);
3031
3032 #ifdef ENABLE_FAST_MFT_SCAN
3033         if (ctx.is_ntfs && !_wgetenv(L"WIMLIB_DISABLE_QUERY_FILE_LAYOUT")) {
3034                 ret = winnt_build_dentry_tree_fast(root_ret, &ctx);
3035                 if (ret >= 0 && ret != WIMLIB_ERR_UNSUPPORTED)
3036                         goto out;
3037                 if (ret >= 0) {
3038                         WARNING("A problem occurred during the fast MFT scan.\n"
3039                                 "          Falling back to the standard "
3040                                 "recursive directory tree scan.");
3041                 }
3042         }
3043 #endif
3044         ret = winnt_build_dentry_tree(root_ret, NULL, params->cur_path,
3045                                       params->cur_path_nchars, L"", &ctx, true);
3046 out:
3047         vss_put_snapshot(ctx.snapshot);
3048         if (ret == 0)
3049                 winnt_do_scan_warnings(root_disk_path, &ctx);
3050         return ret;
3051 }
3052
3053 #endif /* __WIN32__ */