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