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