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