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