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