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