]> wimlib.net Git - wimlib/blob - src/win32_capture.c
Prevent huge memory allocations from fuzzed header fields
[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-2021 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(), since FindFirstStream() opens its own handle to the
1325  * file or directory and apparently does so without specifying
1326  * FILE_FLAG_BACKUP_SEMANTICS.  This causing access denied errors on certain
1327  * files, even when running as the Administrator.
1328  */
1329 static noinline_for_stack int
1330 winnt_scan_data_streams(HANDLE h, struct wim_inode *inode, u64 file_size,
1331                         struct winnt_scan_ctx *ctx)
1332 {
1333         int ret;
1334         u8 _buf[4096] _aligned_attribute(8);
1335         u8 *buf;
1336         size_t bufsize;
1337         IO_STATUS_BLOCK iosb;
1338         NTSTATUS status;
1339         FILE_STREAM_INFORMATION *info;
1340
1341         buf = _buf;
1342         bufsize = sizeof(_buf);
1343
1344         if (!(ctx->vol_flags & FILE_NAMED_STREAMS))
1345                 goto unnamed_only;
1346
1347         /* Get a buffer containing the stream information.  */
1348         while (!NT_SUCCESS(status = NtQueryInformationFile(h,
1349                                                            &iosb,
1350                                                            buf,
1351                                                            bufsize,
1352                                                            FileStreamInformation)))
1353         {
1354
1355                 switch (status) {
1356                 case STATUS_BUFFER_OVERFLOW:
1357                         {
1358                                 u8 *newbuf;
1359
1360                                 bufsize *= 2;
1361                                 if (buf == _buf)
1362                                         newbuf = MALLOC(bufsize);
1363                                 else
1364                                         newbuf = REALLOC(buf, bufsize);
1365                                 if (!newbuf) {
1366                                         ret = WIMLIB_ERR_NOMEM;
1367                                         goto out_free_buf;
1368                                 }
1369                                 buf = newbuf;
1370                         }
1371                         break;
1372                 case STATUS_NOT_IMPLEMENTED:
1373                 case STATUS_NOT_SUPPORTED:
1374                 case STATUS_INVALID_INFO_CLASS:
1375                         goto unnamed_only;
1376                 default:
1377                         winnt_error(status,
1378                                     L"\"%ls\": Failed to query stream information",
1379                                     printable_path(ctx));
1380                         ret = WIMLIB_ERR_READ;
1381                         goto out_free_buf;
1382                 }
1383         }
1384
1385         if (iosb.Information == 0) {
1386                 /* No stream information.  */
1387                 ret = 0;
1388                 goto out_free_buf;
1389         }
1390
1391         /* Parse one or more stream information structures.  */
1392         info = (FILE_STREAM_INFORMATION *)buf;
1393         for (;;) {
1394                 /* Load the stream information.  */
1395                 ret = winnt_scan_data_stream(info->StreamName,
1396                                              info->StreamNameLength / 2,
1397                                              info->StreamSize.QuadPart,
1398                                              inode, ctx);
1399                 if (ret)
1400                         goto out_free_buf;
1401
1402                 if (info->NextEntryOffset == 0) {
1403                         /* No more stream information.  */
1404                         break;
1405                 }
1406                 /* Advance to next stream information.  */
1407                 info = (FILE_STREAM_INFORMATION *)
1408                                 ((u8 *)info + info->NextEntryOffset);
1409         }
1410         ret = 0;
1411         goto out_free_buf;
1412
1413 unnamed_only:
1414         /* The volume does not support named streams.  Only capture the unnamed
1415          * data stream.  */
1416         if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1417                                    FILE_ATTRIBUTE_REPARSE_POINT))
1418         {
1419                 ret = 0;
1420                 goto out_free_buf;
1421         }
1422
1423         {
1424                 wchar_t stream_name[] = L"::$DATA";
1425                 ret = winnt_scan_data_stream(stream_name, 7, file_size,
1426                                              inode, ctx);
1427         }
1428 out_free_buf:
1429         /* Free buffer if allocated on heap.  */
1430         if (unlikely(buf != _buf))
1431                 FREE(buf);
1432         return ret;
1433 }
1434
1435 static u64
1436 extract_starting_lcn(const RETRIEVAL_POINTERS_BUFFER *extents)
1437 {
1438         if (extents->ExtentCount < 1)
1439                 return 0;
1440
1441         return extents->Extents[0].Lcn.QuadPart;
1442 }
1443
1444 static noinline_for_stack u64
1445 get_sort_key(HANDLE h)
1446 {
1447         STARTING_VCN_INPUT_BUFFER in = { .StartingVcn.QuadPart = 0 };
1448         RETRIEVAL_POINTERS_BUFFER out;
1449
1450         if (!NT_SUCCESS(winnt_fsctl(h, FSCTL_GET_RETRIEVAL_POINTERS,
1451                                     &in, sizeof(in), &out, sizeof(out), NULL)))
1452                 return 0;
1453
1454         return extract_starting_lcn(&out);
1455 }
1456
1457 static void
1458 set_sort_key(struct wim_inode *inode, u64 sort_key)
1459 {
1460         for (unsigned i = 0; i < inode->i_num_streams; i++) {
1461                 struct wim_inode_stream *strm = &inode->i_streams[i];
1462                 struct blob_descriptor *blob = stream_blob_resolved(strm);
1463                 if (blob && blob->blob_location == BLOB_IN_WINDOWS_FILE)
1464                         blob->windows_file->sort_key = sort_key;
1465         }
1466 }
1467
1468 static inline bool
1469 should_try_to_use_wimboot_hash(const struct wim_inode *inode,
1470                                const struct winnt_scan_ctx *ctx)
1471 {
1472         /* Directories and encrypted files aren't valid for external backing. */
1473         if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1474                                    FILE_ATTRIBUTE_ENCRYPTED))
1475                 return false;
1476
1477         /* If the file is a reparse point, then try the hash fixup if it's a WOF
1478          * reparse point and we're in WIMBOOT mode.  Otherwise, try the hash
1479          * fixup if WOF may be attached. */
1480         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1481                 return (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_WOF) &&
1482                         (ctx->params->add_flags & WIMLIB_ADD_FLAG_WIMBOOT);
1483         return !ctx->wof_not_attached;
1484 }
1485
1486 /*
1487  * This function implements an optimization for capturing files from a
1488  * filesystem with a backing WIM(s).  If a file is WIM-backed, then we can
1489  * retrieve the SHA-1 message digest of its original contents from its reparse
1490  * point.  This may eliminate the need to read the file's data and/or allow the
1491  * file's data to be immediately deduplicated with existing data in the WIM.
1492  *
1493  * If WOF is attached, then this function is merely an optimization, but
1494  * potentially a very effective one.  If WOF is detached, then this function
1495  * really causes WIM-backed files to be, effectively, automatically
1496  * "dereferenced" when possible; the unnamed data stream is updated to reference
1497  * the original contents and the reparse point is removed.
1498  *
1499  * This function returns 0 if the fixup succeeded or was intentionally not
1500  * executed.  Otherwise it returns an error code.
1501  */
1502 static noinline_for_stack int
1503 try_to_use_wimboot_hash(HANDLE h, struct wim_inode *inode,
1504                         struct winnt_scan_ctx *ctx)
1505 {
1506         struct blob_table *blob_table = ctx->params->blob_table;
1507         struct wim_inode_stream *reparse_strm = NULL;
1508         struct wim_inode_stream *strm;
1509         struct blob_descriptor *blob;
1510         u8 hash[SHA1_HASH_SIZE];
1511         int ret;
1512
1513         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1514                 struct reparse_buffer_disk rpbuf;
1515                 struct {
1516                         WOF_EXTERNAL_INFO wof_info;
1517                         struct wim_provider_rpdata wim_info;
1518                 } *rpdata = (void *)rpbuf.rpdata;
1519                 struct blob_descriptor *reparse_blob;
1520
1521                 /* The file has a WOF reparse point, so WOF must be detached.
1522                  * We can read the reparse point directly.  */
1523                 ctx->wof_not_attached = true;
1524                 reparse_strm = inode_get_unnamed_stream(inode, STREAM_TYPE_REPARSE_POINT);
1525                 reparse_blob = stream_blob_resolved(reparse_strm);
1526
1527                 if (!reparse_blob || reparse_blob->size < sizeof(*rpdata))
1528                         return 0;  /* Not a WIM-backed file  */
1529
1530                 ret = read_blob_into_buf(reparse_blob, rpdata);
1531                 if (ret)
1532                         return ret;
1533
1534                 if (rpdata->wof_info.Version != WOF_CURRENT_VERSION ||
1535                     rpdata->wof_info.Provider != WOF_PROVIDER_WIM ||
1536                     rpdata->wim_info.version != 2)
1537                         return 0;  /* Not a WIM-backed file  */
1538
1539                 /* Okay, this is a WIM backed file.  Get its SHA-1 hash.  */
1540                 copy_hash(hash, rpdata->wim_info.unnamed_data_stream_hash);
1541         } else {
1542                 struct {
1543                         WOF_EXTERNAL_INFO wof_info;
1544                         WIM_PROVIDER_EXTERNAL_INFO wim_info;
1545                 } out;
1546                 NTSTATUS status;
1547
1548                 /* WOF may be attached.  Try reading this file's external
1549                  * backing info.  */
1550                 status = winnt_fsctl(h, FSCTL_GET_EXTERNAL_BACKING,
1551                                      NULL, 0, &out, sizeof(out), NULL);
1552
1553                 /* Is WOF not attached?  */
1554                 if (status == STATUS_INVALID_DEVICE_REQUEST ||
1555                     status == STATUS_NOT_SUPPORTED) {
1556                         ctx->wof_not_attached = true;
1557                         return 0;
1558                 }
1559
1560                 /* Is this file not externally backed?  */
1561                 if (status == STATUS_OBJECT_NOT_EXTERNALLY_BACKED)
1562                         return 0;
1563
1564                 /* Does this file have an unknown type of external backing that
1565                  * needed a larger information buffer?  */
1566                 if (status == STATUS_BUFFER_TOO_SMALL)
1567                         return 0;
1568
1569                 /* Was there some other failure?  */
1570                 if (status != STATUS_SUCCESS) {
1571                         winnt_error(status,
1572                                     L"\"%ls\": FSCTL_GET_EXTERNAL_BACKING failed",
1573                                     printable_path(ctx));
1574                         return WIMLIB_ERR_STAT;
1575                 }
1576
1577                 /* Is this file backed by a WIM?  */
1578                 if (out.wof_info.Version != WOF_CURRENT_VERSION ||
1579                     out.wof_info.Provider != WOF_PROVIDER_WIM ||
1580                     out.wim_info.Version != WIM_PROVIDER_CURRENT_VERSION)
1581                         return 0;
1582
1583                 /* Okay, this is a WIM backed file.  Get its SHA-1 hash.  */
1584                 copy_hash(hash, out.wim_info.ResourceHash);
1585         }
1586
1587         /* If the file's unnamed data stream is nonempty, then fill in its hash
1588          * and deduplicate it if possible.
1589          *
1590          * With WOF detached, we require that the blob *must* de-duplicable for
1591          * any action can be taken, since without WOF we can't fall back to
1592          * getting the "dereferenced" data by reading the stream (the real
1593          * stream is sparse and contains all zeroes).  */
1594         strm = inode_get_unnamed_data_stream(inode);
1595         if (strm && (blob = stream_blob_resolved(strm))) {
1596                 struct blob_descriptor **back_ptr;
1597
1598                 if (reparse_strm && !lookup_blob(blob_table, hash))
1599                         return 0;
1600                 back_ptr = retrieve_pointer_to_unhashed_blob(blob);
1601                 copy_hash(blob->hash, hash);
1602                 if (after_blob_hashed(blob, back_ptr, blob_table,
1603                                       inode) != blob)
1604                         free_blob_descriptor(blob);
1605         }
1606
1607         /* Remove the reparse point, if present.  */
1608         if (reparse_strm) {
1609                 inode_remove_stream(inode, reparse_strm, blob_table);
1610                 inode->i_attributes &= ~(FILE_ATTRIBUTE_REPARSE_POINT |
1611                                          FILE_ATTRIBUTE_SPARSE_FILE);
1612                 if (inode->i_attributes == 0)
1613                         inode->i_attributes = FILE_ATTRIBUTE_NORMAL;
1614         }
1615
1616         return 0;
1617 }
1618
1619 struct file_info {
1620         u32 attributes;
1621         u32 num_links;
1622         u64 creation_time;
1623         u64 last_write_time;
1624         u64 last_access_time;
1625         u64 ino;
1626         u64 end_of_file;
1627         u32 ea_size;
1628 };
1629
1630 static noinline_for_stack NTSTATUS
1631 get_file_info(HANDLE h, struct file_info *info)
1632 {
1633         IO_STATUS_BLOCK iosb;
1634         NTSTATUS status;
1635         FILE_ALL_INFORMATION all_info;
1636
1637         status = NtQueryInformationFile(h, &iosb, &all_info, sizeof(all_info),
1638                                         FileAllInformation);
1639
1640         if (unlikely(!NT_SUCCESS(status) && status != STATUS_BUFFER_OVERFLOW))
1641                 return status;
1642
1643         info->attributes = all_info.BasicInformation.FileAttributes;
1644         info->num_links = all_info.StandardInformation.NumberOfLinks;
1645         info->creation_time = all_info.BasicInformation.CreationTime.QuadPart;
1646         info->last_write_time = all_info.BasicInformation.LastWriteTime.QuadPart;
1647         info->last_access_time = all_info.BasicInformation.LastAccessTime.QuadPart;
1648         info->ino = all_info.InternalInformation.IndexNumber.QuadPart;
1649         info->end_of_file = all_info.StandardInformation.EndOfFile.QuadPart;
1650         info->ea_size = all_info.EaInformation.EaSize;
1651         return STATUS_SUCCESS;
1652 }
1653
1654 static void
1655 get_volume_information(HANDLE h, struct winnt_scan_ctx *ctx)
1656 {
1657         u8 _attr_info[sizeof(FILE_FS_ATTRIBUTE_INFORMATION) + 128] _aligned_attribute(8);
1658         FILE_FS_ATTRIBUTE_INFORMATION *attr_info = (void *)_attr_info;
1659         FILE_FS_VOLUME_INFORMATION vol_info;
1660         struct file_info file_info;
1661         IO_STATUS_BLOCK iosb;
1662         NTSTATUS status;
1663
1664         /* Get volume flags  */
1665         status = NtQueryVolumeInformationFile(h, &iosb, attr_info,
1666                                               sizeof(_attr_info),
1667                                               FileFsAttributeInformation);
1668         if (NT_SUCCESS(status)) {
1669                 ctx->vol_flags = attr_info->FileSystemAttributes;
1670                 ctx->is_ntfs = (attr_info->FileSystemNameLength == 4 * sizeof(wchar_t)) &&
1671                                 !wmemcmp(attr_info->FileSystemName, L"NTFS", 4);
1672         } else {
1673                 winnt_warning(status, L"\"%ls\": Can't get volume attributes",
1674                               printable_path(ctx));
1675         }
1676
1677         /* Get volume ID.  */
1678         status = NtQueryVolumeInformationFile(h, &iosb, &vol_info,
1679                                               sizeof(vol_info),
1680                                               FileFsVolumeInformation);
1681         if ((NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW) &&
1682             (iosb.Information >= offsetof(FILE_FS_VOLUME_INFORMATION,
1683                                           VolumeSerialNumber) +
1684              sizeof(vol_info.VolumeSerialNumber)))
1685         {
1686                 ctx->params->capture_root_dev = vol_info.VolumeSerialNumber;
1687         } else {
1688                 winnt_warning(status, L"\"%ls\": Can't get volume ID",
1689                               printable_path(ctx));
1690         }
1691
1692         /* Get inode number.  */
1693         status = get_file_info(h, &file_info);
1694         if (NT_SUCCESS(status)) {
1695                 ctx->params->capture_root_ino = file_info.ino;
1696         } else {
1697                 winnt_warning(status, L"\"%ls\": Can't get file information",
1698                               printable_path(ctx));
1699         }
1700 }
1701
1702 static int
1703 winnt_build_dentry_tree(struct wim_dentry **root_ret,
1704                         HANDLE cur_dir,
1705                         const wchar_t *relative_path,
1706                         size_t relative_path_nchars,
1707                         const wchar_t *filename,
1708                         struct winnt_scan_ctx *ctx,
1709                         bool recursive)
1710 {
1711         struct wim_dentry *root = NULL;
1712         struct wim_inode *inode = NULL;
1713         HANDLE h = NULL;
1714         int ret;
1715         NTSTATUS status;
1716         struct file_info file_info;
1717         u64 sort_key;
1718
1719         ret = try_exclude(ctx->params);
1720         if (unlikely(ret < 0)) /* Excluded? */
1721                 goto out_progress;
1722         if (unlikely(ret > 0)) /* Error? */
1723                 goto out;
1724
1725         /* Open the file with permission to read metadata.  Although we will
1726          * later need a handle with FILE_LIST_DIRECTORY permission (or,
1727          * equivalently, FILE_READ_DATA; they're the same numeric value) if the
1728          * file is a directory, it can significantly slow things down to request
1729          * this permission on all nondirectories.  Perhaps it causes Windows to
1730          * start prefetching the file contents...  */
1731         status = winnt_openat(cur_dir, relative_path, relative_path_nchars,
1732                               FILE_READ_ATTRIBUTES | FILE_READ_EA |
1733                                 READ_CONTROL | ACCESS_SYSTEM_SECURITY,
1734                               &h);
1735         if (unlikely(!NT_SUCCESS(status))) {
1736                 if (status == STATUS_DELETE_PENDING) {
1737                         WARNING("\"%ls\": Deletion pending; skipping file",
1738                                 printable_path(ctx));
1739                         ret = 0;
1740                         goto out;
1741                 }
1742                 if (status == STATUS_SHARING_VIOLATION) {
1743                         ERROR("Can't open \"%ls\":\n"
1744                               "        File is in use by another process! "
1745                               "Consider using snapshot (VSS) mode.",
1746                               printable_path(ctx));
1747                         ret = WIMLIB_ERR_OPEN;
1748                         goto out;
1749                 }
1750                 winnt_error(status, L"\"%ls\": Can't open file",
1751                             printable_path(ctx));
1752                 if (status == STATUS_FVE_LOCKED_VOLUME)
1753                         ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1754                 else
1755                         ret = WIMLIB_ERR_OPEN;
1756                 goto out;
1757         }
1758
1759         /* Get information about the file.  */
1760         status = get_file_info(h, &file_info);
1761         if (!NT_SUCCESS(status)) {
1762                 winnt_error(status, L"\"%ls\": Can't get file information",
1763                             printable_path(ctx));
1764                 ret = WIMLIB_ERR_STAT;
1765                 goto out;
1766         }
1767
1768         /* Create a WIM dentry with an associated inode, which may be shared.
1769          *
1770          * However, we need to explicitly check for directories and files with
1771          * only 1 link and refuse to hard link them.  This is because Windows
1772          * has a bug where it can return duplicate File IDs for files and
1773          * directories on the FAT filesystem.
1774          *
1775          * Since we don't follow mount points on Windows, we don't need to query
1776          * the volume ID per-file.  Just once, for the root, is enough.  But we
1777          * can't simply pass 0, because then there could be inode collisions
1778          * among multiple calls to win32_build_dentry_tree() that are scanning
1779          * files on different volumes.  */
1780         ret = inode_table_new_dentry(ctx->params->inode_table,
1781                                      filename,
1782                                      file_info.ino,
1783                                      ctx->params->capture_root_dev,
1784                                      (file_info.num_links <= 1),
1785                                      &root);
1786         if (ret)
1787                 goto out;
1788
1789         /* Get the short (DOS) name of the file.  */
1790         status = winnt_get_short_name(h, root);
1791
1792         /* If we can't read the short filename for any reason other than
1793          * out-of-memory, just ignore the error and assume the file has no short
1794          * name.  This shouldn't be an issue, since the short names are
1795          * essentially obsolete anyway.  */
1796         if (unlikely(status == STATUS_NO_MEMORY)) {
1797                 ret = WIMLIB_ERR_NOMEM;
1798                 goto out;
1799         }
1800
1801         inode = root->d_inode;
1802
1803         if (inode->i_nlink > 1) {
1804                 /* Shared inode (hard link); skip reading per-inode information.
1805                  */
1806                 goto out_progress;
1807         }
1808
1809         inode->i_attributes = file_info.attributes;
1810         inode->i_creation_time = file_info.creation_time;
1811         inode->i_last_write_time = file_info.last_write_time;
1812         inode->i_last_access_time = file_info.last_access_time;
1813
1814         /* Get the file's security descriptor, unless we are capturing in
1815          * NO_ACLS mode or the volume does not support security descriptors.  */
1816         if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1817             && (ctx->vol_flags & FILE_PERSISTENT_ACLS))
1818         {
1819                 ret = winnt_load_security_descriptor(h, inode, ctx);
1820                 if (ret)
1821                         goto out;
1822         }
1823
1824         /* Get the file's object ID.  */
1825         ret = winnt_load_object_id(h, inode, ctx);
1826         if (ret)
1827                 goto out;
1828
1829         /* Get the file's extended attributes.  */
1830         if (unlikely(file_info.ea_size != 0)) {
1831                 ret = winnt_load_xattrs(h, inode, ctx, file_info.ea_size);
1832                 if (ret)
1833                         goto out;
1834         }
1835
1836         /* If this is a reparse point, load the reparse data.  */
1837         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1838                 ret = winnt_load_reparse_data(h, inode, ctx);
1839                 if (ret)
1840                         goto out;
1841         }
1842
1843         sort_key = get_sort_key(h);
1844
1845         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1846                 /* Load information about the raw encrypted data.  This is
1847                  * needed for any directory or non-directory that has
1848                  * FILE_ATTRIBUTE_ENCRYPTED set.
1849                  *
1850                  * Note: since OpenEncryptedFileRaw() fails with
1851                  * ERROR_SHARING_VIOLATION if there are any open handles to the
1852                  * file, we have to close the file and re-open it later if
1853                  * needed.  */
1854                 NtClose(h);
1855                 h = NULL;
1856                 ret = winnt_scan_efsrpc_raw_data(inode, ctx);
1857                 if (ret)
1858                         goto out;
1859         } else {
1860                 /*
1861                  * Load information about data streams (unnamed and named).
1862                  *
1863                  * Skip this step for encrypted files, since the data from
1864                  * ReadEncryptedFileRaw() already contains all data streams (and
1865                  * they do in fact all get restored by WriteEncryptedFileRaw().)
1866                  *
1867                  * Note: WIMGAPI (as of Windows 8.1) gets wrong and stores both
1868                  * the EFSRPC data and the named data stream(s)...!
1869                  */
1870                 ret = winnt_scan_data_streams(h,
1871                                               inode,
1872                                               file_info.end_of_file,
1873                                               ctx);
1874                 if (ret)
1875                         goto out;
1876         }
1877
1878         if (unlikely(should_try_to_use_wimboot_hash(inode, ctx))) {
1879                 ret = try_to_use_wimboot_hash(h, inode, ctx);
1880                 if (ret)
1881                         goto out;
1882         }
1883
1884         set_sort_key(inode, sort_key);
1885
1886         if (inode_is_directory(inode) && recursive) {
1887
1888                 /* Directory: recurse to children.  */
1889
1890                 /* Re-open the directory with FILE_LIST_DIRECTORY access.  */
1891                 if (h) {
1892                         NtClose(h);
1893                         h = NULL;
1894                 }
1895                 status = winnt_openat(cur_dir, relative_path,
1896                                       relative_path_nchars, FILE_LIST_DIRECTORY,
1897                                       &h);
1898                 if (!NT_SUCCESS(status)) {
1899                         winnt_error(status, L"\"%ls\": Can't open directory",
1900                                     printable_path(ctx));
1901                         ret = WIMLIB_ERR_OPEN;
1902                         goto out;
1903                 }
1904                 ret = winnt_recurse_directory(h, root, ctx);
1905                 if (ret)
1906                         goto out;
1907         }
1908
1909 out_progress:
1910         ret = 0;
1911         if (recursive) { /* if !recursive, caller handles progress */
1912                 if (likely(root))
1913                         ret = do_scan_progress(ctx->params,
1914                                                WIMLIB_SCAN_DENTRY_OK, inode);
1915                 else
1916                         ret = do_scan_progress(ctx->params,
1917                                                WIMLIB_SCAN_DENTRY_EXCLUDED,
1918                                                NULL);
1919         }
1920 out:
1921         if (likely(h))
1922                 NtClose(h);
1923         if (unlikely(ret)) {
1924                 free_dentry_tree(root, ctx->params->blob_table);
1925                 root = NULL;
1926                 ret = report_scan_error(ctx->params, ret);
1927         }
1928         *root_ret = root;
1929         return ret;
1930 }
1931
1932 static void
1933 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_ctx *ctx)
1934 {
1935         if (likely(ctx->num_get_sacl_priv_notheld == 0 &&
1936                    ctx->num_get_sd_access_denied == 0))
1937                 return;
1938
1939         WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1940         if (ctx->num_get_sacl_priv_notheld != 0) {
1941                 WARNING("- Could not capture SACL (System Access Control List)\n"
1942                         "            on %lu files or directories.",
1943                         ctx->num_get_sacl_priv_notheld);
1944         }
1945         if (ctx->num_get_sd_access_denied != 0) {
1946                 WARNING("- Could not capture security descriptor at all\n"
1947                         "            on %lu files or directories.",
1948                         ctx->num_get_sd_access_denied);
1949         }
1950         WARNING("To fully capture all security descriptors, run the program\n"
1951                 "          with Administrator rights.");
1952 }
1953
1954 /*----------------------------------------------------------------------------*
1955  *                         Fast MFT scan implementation                       *
1956  *----------------------------------------------------------------------------*/
1957
1958 #define ENABLE_FAST_MFT_SCAN    1
1959
1960 #ifdef ENABLE_FAST_MFT_SCAN
1961
1962 typedef struct {
1963         u64 StartingCluster;
1964         u64 ClusterCount;
1965 } CLUSTER_RANGE;
1966
1967 typedef struct {
1968         u64 StartingFileReferenceNumber;
1969         u64 EndingFileReferenceNumber;
1970 } FILE_REFERENCE_RANGE;
1971
1972 /* The FSCTL_QUERY_FILE_LAYOUT ioctl.  This ioctl can be used on Windows 8 and
1973  * later to scan the MFT of an NTFS volume.  */
1974 #define FSCTL_QUERY_FILE_LAYOUT         CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 157, METHOD_NEITHER, FILE_ANY_ACCESS)
1975
1976 /* The input to FSCTL_QUERY_FILE_LAYOUT  */
1977 typedef struct {
1978         u32 NumberOfPairs;
1979 #define QUERY_FILE_LAYOUT_RESTART                                       0x00000001
1980 #define QUERY_FILE_LAYOUT_INCLUDE_NAMES                                 0x00000002
1981 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS                               0x00000004
1982 #define QUERY_FILE_LAYOUT_INCLUDE_EXTENTS                               0x00000008
1983 #define QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO                            0x00000010
1984 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED    0x00000020
1985         u32 Flags;
1986 #define QUERY_FILE_LAYOUT_FILTER_TYPE_NONE              0
1987 #define QUERY_FILE_LAYOUT_FILTER_TYPE_CLUSTERS          1
1988 #define QUERY_FILE_LAYOUT_FILTER_TYPE_FILEID            2
1989 #define QUERY_FILE_LAYOUT_NUM_FILTER_TYPES              3
1990         u32 FilterType;
1991         u32 Reserved;
1992         union {
1993                 CLUSTER_RANGE ClusterRanges[1];
1994                 FILE_REFERENCE_RANGE FileReferenceRanges[1];
1995         } Filter;
1996 } QUERY_FILE_LAYOUT_INPUT;
1997
1998 /* The header of the buffer returned by FSCTL_QUERY_FILE_LAYOUT  */
1999 typedef struct {
2000         u32 FileEntryCount;
2001         u32 FirstFileOffset;
2002 #define QUERY_FILE_LAYOUT_SINGLE_INSTANCED                              0x00000001
2003         u32 Flags;
2004         u32 Reserved;
2005 } QUERY_FILE_LAYOUT_OUTPUT;
2006
2007 /* Inode information returned by FSCTL_QUERY_FILE_LAYOUT  */
2008 typedef struct {
2009         u32 Version;
2010         u32 NextFileOffset;
2011         u32 Flags;
2012         u32 FileAttributes;
2013         u64 FileReferenceNumber;
2014         u32 FirstNameOffset;
2015         u32 FirstStreamOffset;
2016         u32 ExtraInfoOffset;
2017         u32 Reserved;
2018 } FILE_LAYOUT_ENTRY;
2019
2020 /* Extra inode information returned by FSCTL_QUERY_FILE_LAYOUT  */
2021 typedef struct {
2022         struct {
2023                 u64 CreationTime;
2024                 u64 LastAccessTime;
2025                 u64 LastWriteTime;
2026                 u64 ChangeTime;
2027                 u32 FileAttributes;
2028         } BasicInformation;
2029         u32 OwnerId;
2030         u32 SecurityId;
2031         s64 Usn;
2032 } FILE_LAYOUT_INFO_ENTRY;
2033
2034 /* Filename (or dentry) information returned by FSCTL_QUERY_FILE_LAYOUT  */
2035 typedef struct {
2036         u32 NextNameOffset;
2037 #define FILE_LAYOUT_NAME_ENTRY_PRIMARY  0x00000001
2038 #define FILE_LAYOUT_NAME_ENTRY_DOS      0x00000002
2039         u32 Flags;
2040         u64 ParentFileReferenceNumber;
2041         u32 FileNameLength;
2042         u32 Reserved;
2043         wchar_t FileName[1];
2044 } FILE_LAYOUT_NAME_ENTRY;
2045
2046 /* Stream information returned by FSCTL_QUERY_FILE_LAYOUT  */
2047 typedef struct {
2048         u32 Version;
2049         u32 NextStreamOffset;
2050 #define STREAM_LAYOUT_ENTRY_IMMOVABLE                   0x00000001
2051 #define STREAM_LAYOUT_ENTRY_PINNED                      0x00000002
2052 #define STREAM_LAYOUT_ENTRY_RESIDENT                    0x00000004
2053 #define STREAM_LAYOUT_ENTRY_NO_CLUSTERS_ALLOCATED       0x00000008
2054         u32 Flags;
2055         u32 ExtentInformationOffset;
2056         u64 AllocationSize;
2057         u64 EndOfFile;
2058         u64 Reserved;
2059         u32 AttributeFlags;
2060         u32 StreamIdentifierLength;
2061         wchar_t StreamIdentifier[1];
2062 } STREAM_LAYOUT_ENTRY;
2063
2064
2065 typedef struct {
2066 #define STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS       0x00000001
2067 #define STREAM_EXTENT_ENTRY_ALL_EXTENTS                 0x00000002
2068         u32 Flags;
2069         union {
2070                 RETRIEVAL_POINTERS_BUFFER RetrievalPointers;
2071         } ExtentInformation;
2072 } STREAM_EXTENT_ENTRY;
2073
2074 /* Extract the MFT number part of the full inode number  */
2075 #define NTFS_MFT_NO(ref)        ((ref) & (((u64)1 << 48) - 1))
2076
2077 /* Is the file the root directory of the NTFS volume?  The root directory always
2078  * occupies MFT record 5.  */
2079 #define NTFS_IS_ROOT_FILE(ino)  (NTFS_MFT_NO(ino) == 5)
2080
2081 /* Is the file a special NTFS file, other than the root directory?  The special
2082  * files are the first 16 records in the MFT.  */
2083 #define NTFS_IS_SPECIAL_FILE(ino)                       \
2084         (NTFS_MFT_NO(ino) <= 15 && !NTFS_IS_ROOT_FILE(ino))
2085
2086 #define NTFS_SPECIAL_STREAM_OBJECT_ID           0x00000001
2087 #define NTFS_SPECIAL_STREAM_EA                  0x00000002
2088 #define NTFS_SPECIAL_STREAM_EA_INFORMATION      0x00000004
2089
2090 /* Intermediate inode structure.  This is used to temporarily save information
2091  * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_inode'.  */
2092 struct ntfs_inode {
2093         struct avl_tree_node index_node;
2094         u64 ino;
2095         u64 creation_time;
2096         u64 last_access_time;
2097         u64 last_write_time;
2098         u64 starting_lcn;
2099         u32 attributes;
2100         u32 security_id;
2101         u32 num_aliases;
2102         u32 num_streams;
2103         u32 special_streams;
2104         u32 first_stream_offset;
2105         struct ntfs_dentry *first_child;
2106         wchar_t short_name[13];
2107 };
2108
2109 /* Intermediate dentry structure.  This is used to temporarily save information
2110  * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_dentry'. */
2111 struct ntfs_dentry {
2112         u32 offset_from_inode : 31;
2113         u32 is_primary : 1;
2114         union {
2115                 /* Note: build_children_lists() replaces 'parent_ino' with
2116                  * 'next_child'.  */
2117                 u64 parent_ino;
2118                 struct ntfs_dentry *next_child;
2119         };
2120         wchar_t name[0];
2121 };
2122
2123 /* Intermediate stream structure.  This is used to temporarily save information
2124  * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct
2125  * wim_inode_stream'.  */
2126 struct ntfs_stream {
2127         u64 size;
2128         wchar_t name[0];
2129 };
2130
2131 /* Map of all known NTFS inodes, keyed by inode number  */
2132 struct ntfs_inode_map {
2133         struct avl_tree_node *root;
2134 };
2135
2136 #define NTFS_INODE(node)                                \
2137         avl_tree_entry((node), struct ntfs_inode, index_node)
2138
2139 #define SKIP_ALIGNED(p, size)   ((void *)(p) + ALIGN((size), 8))
2140
2141 /* Get a pointer to the first dentry of the inode.  */
2142 #define FIRST_DENTRY(ni) SKIP_ALIGNED((ni), sizeof(struct ntfs_inode))
2143
2144 /* Get a pointer to the first stream of the inode.  */
2145 #define FIRST_STREAM(ni) ((const void *)ni + ni->first_stream_offset)
2146
2147 /* Advance to the next dentry of the inode.  */
2148 #define NEXT_DENTRY(nd)  SKIP_ALIGNED((nd), sizeof(struct ntfs_dentry) +   \
2149                                 (wcslen((nd)->name) + 1) * sizeof(wchar_t))
2150
2151 /* Advance to the next stream of the inode.  */
2152 #define NEXT_STREAM(ns)  SKIP_ALIGNED((ns), sizeof(struct ntfs_stream) +   \
2153                                 (wcslen((ns)->name) + 1) * sizeof(wchar_t))
2154
2155 static int
2156 _avl_cmp_ntfs_inodes(const struct avl_tree_node *node1,
2157                      const struct avl_tree_node *node2)
2158 {
2159         return cmp_u64(NTFS_INODE(node1)->ino, NTFS_INODE(node2)->ino);
2160 }
2161
2162 /* Adds an NTFS inode to the map.  */
2163 static void
2164 ntfs_inode_map_add_inode(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2165 {
2166         if (avl_tree_insert(&map->root, &ni->index_node, _avl_cmp_ntfs_inodes)) {
2167                 WARNING("Inode 0x%016"PRIx64" is a duplicate!", ni->ino);
2168                 FREE(ni);
2169         }
2170 }
2171
2172 /* Find an ntfs_inode in the map by inode number.  Returns NULL if not found. */
2173 static struct ntfs_inode *
2174 ntfs_inode_map_lookup(struct ntfs_inode_map *map, u64 ino)
2175 {
2176         struct ntfs_inode tmp;
2177         struct avl_tree_node *res;
2178
2179         tmp.ino = ino;
2180         res = avl_tree_lookup_node(map->root, &tmp.index_node, _avl_cmp_ntfs_inodes);
2181         if (!res)
2182                 return NULL;
2183         return NTFS_INODE(res);
2184 }
2185
2186 /* Remove an ntfs_inode from the map and free it.  */
2187 static void
2188 ntfs_inode_map_remove(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2189 {
2190         avl_tree_remove(&map->root, &ni->index_node);
2191         FREE(ni);
2192 }
2193
2194 /* Free all ntfs_inodes in the map.  */
2195 static void
2196 ntfs_inode_map_destroy(struct ntfs_inode_map *map)
2197 {
2198         struct ntfs_inode *ni;
2199
2200         avl_tree_for_each_in_postorder(ni, map->root, struct ntfs_inode, index_node)
2201                 FREE(ni);
2202 }
2203
2204 static bool
2205 file_has_streams(const FILE_LAYOUT_ENTRY *file)
2206 {
2207         return (file->FirstStreamOffset != 0) &&
2208                 !(file->FileAttributes & FILE_ATTRIBUTE_ENCRYPTED);
2209 }
2210
2211 static bool
2212 is_valid_name_entry(const FILE_LAYOUT_NAME_ENTRY *name)
2213 {
2214         return name->FileNameLength > 0 &&
2215                 name->FileNameLength % 2 == 0 &&
2216                 !wmemchr(name->FileName, L'\0', name->FileNameLength / 2) &&
2217                 (!(name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) ||
2218                  name->FileNameLength <= 24);
2219 }
2220
2221 /* Validate the FILE_LAYOUT_NAME_ENTRYs of the specified file and compute the
2222  * total length in bytes of the ntfs_dentry structures needed to hold the name
2223  * information.  */
2224 static int
2225 validate_names_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2226                                         size_t *total_length_ret)
2227 {
2228         const FILE_LAYOUT_NAME_ENTRY *name =
2229                 (const void *)file + file->FirstNameOffset;
2230         size_t total = 0;
2231         size_t num_long_names = 0;
2232
2233         for (;;) {
2234                 if (unlikely(!is_valid_name_entry(name))) {
2235                         ERROR("Invalid FILE_LAYOUT_NAME_ENTRY! "
2236                               "FileReferenceNumber=0x%016"PRIx64", "
2237                               "FileNameLength=%"PRIu32", "
2238                               "FileName=%.*ls, Flags=0x%08"PRIx32,
2239                               file->FileReferenceNumber,
2240                               name->FileNameLength,
2241                               (int)(name->FileNameLength / 2),
2242                               name->FileName, name->Flags);
2243                         return WIMLIB_ERR_UNSUPPORTED;
2244                 }
2245                 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2246                         num_long_names++;
2247                         total += ALIGN(sizeof(struct ntfs_dentry) +
2248                                        name->FileNameLength + sizeof(wchar_t),
2249                                        8);
2250                 }
2251                 if (name->NextNameOffset == 0)
2252                         break;
2253                 name = (const void *)name + name->NextNameOffset;
2254         }
2255
2256         if (unlikely(num_long_names == 0)) {
2257                 ERROR("Inode 0x%016"PRIx64" has no long names!",
2258                       file->FileReferenceNumber);
2259                 return WIMLIB_ERR_UNSUPPORTED;
2260         }
2261
2262         *total_length_ret = total;
2263         return 0;
2264 }
2265
2266 static bool
2267 is_valid_stream_entry(const STREAM_LAYOUT_ENTRY *stream)
2268 {
2269         return stream->StreamIdentifierLength % 2 == 0 &&
2270                 !wmemchr(stream->StreamIdentifier , L'\0',
2271                          stream->StreamIdentifierLength / 2);
2272 }
2273
2274 /* assumes that 'id' is a wide string literal */
2275 #define stream_has_identifier(stream, id)                               \
2276         ((stream)->StreamIdentifierLength == sizeof(id) - 2 &&          \
2277          !memcmp((stream)->StreamIdentifier, id, sizeof(id) - 2))
2278 /*
2279  * If the specified STREAM_LAYOUT_ENTRY represents a DATA stream as opposed to
2280  * some other type of NTFS stream such as a STANDARD_INFORMATION stream, return
2281  * true and set *stream_name_ret and *stream_name_nchars_ret to specify just the
2282  * stream name.  For example, ":foo:$DATA" would become "foo" with length 3
2283  * characters.  Otherwise return false.
2284  */
2285 static bool
2286 use_stream(const FILE_LAYOUT_ENTRY *file, const STREAM_LAYOUT_ENTRY *stream,
2287            const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
2288 {
2289         const wchar_t *stream_name;
2290         size_t stream_name_nchars;
2291
2292         if (stream->StreamIdentifierLength == 0) {
2293                 /* The unnamed data stream may be given as an empty string
2294                  * rather than as "::$DATA".  Handle it both ways.  */
2295                 stream_name = L"";
2296                 stream_name_nchars = 0;
2297         } else if (!get_data_stream_name(stream->StreamIdentifier,
2298                                          stream->StreamIdentifierLength / 2,
2299                                          &stream_name, &stream_name_nchars))
2300                 return false;
2301
2302         /* Skip the unnamed data stream for directories.  */
2303         if (stream_name_nchars == 0 &&
2304             (file->FileAttributes & FILE_ATTRIBUTE_DIRECTORY))
2305                 return false;
2306
2307         *stream_name_ret = stream_name;
2308         *stream_name_nchars_ret = stream_name_nchars;
2309         return true;
2310 }
2311
2312 /* Validate the STREAM_LAYOUT_ENTRYs of the specified file and compute the total
2313  * length in bytes of the ntfs_stream structures needed to hold the stream
2314  * information.  In addition, set *special_streams_ret to a bitmask of special
2315  * stream types that were found.  */
2316 static int
2317 validate_streams_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2318                                           size_t *total_length_ret,
2319                                           u32 *special_streams_ret)
2320 {
2321         const STREAM_LAYOUT_ENTRY *stream =
2322                 (const void *)file + file->FirstStreamOffset;
2323         size_t total = 0;
2324         u32 special_streams = 0;
2325
2326         for (;;) {
2327                 const wchar_t *name;
2328                 size_t name_nchars;
2329
2330                 if (unlikely(!is_valid_stream_entry(stream))) {
2331                         WARNING("Invalid STREAM_LAYOUT_ENTRY! "
2332                                 "FileReferenceNumber=0x%016"PRIx64", "
2333                                 "StreamIdentifierLength=%"PRIu32", "
2334                                 "StreamIdentifier=%.*ls",
2335                                 file->FileReferenceNumber,
2336                                 stream->StreamIdentifierLength,
2337                                 (int)(stream->StreamIdentifierLength / 2),
2338                                 stream->StreamIdentifier);
2339                         return WIMLIB_ERR_UNSUPPORTED;
2340                 }
2341
2342                 if (use_stream(file, stream, &name, &name_nchars)) {
2343                         total += ALIGN(sizeof(struct ntfs_stream) +
2344                                        (name_nchars + 1) * sizeof(wchar_t), 8);
2345                 } else if (stream_has_identifier(stream, L"::$OBJECT_ID")) {
2346                         special_streams |= NTFS_SPECIAL_STREAM_OBJECT_ID;
2347                 } else if (stream_has_identifier(stream, L"::$EA")) {
2348                         special_streams |= NTFS_SPECIAL_STREAM_EA;
2349                 } else if (stream_has_identifier(stream, L"::$EA_INFORMATION")) {
2350                         special_streams |= NTFS_SPECIAL_STREAM_EA_INFORMATION;
2351                 }
2352                 if (stream->NextStreamOffset == 0)
2353                         break;
2354                 stream = (const void *)stream + stream->NextStreamOffset;
2355         }
2356
2357         *total_length_ret = total;
2358         *special_streams_ret = special_streams;
2359         return 0;
2360 }
2361
2362 static void *
2363 load_name_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2364                       void *p)
2365 {
2366         const FILE_LAYOUT_NAME_ENTRY *name =
2367                 (const void *)file + file->FirstNameOffset;
2368         for (;;) {
2369                 struct ntfs_dentry *nd = p;
2370                 /* Note that a name may be just a short (DOS) name, just a long
2371                  * name, or both a short name and a long name.  If there is a
2372                  * short name, one name should also be marked as "primary" to
2373                  * indicate which long name the short name is associated with.
2374                  * Also, there should be at most one short name per inode.  */
2375                 if (name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) {
2376                         memcpy(ni->short_name,
2377                                name->FileName, name->FileNameLength);
2378                         ni->short_name[name->FileNameLength / 2] = L'\0';
2379                 }
2380                 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2381                         ni->num_aliases++;
2382                         nd->offset_from_inode = (u8 *)nd - (u8 *)ni;
2383                         nd->is_primary = ((name->Flags &
2384                                            FILE_LAYOUT_NAME_ENTRY_PRIMARY) != 0);
2385                         nd->parent_ino = name->ParentFileReferenceNumber;
2386                         memcpy(nd->name, name->FileName, name->FileNameLength);
2387                         nd->name[name->FileNameLength / 2] = L'\0';
2388                         p += ALIGN(sizeof(struct ntfs_dentry) +
2389                                    name->FileNameLength + sizeof(wchar_t), 8);
2390                 }
2391                 if (name->NextNameOffset == 0)
2392                         break;
2393                 name = (const void *)name + name->NextNameOffset;
2394         }
2395         return p;
2396 }
2397
2398 static u64
2399 load_starting_lcn(const STREAM_LAYOUT_ENTRY *stream)
2400 {
2401         const STREAM_EXTENT_ENTRY *entry;
2402
2403         if (stream->ExtentInformationOffset == 0)
2404                 return 0;
2405
2406         entry = (const void *)stream + stream->ExtentInformationOffset;
2407
2408         if (!(entry->Flags & STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS))
2409                 return 0;
2410
2411         return extract_starting_lcn(&entry->ExtentInformation.RetrievalPointers);
2412 }
2413
2414 static void *
2415 load_stream_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2416                         void *p)
2417 {
2418         const STREAM_LAYOUT_ENTRY *stream =
2419                 (const void *)file + file->FirstStreamOffset;
2420         const u32 first_stream_offset = (const u8 *)p - (const u8 *)ni;
2421         for (;;) {
2422                 struct ntfs_stream *ns = p;
2423                 const wchar_t *name;
2424                 size_t name_nchars;
2425
2426                 if (use_stream(file, stream, &name, &name_nchars)) {
2427                         ni->first_stream_offset = first_stream_offset;
2428                         ni->num_streams++;
2429                         if (name_nchars == 0)
2430                                 ni->starting_lcn = load_starting_lcn(stream);
2431                         ns->size = stream->EndOfFile;
2432                         wmemcpy(ns->name, name, name_nchars);
2433                         ns->name[name_nchars] = L'\0';
2434                         p += ALIGN(sizeof(struct ntfs_stream) +
2435                                    (name_nchars + 1) * sizeof(wchar_t), 8);
2436                 }
2437                 if (stream->NextStreamOffset == 0)
2438                         break;
2439                 stream = (const void *)stream + stream->NextStreamOffset;
2440         }
2441         return p;
2442 }
2443
2444 /* Process the information for a file given by FSCTL_QUERY_FILE_LAYOUT.  */
2445 static int
2446 load_one_file(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode_map *inode_map)
2447 {
2448         const FILE_LAYOUT_INFO_ENTRY *info =
2449                 (const void *)file + file->ExtraInfoOffset;
2450         size_t inode_size;
2451         struct ntfs_inode *ni;
2452         size_t n;
2453         int ret;
2454         void *p;
2455         u32 special_streams = 0;
2456
2457         inode_size = ALIGN(sizeof(struct ntfs_inode), 8);
2458
2459         /* The root file should have no names, and all other files should have
2460          * at least one name.  But just in case, we ignore the names of the root
2461          * file, and we ignore any non-root file with no names.  */
2462         if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber)) {
2463                 if (file->FirstNameOffset == 0)
2464                         return 0;
2465                 ret = validate_names_and_compute_total_length(file, &n);
2466                 if (ret)
2467                         return ret;
2468                 inode_size += n;
2469         }
2470
2471         if (file_has_streams(file)) {
2472                 ret = validate_streams_and_compute_total_length(file, &n,
2473                                                                 &special_streams);
2474                 if (ret)
2475                         return ret;
2476                 inode_size += n;
2477         }
2478
2479         /* To save memory, we allocate the ntfs_dentry's and ntfs_stream's in
2480          * the same memory block as their ntfs_inode.  */
2481         ni = CALLOC(1, inode_size);
2482         if (!ni)
2483                 return WIMLIB_ERR_NOMEM;
2484
2485         ni->ino = file->FileReferenceNumber;
2486         ni->attributes = info->BasicInformation.FileAttributes;
2487         ni->creation_time = info->BasicInformation.CreationTime;
2488         ni->last_write_time = info->BasicInformation.LastWriteTime;
2489         ni->last_access_time = info->BasicInformation.LastAccessTime;
2490         ni->security_id = info->SecurityId;
2491         ni->special_streams = special_streams;
2492
2493         p = FIRST_DENTRY(ni);
2494
2495         if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber))
2496                 p = load_name_information(file, ni, p);
2497
2498         if (file_has_streams(file))
2499                 p = load_stream_information(file, ni, p);
2500
2501         wimlib_assert((u8 *)p - (u8 *)ni == inode_size);
2502
2503         ntfs_inode_map_add_inode(inode_map, ni);
2504         return 0;
2505 }
2506
2507 /*
2508  * Quickly find all files on an NTFS volume by using FSCTL_QUERY_FILE_LAYOUT to
2509  * scan the MFT.  The NTFS volume is specified by the NT namespace path @path.
2510  * For each file, allocate an 'ntfs_inode' structure for each file and add it to
2511  * 'inode_map' keyed by inode number.  Include NTFS special files such as
2512  * $Bitmap (they will be removed later).
2513  */
2514 static int
2515 load_files_from_mft(const wchar_t *path, struct ntfs_inode_map *inode_map)
2516 {
2517         HANDLE h = NULL;
2518         QUERY_FILE_LAYOUT_INPUT in = (QUERY_FILE_LAYOUT_INPUT) {
2519                 .NumberOfPairs = 0,
2520                 .Flags = QUERY_FILE_LAYOUT_RESTART |
2521                          QUERY_FILE_LAYOUT_INCLUDE_NAMES |
2522                          QUERY_FILE_LAYOUT_INCLUDE_STREAMS |
2523                          QUERY_FILE_LAYOUT_INCLUDE_EXTENTS |
2524                          QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO |
2525                          QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED,
2526                 .FilterType = QUERY_FILE_LAYOUT_FILTER_TYPE_NONE,
2527         };
2528         size_t outsize = 32768;
2529         QUERY_FILE_LAYOUT_OUTPUT *out = NULL;
2530         int ret;
2531         NTSTATUS status;
2532
2533         status = winnt_open(path, wcslen(path),
2534                             FILE_READ_DATA | FILE_READ_ATTRIBUTES, &h);
2535         if (!NT_SUCCESS(status)) {
2536                 ret = -1; /* Silently try standard recursive scan instead  */
2537                 goto out;
2538         }
2539
2540         for (;;) {
2541                 /* Allocate a buffer for the output of the ioctl.  */
2542                 out = MALLOC(outsize);
2543                 if (!out) {
2544                         ret = WIMLIB_ERR_NOMEM;
2545                         goto out;
2546                 }
2547
2548                 /* Execute FSCTL_QUERY_FILE_LAYOUT until it fails.  */
2549                 while (NT_SUCCESS(status = winnt_fsctl(h,
2550                                                        FSCTL_QUERY_FILE_LAYOUT,
2551                                                        &in, sizeof(in),
2552                                                        out, outsize, NULL)))
2553                 {
2554                         const FILE_LAYOUT_ENTRY *file =
2555                                 (const void *)out + out->FirstFileOffset;
2556                         for (;;) {
2557                                 ret = load_one_file(file, inode_map);
2558                                 if (ret)
2559                                         goto out;
2560                                 if (file->NextFileOffset == 0)
2561                                         break;
2562                                 file = (const void *)file + file->NextFileOffset;
2563                         }
2564                         in.Flags &= ~QUERY_FILE_LAYOUT_RESTART;
2565                 }
2566
2567                 /* Enlarge the buffer if needed.  */
2568                 if (status != STATUS_BUFFER_TOO_SMALL)
2569                         break;
2570                 FREE(out);
2571                 outsize *= 2;
2572         }
2573
2574         /* Normally, FSCTL_QUERY_FILE_LAYOUT fails with STATUS_END_OF_FILE after
2575          * all files have been enumerated.  */
2576         if (status != STATUS_END_OF_FILE) {
2577                 if (status == STATUS_INVALID_DEVICE_REQUEST /* old OS */ ||
2578                     status == STATUS_NOT_SUPPORTED /* Samba volume, WinXP */ ||
2579                     status == STATUS_INVALID_PARAMETER /* not root directory */ )
2580                 {
2581                         /* Silently try standard recursive scan instead  */
2582                         ret = -1;
2583                 } else {
2584                         winnt_error(status,
2585                                     L"Error enumerating files on volume \"%ls\"",
2586                                     path);
2587                         /* Try standard recursive scan instead  */
2588                         ret = WIMLIB_ERR_UNSUPPORTED;
2589                 }
2590                 goto out;
2591         }
2592         ret = 0;
2593 out:
2594         FREE(out);
2595         NtClose(h);
2596         return ret;
2597 }
2598
2599 /* Build the list of child dentries for each inode in @map.  This is done by
2600  * iterating through each name of each inode and adding it to its parent's
2601  * children list.  Note that every name should have a parent, i.e. should belong
2602  * to some directory.  The root directory does not have any names.  */
2603 static int
2604 build_children_lists(struct ntfs_inode_map *map, struct ntfs_inode **root_ret)
2605 {
2606         struct ntfs_inode *ni;
2607
2608         avl_tree_for_each_in_order(ni, map->root, struct ntfs_inode, index_node)
2609         {
2610                 struct ntfs_dentry *nd;
2611                 u32 n;
2612
2613                 if (NTFS_IS_ROOT_FILE(ni->ino)) {
2614                         *root_ret = ni;
2615                         continue;
2616                 }
2617
2618                 n = ni->num_aliases;
2619                 nd = FIRST_DENTRY(ni);
2620                 for (;;) {
2621                         struct ntfs_inode *parent;
2622
2623                         parent = ntfs_inode_map_lookup(map, nd->parent_ino);
2624                         if (unlikely(!parent)) {
2625                                 ERROR("Parent inode 0x%016"PRIx64" of"
2626                                       "directory entry \"%ls\" (inode "
2627                                       "0x%016"PRIx64") was missing from the "
2628                                       "MFT listing!",
2629                                       nd->parent_ino, nd->name, ni->ino);
2630                                 return WIMLIB_ERR_UNSUPPORTED;
2631                         }
2632                         nd->next_child = parent->first_child;
2633                         parent->first_child = nd;
2634                         if (!--n)
2635                                 break;
2636                         nd = NEXT_DENTRY(nd);
2637                 }
2638         }
2639         return 0;
2640 }
2641
2642 struct security_map_node {
2643         struct avl_tree_node index_node;
2644         u32 disk_security_id;
2645         u32 wim_security_id;
2646 };
2647
2648 /* Map from disk security IDs to WIM security IDs  */
2649 struct security_map {
2650         struct avl_tree_node *root;
2651 };
2652
2653 #define SECURITY_MAP_NODE(node)                         \
2654         avl_tree_entry((node), struct security_map_node, index_node)
2655
2656 static int
2657 _avl_cmp_security_map_nodes(const struct avl_tree_node *node1,
2658                             const struct avl_tree_node *node2)
2659 {
2660         return cmp_u32(SECURITY_MAP_NODE(node1)->disk_security_id,
2661                        SECURITY_MAP_NODE(node2)->disk_security_id);
2662 }
2663
2664 static s32
2665 security_map_lookup(struct security_map *map, u32 disk_security_id)
2666 {
2667         struct security_map_node tmp;
2668         const struct avl_tree_node *res;
2669
2670         if (disk_security_id == 0)  /* No on-disk security ID; uncacheable  */
2671                 return -1;
2672
2673         tmp.disk_security_id = disk_security_id;
2674         res = avl_tree_lookup_node(map->root, &tmp.index_node,
2675                                    _avl_cmp_security_map_nodes);
2676         if (!res)
2677                 return -1;
2678         return SECURITY_MAP_NODE(res)->wim_security_id;
2679 }
2680
2681 static int
2682 security_map_insert(struct security_map *map, u32 disk_security_id,
2683                     u32 wim_security_id)
2684 {
2685         struct security_map_node *node;
2686
2687         if (disk_security_id == 0)  /* No on-disk security ID; uncacheable  */
2688                 return 0;
2689
2690         node = MALLOC(sizeof(*node));
2691         if (!node)
2692                 return WIMLIB_ERR_NOMEM;
2693
2694         node->disk_security_id = disk_security_id;
2695         node->wim_security_id = wim_security_id;
2696         avl_tree_insert(&map->root, &node->index_node,
2697                         _avl_cmp_security_map_nodes);
2698         return 0;
2699 }
2700
2701 static void
2702 security_map_destroy(struct security_map *map)
2703 {
2704         struct security_map_node *node;
2705
2706         avl_tree_for_each_in_postorder(node, map->root,
2707                                        struct security_map_node, index_node)
2708                 FREE(node);
2709 }
2710
2711 /*
2712  * Turn our temporary NTFS structures into the final WIM structures:
2713  *
2714  *      ntfs_inode      => wim_inode
2715  *      ntfs_dentry     => wim_dentry
2716  *      ntfs_stream     => wim_inode_stream
2717  *
2718  * This also handles things such as exclusions and issuing progress messages.
2719  * It's similar to winnt_build_dentry_tree(), but this is much faster because
2720  * almost all information we need is already loaded in memory in the ntfs_*
2721  * structures.  However, in some cases we still fall back to
2722  * winnt_build_dentry_tree() and/or opening the file.
2723  */
2724 static int
2725 generate_wim_structures_recursive(struct wim_dentry **root_ret,
2726                                   const wchar_t *filename, bool is_primary_name,
2727                                   struct ntfs_inode *ni,
2728                                   struct winnt_scan_ctx *ctx,
2729                                   struct ntfs_inode_map *inode_map,
2730                                   struct security_map *security_map)
2731 {
2732         int ret = 0;
2733         struct wim_dentry *root = NULL;
2734         struct wim_inode *inode = NULL;
2735         const struct ntfs_stream *ns;
2736
2737         /* Completely ignore NTFS special files.  */
2738         if (NTFS_IS_SPECIAL_FILE(ni->ino))
2739                 goto out;
2740
2741         /* Fall back to the standard scan for unhandled cases.  Reparse points,
2742          * in particular, can't be properly handled here because a commonly used
2743          * filter driver (WOF) hides reparse points from regular filesystem APIs
2744          * but not from FSCTL_QUERY_FILE_LAYOUT.  */
2745         if (ni->attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
2746                               FILE_ATTRIBUTE_ENCRYPTED) ||
2747             ni->special_streams != 0)
2748         {
2749                 ret = winnt_build_dentry_tree(&root, NULL,
2750                                               ctx->params->cur_path,
2751                                               ctx->params->cur_path_nchars,
2752                                               filename, ctx, false);
2753                 if (ret) /* Error? */
2754                         goto out;
2755                 if (!root) /* Excluded? */
2756                         goto out_progress;
2757                 inode = root->d_inode;
2758                 goto process_children;
2759         }
2760
2761         /* Test for exclusion based on path.  */
2762         ret = try_exclude(ctx->params);
2763         if (unlikely(ret < 0)) /* Excluded? */
2764                 goto out_progress;
2765         if (unlikely(ret > 0)) /* Error? */
2766                 goto out;
2767
2768         /* Create the WIM dentry and possibly a new WIM inode  */
2769         ret = inode_table_new_dentry(ctx->params->inode_table, filename,
2770                                      ni->ino, ctx->params->capture_root_dev,
2771                                      false, &root);
2772         if (ret)
2773                 goto out;
2774
2775         inode = root->d_inode;
2776
2777         /* Set the short name if needed.  */
2778         if (is_primary_name && *ni->short_name) {
2779                 size_t nbytes = wcslen(ni->short_name) * sizeof(wchar_t);
2780                 root->d_short_name = memdup(ni->short_name,
2781                                             nbytes + sizeof(wchar_t));
2782                 if (!root->d_short_name) {
2783                         ret = WIMLIB_ERR_NOMEM;
2784                         goto out;
2785                 }
2786                 root->d_short_name_nbytes = nbytes;
2787         }
2788
2789         if (inode->i_nlink > 1) { /* Already seen this inode?  */
2790                 ret = 0;
2791                 goto out_progress;
2792         }
2793
2794         /* The file attributes and timestamps were cached from the MFT.  */
2795         inode->i_attributes = ni->attributes;
2796         inode->i_creation_time = ni->creation_time;
2797         inode->i_last_write_time = ni->last_write_time;
2798         inode->i_last_access_time = ni->last_access_time;
2799
2800         /* Set the security descriptor if needed.  */
2801         if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)) {
2802                 /* Look up the WIM security ID that corresponds to the on-disk
2803                  * security ID.  */
2804                 s32 wim_security_id =
2805                         security_map_lookup(security_map, ni->security_id);
2806                 if (likely(wim_security_id >= 0)) {
2807                         /* The mapping for this security ID is already cached.*/
2808                         inode->i_security_id = wim_security_id;
2809                 } else {
2810                         HANDLE h;
2811                         NTSTATUS status;
2812
2813                         /* Create a mapping for this security ID and insert it
2814                          * into the security map.  */
2815
2816                         status = winnt_open(ctx->params->cur_path,
2817                                             ctx->params->cur_path_nchars,
2818                                             READ_CONTROL |
2819                                                 ACCESS_SYSTEM_SECURITY, &h);
2820                         if (!NT_SUCCESS(status)) {
2821                                 winnt_error(status, L"Can't open \"%ls\" to "
2822                                             "read security descriptor",
2823                                             printable_path(ctx));
2824                                 ret = WIMLIB_ERR_OPEN;
2825                                 goto out;
2826                         }
2827                         ret = winnt_load_security_descriptor(h, inode, ctx);
2828                         NtClose(h);
2829                         if (ret)
2830                                 goto out;
2831
2832                         ret = security_map_insert(security_map, ni->security_id,
2833                                                   inode->i_security_id);
2834                         if (ret)
2835                                 goto out;
2836                 }
2837         }
2838
2839         /* Add data streams based on the cached information from the MFT.  */
2840         ns = FIRST_STREAM(ni);
2841         for (u32 i = 0; i < ni->num_streams; i++) {
2842                 struct windows_file *windows_file;
2843
2844                 /* Reference the stream by path if it's a named data stream, or
2845                  * if the volume doesn't support "open by file ID", or if the
2846                  * application hasn't explicitly opted in to "open by file ID".
2847                  * Otherwise, only save the inode number (file ID).  */
2848                 if (*ns->name ||
2849                     !(ctx->vol_flags & FILE_SUPPORTS_OPEN_BY_FILE_ID) ||
2850                     !(ctx->params->add_flags & WIMLIB_ADD_FLAG_FILE_PATHS_UNNEEDED))
2851                 {
2852                         windows_file = alloc_windows_file(ctx->params->cur_path,
2853                                                           ctx->params->cur_path_nchars,
2854                                                           ns->name,
2855                                                           wcslen(ns->name),
2856                                                           ctx->snapshot,
2857                                                           false);
2858                 } else {
2859                         windows_file = alloc_windows_file_for_file_id(ni->ino,
2860                                                                       ctx->params->cur_path,
2861                                                                       ctx->params->root_path_nchars,
2862                                                                       ctx->snapshot);
2863                 }
2864
2865                 ret = add_stream(inode, windows_file, ns->size,
2866                                  STREAM_TYPE_DATA, ns->name,
2867                                  ctx->params->unhashed_blobs);
2868                 if (ret)
2869                         goto out;
2870                 ns = NEXT_STREAM(ns);
2871         }
2872
2873         set_sort_key(inode, ni->starting_lcn);
2874
2875         /* If processing a directory, then recurse to its children.  In this
2876          * version there is no need to go to disk, as we already have the list
2877          * of children cached from the MFT.  */
2878 process_children:
2879         if (inode_is_directory(inode)) {
2880                 const struct ntfs_dentry *nd = ni->first_child;
2881
2882                 while (nd != NULL) {
2883                         size_t orig_path_nchars;
2884                         struct wim_dentry *child;
2885                         const struct ntfs_dentry *next = nd->next_child;
2886
2887                         ret = WIMLIB_ERR_NOMEM;
2888                         if (!pathbuf_append_name(ctx->params, nd->name,
2889                                                  wcslen(nd->name),
2890                                                  &orig_path_nchars))
2891                                 goto out;
2892
2893                         ret = generate_wim_structures_recursive(
2894                                         &child,
2895                                         nd->name,
2896                                         nd->is_primary,
2897                                         (void *)nd - nd->offset_from_inode,
2898                                         ctx,
2899                                         inode_map,
2900                                         security_map);
2901
2902                         pathbuf_truncate(ctx->params, orig_path_nchars);
2903
2904                         if (ret)
2905                                 goto out;
2906
2907                         attach_scanned_tree(root, child, ctx->params->blob_table);
2908                         nd = next;
2909                 }
2910         }
2911
2912 out_progress:
2913         if (likely(root))
2914                 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_OK, inode);
2915         else
2916                 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
2917 out:
2918         if (--ni->num_aliases == 0) {
2919                 /* Memory usage optimization: when we don't need the ntfs_inode
2920                  * (and its names and streams) anymore, free it.  */
2921                 ntfs_inode_map_remove(inode_map, ni);
2922         }
2923         if (unlikely(ret)) {
2924                 free_dentry_tree(root, ctx->params->blob_table);
2925                 root = NULL;
2926         }
2927         *root_ret = root;
2928         return ret;
2929 }
2930
2931 static int
2932 winnt_build_dentry_tree_fast(struct wim_dentry **root_ret,
2933                              struct winnt_scan_ctx *ctx)
2934 {
2935         struct ntfs_inode_map inode_map = { .root = NULL };
2936         struct security_map security_map = { .root = NULL };
2937         struct ntfs_inode *root = NULL;
2938         wchar_t *path = ctx->params->cur_path;
2939         size_t path_nchars = ctx->params->cur_path_nchars;
2940         bool adjust_path;
2941         int ret;
2942
2943         adjust_path = (path[path_nchars - 1] == L'\\');
2944         if (adjust_path)
2945                 path[path_nchars - 1] = L'\0';
2946
2947         ret = load_files_from_mft(path, &inode_map);
2948
2949         if (adjust_path)
2950                 path[path_nchars - 1] = L'\\';
2951
2952         if (ret)
2953                 goto out;
2954
2955         ret = build_children_lists(&inode_map, &root);
2956         if (ret)
2957                 goto out;
2958
2959         if (!root) {
2960                 ERROR("The MFT listing for volume \"%ls\" did not include a "
2961                       "root directory!", path);
2962                 ret = WIMLIB_ERR_UNSUPPORTED;
2963                 goto out;
2964         }
2965
2966         root->num_aliases = 1;
2967
2968         ret = generate_wim_structures_recursive(root_ret, L"", false, root, ctx,
2969                                                 &inode_map, &security_map);
2970 out:
2971         ntfs_inode_map_destroy(&inode_map);
2972         security_map_destroy(&security_map);
2973         return ret;
2974 }
2975
2976 #endif /* ENABLE_FAST_MFT_SCAN */
2977
2978 /*----------------------------------------------------------------------------*
2979  *                 Entry point for directory tree scans on Windows            *
2980  *----------------------------------------------------------------------------*/
2981
2982 int
2983 win32_build_dentry_tree(struct wim_dentry **root_ret,
2984                         const wchar_t *root_disk_path,
2985                         struct scan_params *params)
2986 {
2987         struct winnt_scan_ctx ctx = { .params = params };
2988         UNICODE_STRING ntpath;
2989         HANDLE h = NULL;
2990         NTSTATUS status;
2991         int ret;
2992
2993         if (params->add_flags & WIMLIB_ADD_FLAG_SNAPSHOT)
2994                 ret = vss_create_snapshot(root_disk_path, &ntpath, &ctx.snapshot);
2995         else
2996                 ret = win32_path_to_nt_path(root_disk_path, &ntpath);
2997
2998         if (ret)
2999                 goto out;
3000
3001         if (ntpath.Length < 4 * sizeof(wchar_t) ||
3002             wmemcmp(ntpath.Buffer, L"\\??\\", 4))
3003         {
3004                 ERROR("\"%ls\": unrecognized path format", root_disk_path);
3005                 ret = WIMLIB_ERR_INVALID_PARAM;
3006         } else {
3007                 ret = pathbuf_init(params, ntpath.Buffer);
3008         }
3009         HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
3010         if (ret)
3011                 goto out;
3012
3013         status = winnt_open(params->cur_path, params->cur_path_nchars,
3014                             FILE_READ_ATTRIBUTES, &h);
3015         if (!NT_SUCCESS(status)) {
3016                 winnt_error(status, L"Can't open \"%ls\"", root_disk_path);
3017                 if (status == STATUS_FVE_LOCKED_VOLUME)
3018                         ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
3019                 else
3020                         ret = WIMLIB_ERR_OPEN;
3021                 goto out;
3022         }
3023
3024         get_volume_information(h, &ctx);
3025
3026         NtClose(h);
3027
3028 #ifdef ENABLE_FAST_MFT_SCAN
3029         if (ctx.is_ntfs && !_wgetenv(L"WIMLIB_DISABLE_QUERY_FILE_LAYOUT")) {
3030                 ret = winnt_build_dentry_tree_fast(root_ret, &ctx);
3031                 if (ret >= 0 && ret != WIMLIB_ERR_UNSUPPORTED)
3032                         goto out;
3033                 if (ret >= 0) {
3034                         WARNING("A problem occurred during the fast MFT scan.\n"
3035                                 "          Falling back to the standard "
3036                                 "recursive directory tree scan.");
3037                 }
3038         }
3039 #endif
3040         ret = winnt_build_dentry_tree(root_ret, NULL, params->cur_path,
3041                                       params->cur_path_nchars, L"", &ctx, true);
3042 out:
3043         vss_put_snapshot(ctx.snapshot);
3044         if (ret == 0)
3045                 winnt_do_scan_warnings(root_disk_path, &ctx);
3046         return ret;
3047 }
3048
3049 #endif /* _WIN32 */