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