2 * win32_capture.c - Windows-specific code for capturing files into a WIM image.
4 * This now uses the native Windows NT API a lot and not just Win32.
8 * Copyright (C) 2013-2018 Eric Biggers
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
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
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/.
30 #include "wimlib/win32_common.h"
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"
46 struct winnt_scan_ctx {
47 struct scan_params *params;
50 unsigned long num_get_sd_access_denied;
51 unsigned long num_get_sacl_priv_notheld;
53 /* True if WOF is definitely not attached to the volume being scanned;
54 * false if it may be */
55 bool wof_not_attached;
57 /* A reference to the VSS snapshot being used, or NULL if none */
58 struct vss_snapshot *snapshot;
61 static inline const wchar_t *
62 printable_path(const struct winnt_scan_ctx *ctx)
64 /* Skip over \\?\ or \??\ */
65 return ctx->params->cur_path + 4;
68 /* Description of where data is located on a Windows filesystem */
71 /* Is the data the raw encrypted data of an EFS-encrypted file? */
74 /* Is this file "open by file ID" rather than the regular "open by
75 * path"? "Open by file ID" uses resources more efficiently. */
78 /* The file's LCN (logical cluster number) for sorting, or 0 if unknown.
82 /* Length of the path in bytes, excluding the null terminator if
86 /* A reference to the VSS snapshot containing the file, or NULL if none.
88 struct vss_snapshot *snapshot;
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. */
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)
104 size_t full_path_nbytes;
105 struct windows_file *file;
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);
112 file = MALLOC(sizeof(struct windows_file) + full_path_nbytes +
117 file->is_encrypted = is_encrypted;
118 file->is_file_id = 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 */
126 p = wmempcpy(p, stream_name, stream_name_nchars);
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)
138 size_t full_path_nbytes;
139 struct windows_file *file;
142 full_path_nbytes = (root_path_nchars * sizeof(wchar_t)) +
144 file = MALLOC(sizeof(struct windows_file) + full_path_nbytes +
149 file->is_encrypted = 0;
150 file->is_file_id = 1;
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));
160 /* Add a stream, located on a Windows filesystem, to the specified WIM inode. */
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)
166 struct blob_descriptor *blob = NULL;
167 struct wim_inode_stream *strm;
173 /* If the stream is nonempty, create a blob descriptor for it. */
175 blob = new_blob_descriptor();
178 blob->windows_file = windows_file;
179 blob->blob_location = BLOB_IN_WINDOWS_FILE;
180 blob->file_inode = inode;
181 blob->size = stream_size;
185 strm = inode_add_stream(inode, stream_type, stream_name, blob);
189 prepare_unhashed_blob(blob, inode, strm->stream_id, unhashed_blobs);
193 free_windows_file(windows_file);
197 free_blob_descriptor(blob);
198 ret = WIMLIB_ERR_NOMEM;
202 struct windows_file *
203 clone_windows_file(const struct windows_file *file)
205 struct windows_file *new;
207 new = memdup(file, sizeof(*file) + file->path_nbytes + sizeof(wchar_t));
209 vss_get_snapshot(new->snapshot);
214 free_windows_file(struct windows_file *file)
216 vss_put_snapshot(file->snapshot);
221 cmp_windows_files(const struct windows_file *file1,
222 const struct windows_file *file2)
224 /* Compare by starting LCN (logical cluster number) */
225 int v = cmp_u64(file1->sort_key, file2->sort_key);
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));
235 return cmp_u32(file1->path_nbytes, file2->path_nbytes);
239 get_windows_file_path(const struct windows_file *file)
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.
251 winnt_openat(HANDLE cur_dir, const wchar_t *path, size_t path_nchars,
252 ACCESS_MASK perms, HANDLE *h_ret)
254 UNICODE_STRING name = {
255 .Length = path_nchars * sizeof(wchar_t),
256 .MaximumLength = path_nchars * sizeof(wchar_t),
257 .Buffer = (wchar_t *)path,
259 OBJECT_ATTRIBUTES attr = {
260 .Length = sizeof(attr),
261 .RootDirectory = cur_dir,
264 IO_STATUS_BLOCK iosb;
266 ULONG options = FILE_OPEN_REPARSE_POINT | FILE_OPEN_FOR_BACKUP_INTENT;
268 perms |= SYNCHRONIZE;
269 if (perms & (FILE_READ_DATA | FILE_LIST_DIRECTORY)) {
270 options |= FILE_SYNCHRONOUS_IO_NONALERT;
271 options |= FILE_SEQUENTIAL_ONLY;
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;
284 if (perms & READ_CONTROL) {
285 perms &= ~READ_CONTROL;
294 winnt_open(const wchar_t *path, size_t path_nchars, ACCESS_MASK perms,
297 return winnt_openat(NULL, path, path_nchars, perms, h_ret);
300 static const wchar_t *
301 windows_file_to_string(const struct windows_file *file, u8 *buf, size_t bufsize)
303 if (file->is_file_id) {
306 (u8 *)file->path + file->path_nbytes - 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);
312 return L"(name too long)";
314 return (wchar_t *)buf;
318 read_winnt_stream_prefix(const struct windows_file *file,
319 u64 size, const struct consume_chunk_callback *cb)
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,
327 OBJECT_ATTRIBUTES attr = {
328 .Length = sizeof(attr),
333 u8 buf[BUFFER_SIZE] _aligned_attribute(8);
337 status = NtOpenFile(&h, FILE_READ_DATA | SYNCHRONIZE,
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)));
352 winnt_error(status, L"Can't open %ls for reading",
353 windows_file_to_string(file, buf, sizeof(buf)));
355 return WIMLIB_ERR_OPEN;
359 bytes_remaining = size;
360 while (bytes_remaining) {
361 IO_STATUS_BLOCK iosb;
364 const unsigned max_tries = 5;
365 unsigned tries_remaining = max_tries;
367 count = min(sizeof(buf), bytes_remaining);
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;
378 winnt_warning(status, L"Error reading data from %ls",
379 windows_file_to_string(file, buf, sizeof(buf)));
381 /* Currently these retries are purely a guess;
382 * there is no reproducible problem that they solve. */
383 if (--tries_remaining) {
385 if (status == STATUS_INSUFFICIENT_RESOURCES ||
386 status == STATUS_NO_MEMORY) {
389 WARNING("Retrying after %dms...", delay);
393 ERROR("Too many retries; returning failure");
394 ret = WIMLIB_ERR_READ;
397 } else if (unlikely(tries_remaining != max_tries)) {
398 WARNING("A read request had to be retried multiple times "
399 "before it succeeded!");
402 bytes_read = iosb.Information;
404 bytes_remaining -= bytes_read;
405 ret = consume_chunk(cb, buf, bytes_read);
413 struct win32_encrypted_read_ctx {
414 const struct consume_chunk_callback *cb;
420 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
422 struct win32_encrypted_read_ctx *ctx = _ctx;
424 size_t bytes_to_consume = min(len, ctx->bytes_remaining);
426 if (bytes_to_consume == 0)
427 return ERROR_SUCCESS;
429 ret = consume_chunk(ctx->cb, data, bytes_to_consume);
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;
436 ctx->bytes_remaining -= bytes_to_consume;
437 return ERROR_SUCCESS;
441 read_win32_encrypted_file_prefix(const wchar_t *path, bool is_dir, u64 size,
442 const struct consume_chunk_callback *cb)
444 struct win32_encrypted_read_ctx export_ctx;
451 flags |= CREATE_FOR_DIR;
454 export_ctx.wimlib_err_code = 0;
455 export_ctx.bytes_remaining = size;
457 err = OpenEncryptedFileRaw(path, flags, &file_ctx);
458 if (err != ERROR_SUCCESS) {
460 L"Failed to open encrypted file \"%ls\" for raw read",
462 return WIMLIB_ERR_OPEN;
464 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
465 &export_ctx, file_ctx);
466 if (err != ERROR_SUCCESS) {
467 ret = export_ctx.wimlib_err_code;
470 L"Failed to read encrypted file \"%ls\"",
472 ret = WIMLIB_ERR_READ;
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,
479 ret = WIMLIB_ERR_READ;
483 CloseEncryptedFileRaw(file_ctx);
487 /* Read the first @size bytes from the file, or named data stream of a file,
488 * described by @blob. */
490 read_windows_file_prefix(const struct blob_descriptor *blob, u64 size,
491 const struct consume_chunk_callback *cb)
493 const struct windows_file *file = blob->windows_file;
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);
500 return read_winnt_stream_prefix(file, size, cb);
504 * Load the short name of a file into a WIM dentry.
506 static noinline_for_stack NTSTATUS
507 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
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. */
513 IO_STATUS_BLOCK iosb;
514 u8 buf[128] _aligned_attribute(8);
515 const FILE_NAME_INFORMATION *info;
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;
531 * Load the security descriptor of a file into the corresponding inode and the
532 * WIM image's security descriptor set.
534 static noinline_for_stack int
535 winnt_load_security_descriptor(HANDLE h, struct wim_inode *inode,
536 struct winnt_scan_ctx *ctx)
538 SECURITY_INFORMATION requestedInformation;
539 u8 _buf[4096] _aligned_attribute(8);
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.
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
557 * Older versions of Windows tolerate these new flags being passed in.
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;
567 bufsize = sizeof(_buf);
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:
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
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
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.
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.
598 while (!NT_SUCCESS(status = NtQuerySecurityObject(h,
599 requestedInformation,
600 (PSECURITY_DESCRIPTOR)buf,
605 case STATUS_BUFFER_TOO_SMALL:
606 wimlib_assert(buf == _buf);
607 buf = MALLOC(len_needed);
609 status = STATUS_NO_MEMORY;
612 bufsize = len_needed;
614 case STATUS_PRIVILEGE_NOT_HELD:
615 case STATUS_ACCESS_DENIED:
616 if (ctx->params->add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
618 /* Permission denied in STRICT_ACLS mode, or
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);
630 /* Fake success (useful when capturing as
631 * non-Administrator). */
632 ctx->num_get_sd_access_denied++;
633 status = STATUS_SUCCESS;
638 /* We can get a length of 0 with Samba. Assume that means "no security
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;
649 if (unlikely(buf != _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;
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)
664 FILE_OBJECTID_BUFFER buffer;
668 if (!(ctx->vol_flags & FILE_SUPPORTS_OBJECT_IDS))
671 status = winnt_fsctl(h, FSCTL_GET_OBJECT_ID, NULL, 0,
672 &buffer, sizeof(buffer), &len);
674 if (status == STATUS_OBJECTID_NOT_FOUND) /* No object ID */
677 if (status == STATUS_INVALID_DEVICE_REQUEST ||
678 status == STATUS_NOT_SUPPORTED /* Samba volume, WinXP */) {
679 /* The filesystem claimed to support object IDs, but we can't
680 * actually read them. This happens with Samba. */
681 ctx->vol_flags &= ~FILE_SUPPORTS_OBJECT_IDS;
685 if (!NT_SUCCESS(status)) {
686 winnt_error(status, L"\"%ls\": Can't read object ID",
687 printable_path(ctx));
688 return WIMLIB_ERR_STAT;
691 if (len == 0) /* No object ID (for directories) */
694 if (!inode_set_object_id(inode, &buffer, len))
695 return WIMLIB_ERR_NOMEM;
700 /* Load a file's extended attributes into the corresponding WIM inode. */
701 static noinline_for_stack int
702 winnt_load_xattrs(HANDLE h, struct wim_inode *inode,
703 struct winnt_scan_ctx *ctx, u32 ea_size)
705 IO_STATUS_BLOCK iosb;
707 u8 _buf[1024] _aligned_attribute(4);
709 const FILE_FULL_EA_INFORMATION *ea;
710 struct wim_xattr_entry *entry;
715 * EaSize from FILE_EA_INFORMATION is apparently supposed to give the
716 * size of the buffer required for NtQueryEaFile(), but it doesn't
717 * actually work correctly; it can be off by about 4 bytes per xattr.
719 * So just start out by doubling the advertised size, and also handle
720 * STATUS_BUFFER_OVERFLOW just in case.
723 if (unlikely(ea_size * 2 < ea_size))
724 ea_size = UINT32_MAX;
727 if (unlikely(ea_size > sizeof(_buf))) {
728 buf = MALLOC(ea_size);
730 if (ea_size >= (1 << 20)) {
731 WARNING("\"%ls\": EaSize was extremely large (%u)",
732 printable_path(ctx), ea_size);
734 return WIMLIB_ERR_NOMEM;
738 status = NtQueryEaFile(h, &iosb, buf, ea_size,
739 FALSE, NULL, 0, NULL, TRUE);
741 if (unlikely(!NT_SUCCESS(status))) {
742 if (status == STATUS_BUFFER_OVERFLOW) {
749 if (status == STATUS_NO_EAS_ON_FILE) {
751 * FILE_EA_INFORMATION.EaSize was nonzero so this
752 * shouldn't happen, but just in case...
757 winnt_error(status, L"\"%ls\": Can't read extended attributes",
758 printable_path(ctx));
759 ret = WIMLIB_ERR_STAT;
763 ea = (const FILE_FULL_EA_INFORMATION *)buf;
764 entry = (struct wim_xattr_entry *)buf;
767 * wim_xattr_entry is not larger than FILE_FULL_EA_INFORMATION,
768 * so we can reuse the same buffer by overwriting the
769 * FILE_FULL_EA_INFORMATION with the wim_xattr_entry in-place.
771 FILE_FULL_EA_INFORMATION _ea;
773 STATIC_ASSERT(offsetof(struct wim_xattr_entry, name) <=
774 offsetof(FILE_FULL_EA_INFORMATION, EaName));
775 wimlib_assert((u8 *)entry <= (const u8 *)ea);
777 memcpy(&_ea, ea, sizeof(_ea));
779 entry->value_len = cpu_to_le16(_ea.EaValueLength);
780 entry->name_len = _ea.EaNameLength;
781 entry->flags = _ea.Flags;
782 memmove(entry->name, ea->EaName, _ea.EaNameLength);
783 entry->name[_ea.EaNameLength] = '\0';
784 memmove(&entry->name[_ea.EaNameLength + 1],
785 &ea->EaName[_ea.EaNameLength + 1], _ea.EaValueLength);
786 entry = (struct wim_xattr_entry *)
787 &entry->name[_ea.EaNameLength + 1 + _ea.EaValueLength];
788 if (_ea.NextEntryOffset == 0)
790 ea = (const FILE_FULL_EA_INFORMATION *)
791 ((const u8 *)ea + _ea.NextEntryOffset);
793 wimlib_assert((u8 *)entry - buf <= ea_size);
795 ret = WIMLIB_ERR_NOMEM;
796 if (!inode_set_xattrs(inode, buf, (u8 *)entry - buf))
800 if (unlikely(buf != _buf))
806 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
808 const wchar_t *relative_path,
809 size_t relative_path_nchars,
810 const wchar_t *filename,
811 struct winnt_scan_ctx *ctx);
814 winnt_recurse_directory(HANDLE h,
815 struct wim_dentry *parent,
816 struct winnt_scan_ctx *ctx)
819 const size_t bufsize = 8192;
820 IO_STATUS_BLOCK iosb;
824 buf = MALLOC(bufsize);
826 return WIMLIB_ERR_NOMEM;
828 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
829 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
831 while (NT_SUCCESS(status = NtQueryDirectoryFile(h, NULL, NULL, NULL,
833 FileNamesInformation,
834 FALSE, NULL, FALSE)))
836 const FILE_NAMES_INFORMATION *info = buf;
838 if (!should_ignore_filename(info->FileName,
839 info->FileNameLength / 2))
841 struct wim_dentry *child;
842 size_t orig_path_nchars;
843 const wchar_t *filename;
845 ret = WIMLIB_ERR_NOMEM;
846 filename = pathbuf_append_name(ctx->params,
848 info->FileNameLength / 2,
853 ret = winnt_build_dentry_tree_recursive(
857 info->FileNameLength / 2,
861 pathbuf_truncate(ctx->params, orig_path_nchars);
865 attach_scanned_tree(parent, child,
866 ctx->params->blob_table);
868 if (info->NextEntryOffset == 0)
870 info = (const FILE_NAMES_INFORMATION *)
871 ((const u8 *)info + info->NextEntryOffset);
875 if (unlikely(status != STATUS_NO_MORE_FILES)) {
876 winnt_error(status, L"\"%ls\": Can't read directory",
877 printable_path(ctx));
878 ret = WIMLIB_ERR_READ;
885 /* Reparse point fixup status code */
886 #define RP_FIXED (-1)
889 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
892 IO_STATUS_BLOCK iosb;
893 FILE_INTERNAL_INFORMATION int_info;
894 FILE_FS_VOLUME_INFORMATION vol_info;
896 status = NtQueryInformationFile(h, &iosb, &int_info, sizeof(int_info),
897 FileInternalInformation);
898 if (!NT_SUCCESS(status))
901 if (int_info.IndexNumber.QuadPart != ino)
904 status = NtQueryVolumeInformationFile(h, &iosb,
905 &vol_info, sizeof(vol_info),
906 FileFsVolumeInformation);
907 if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
910 if (iosb.Information <
911 offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
912 sizeof(vol_info.VolumeSerialNumber))
915 return (vol_info.VolumeSerialNumber == dev);
919 * This is the Windows equivalent of unix_relativize_link_target(); see there
920 * for general details. This version works with an "absolute" Windows link
921 * target, specified from the root of the Windows kernel object namespace. Note
922 * that we have to open directories with a trailing slash when present because
923 * \??\E: opens the E: device itself and not the filesystem root directory.
925 static const wchar_t *
926 winnt_relativize_link_target(const wchar_t *target, size_t target_nbytes,
930 OBJECT_ATTRIBUTES attr;
931 IO_STATUS_BLOCK iosb;
933 const wchar_t *target_end;
936 target_end = target + (target_nbytes / sizeof(wchar_t));
939 if (target_end == target)
942 /* No leading slash??? */
943 if (target[0] != L'\\')
947 if ((target_end - target) >= 2 &&
948 target[0] == L'\\' && target[1] == L'\\')
951 attr.Length = sizeof(attr);
952 attr.RootDirectory = NULL;
953 attr.ObjectName = &name;
955 attr.SecurityDescriptor = NULL;
956 attr.SecurityQualityOfService = NULL;
958 name.Buffer = (wchar_t *)target;
963 const wchar_t *orig_p = p;
965 /* Skip non-backslashes */
966 while (p != target_end && *p != L'\\')
969 /* Skip backslashes */
970 while (p != target_end && *p == L'\\')
973 /* Append path component */
974 name.Length += (p - orig_p) * sizeof(wchar_t);
975 name.MaximumLength = name.Length;
977 /* Try opening the file */
978 status = NtOpenFile(&h,
979 FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
982 FILE_SHARE_VALID_FLAGS,
983 FILE_OPEN_FOR_BACKUP_INTENT);
985 if (NT_SUCCESS(status)) {
986 /* Reset root directory */
987 if (attr.RootDirectory)
988 NtClose(attr.RootDirectory);
989 attr.RootDirectory = h;
990 name.Buffer = (wchar_t *)p;
993 if (file_has_ino_and_dev(h, ino, dev))
994 goto out_close_root_dir;
996 } while (p != target_end);
1001 if (attr.RootDirectory)
1002 NtClose(attr.RootDirectory);
1003 while (p > target && *(p - 1) == L'\\')
1009 winnt_rpfix_progress(struct scan_params *params,
1010 const struct link_reparse_point *link, int scan_status)
1012 size_t print_name_nchars = link->print_name_nbytes / sizeof(wchar_t);
1013 wchar_t print_name0[print_name_nchars + 1];
1015 wmemcpy(print_name0, link->print_name, print_name_nchars);
1016 print_name0[print_name_nchars] = L'\0';
1018 params->progress.scan.symlink_target = print_name0;
1019 return do_scan_progress(params, scan_status, NULL);
1023 winnt_try_rpfix(struct reparse_buffer_disk *rpbuf, u16 *rpbuflen_p,
1024 struct scan_params *params)
1026 struct link_reparse_point link;
1027 const wchar_t *rel_target;
1030 if (parse_link_reparse_point(rpbuf, *rpbuflen_p, &link)) {
1031 /* Couldn't understand the reparse data; don't do the fixup. */
1036 * Don't do reparse point fixups on relative symbolic links.
1038 * On Windows, a relative symbolic link is supposed to be identifiable
1039 * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
1040 * SYMBOLIC_LINK_RELATIVE. We will use this information, although this
1041 * may not always do what the user expects, since drive-relative
1042 * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
1043 * set, in addition to truly relative symbolic links such as "Users" or
1044 * "Users\Public". However, WIMGAPI (as of Windows 8.1) has this same
1047 * Otherwise, as far as I can tell, the targets of symbolic links that
1048 * are NOT relative, as well as junctions (note: a mountpoint is the
1049 * sames thing as a junction), must be NT namespace paths, for example:
1051 * - \??\e:\Users\Public
1052 * - \DosDevices\e:\Users\Public
1053 * - \Device\HardDiskVolume4\Users\Public
1054 * - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
1055 * - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
1057 if (link_is_relative_symlink(&link))
1060 rel_target = winnt_relativize_link_target(link.substitute_name,
1061 link.substitute_name_nbytes,
1062 params->capture_root_ino,
1063 params->capture_root_dev);
1065 if (rel_target == link.substitute_name) {
1066 /* Target points outside of the tree being captured or had an
1067 * unrecognized path format. Don't adjust it. */
1068 return winnt_rpfix_progress(params, &link,
1069 WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK);
1072 /* We have an absolute target pointing within the directory being
1073 * captured. @rel_target is the suffix of the link target that is the
1074 * part relative to the directory being captured.
1076 * We will cut off the prefix before this part (which is the path to the
1077 * directory being captured) and add a dummy prefix. Since the process
1078 * will need to be reversed when applying the image, it doesn't matter
1079 * what exactly the prefix is, as long as it looks like an absolute
1082 static const wchar_t prefix[6] = L"\\??\\X:";
1083 static const size_t num_unprintable_chars = 4;
1085 size_t rel_target_nbytes =
1086 link.substitute_name_nbytes - ((const u8 *)rel_target -
1087 (const u8 *)link.substitute_name);
1089 wchar_t tmp[(sizeof(prefix) + rel_target_nbytes) / sizeof(wchar_t)];
1091 memcpy(tmp, prefix, sizeof(prefix));
1092 memcpy(tmp + ARRAY_LEN(prefix), rel_target, rel_target_nbytes);
1094 link.substitute_name = tmp;
1095 link.substitute_name_nbytes = sizeof(tmp);
1097 link.print_name = link.substitute_name + num_unprintable_chars;
1098 link.print_name_nbytes = link.substitute_name_nbytes -
1099 (num_unprintable_chars * sizeof(wchar_t));
1101 if (make_link_reparse_point(&link, rpbuf, rpbuflen_p))
1104 ret = winnt_rpfix_progress(params, &link,
1105 WIMLIB_SCAN_DENTRY_FIXED_SYMLINK);
1111 /* Load the reparse data of a file into the corresponding WIM inode. If the
1112 * reparse point is a symbolic link or junction with an absolute target and
1113 * RPFIX mode is enabled, then also rewrite its target to be relative to the
1115 static noinline_for_stack int
1116 winnt_load_reparse_data(HANDLE h, struct wim_inode *inode,
1117 struct winnt_scan_ctx *ctx)
1119 struct reparse_buffer_disk rpbuf;
1125 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1126 /* See comment above assign_stream_types_encrypted() */
1127 WARNING("Ignoring reparse data of encrypted file \"%ls\"",
1128 printable_path(ctx));
1132 status = winnt_fsctl(h, FSCTL_GET_REPARSE_POINT,
1133 NULL, 0, &rpbuf, sizeof(rpbuf), &len);
1134 if (!NT_SUCCESS(status)) {
1135 winnt_error(status, L"\"%ls\": Can't get reparse point",
1136 printable_path(ctx));
1137 return WIMLIB_ERR_READLINK;
1142 if (unlikely(rpbuflen < REPARSE_DATA_OFFSET)) {
1143 ERROR("\"%ls\": reparse point buffer is too short",
1144 printable_path(ctx));
1145 return WIMLIB_ERR_INVALID_REPARSE_DATA;
1148 if (le32_to_cpu(rpbuf.rptag) == WIM_IO_REPARSE_TAG_DEDUP) {
1150 * Windows treats Data Deduplication reparse points specially.
1151 * Reads from the unnamed data stream actually return the
1152 * redirected file contents, even with FILE_OPEN_REPARSE_POINT.
1153 * Deduplicated files also cannot be properly restored without
1154 * also restoring the "System Volume Information" directory,
1155 * which wimlib excludes by default. Therefore, the logical
1156 * behavior for us seems to be to ignore the reparse point and
1157 * treat the file as a normal file.
1159 inode->i_attributes &= ~FILE_ATTRIBUTE_REPARSE_POINT;
1163 if (ctx->params->add_flags & WIMLIB_ADD_FLAG_RPFIX) {
1164 ret = winnt_try_rpfix(&rpbuf, &rpbuflen, ctx->params);
1165 if (ret == RP_FIXED)
1166 inode->i_rp_flags &= ~WIM_RP_FLAG_NOT_FIXED;
1171 inode->i_reparse_tag = le32_to_cpu(rpbuf.rptag);
1172 inode->i_rp_reserved = le16_to_cpu(rpbuf.rpreserved);
1174 if (!inode_add_stream_with_data(inode,
1175 STREAM_TYPE_REPARSE_POINT,
1178 rpbuflen - REPARSE_DATA_OFFSET,
1179 ctx->params->blob_table))
1180 return WIMLIB_ERR_NOMEM;
1186 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
1189 *(u64*)_size_ret += len;
1190 return ERROR_SUCCESS;
1194 win32_get_encrypted_file_size(const wchar_t *path, bool is_dir, u64 *size_ret)
1202 flags |= CREATE_FOR_DIR;
1204 err = OpenEncryptedFileRaw(path, flags, &file_ctx);
1205 if (err != ERROR_SUCCESS) {
1207 L"Failed to open encrypted file \"%ls\" for raw read",
1209 return WIMLIB_ERR_OPEN;
1212 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
1213 size_ret, file_ctx);
1214 if (err != ERROR_SUCCESS) {
1216 L"Failed to read raw encrypted data from \"%ls\"",
1218 ret = WIMLIB_ERR_READ;
1222 CloseEncryptedFileRaw(file_ctx);
1227 winnt_scan_efsrpc_raw_data(struct wim_inode *inode,
1228 struct winnt_scan_ctx *ctx)
1230 wchar_t *path = ctx->params->cur_path;
1231 size_t path_nchars = ctx->params->cur_path_nchars;
1232 const bool is_dir = (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY);
1233 struct windows_file *windows_file;
1237 /* OpenEncryptedFileRaw() expects a Win32 name. */
1238 wimlib_assert(!wmemcmp(path, L"\\??\\", 4));
1241 ret = win32_get_encrypted_file_size(path, is_dir, &size);
1245 /* Empty EFSRPC data does not make sense */
1246 wimlib_assert(size != 0);
1248 windows_file = alloc_windows_file(path, path_nchars, NULL, 0,
1249 ctx->snapshot, true);
1250 ret = add_stream(inode, windows_file, size, STREAM_TYPE_EFSRPC_RAW_DATA,
1251 NO_STREAM_NAME, ctx->params->unhashed_blobs);
1258 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1259 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
1261 const wchar_t *sep, *type, *end;
1263 /* The stream name should be returned as :NAME:TYPE */
1264 if (raw_stream_name_nchars < 1)
1266 if (raw_stream_name[0] != L':')
1270 raw_stream_name_nchars--;
1272 end = raw_stream_name + raw_stream_name_nchars;
1274 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
1279 if (end - type != 5)
1282 if (wmemcmp(type, L"$DATA", 5))
1285 *stream_name_ret = raw_stream_name;
1286 *stream_name_nchars_ret = sep - raw_stream_name;
1291 winnt_scan_data_stream(wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1292 u64 stream_size, struct wim_inode *inode,
1293 struct winnt_scan_ctx *ctx)
1295 wchar_t *stream_name;
1296 size_t stream_name_nchars;
1297 struct windows_file *windows_file;
1299 /* Given the raw stream name (which is something like
1300 * :streamname:$DATA), extract just the stream name part (streamname).
1301 * Ignore any non-$DATA streams. */
1302 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
1303 (const wchar_t **)&stream_name,
1304 &stream_name_nchars))
1307 stream_name[stream_name_nchars] = L'\0';
1309 windows_file = alloc_windows_file(ctx->params->cur_path,
1310 ctx->params->cur_path_nchars,
1311 stream_name, stream_name_nchars,
1312 ctx->snapshot, false);
1313 return add_stream(inode, windows_file, stream_size, STREAM_TYPE_DATA,
1314 stream_name, ctx->params->unhashed_blobs);
1318 * Load information about the data streams of an open file into a WIM inode.
1320 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
1321 * and FindNextStream(). This is done for two reasons:
1323 * - FindFirstStream() opens its own handle to the file or directory and
1324 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
1325 * causing access denied errors on certain files (even when running as the
1327 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
1328 * and later, whereas the stream support in NtQueryInformationFile() was
1329 * already present in Windows XP.
1331 static noinline_for_stack int
1332 winnt_scan_data_streams(HANDLE h, struct wim_inode *inode, u64 file_size,
1333 struct winnt_scan_ctx *ctx)
1336 u8 _buf[4096] _aligned_attribute(8);
1339 IO_STATUS_BLOCK iosb;
1341 FILE_STREAM_INFORMATION *info;
1344 bufsize = sizeof(_buf);
1346 if (!(ctx->vol_flags & FILE_NAMED_STREAMS))
1349 /* Get a buffer containing the stream information. */
1350 while (!NT_SUCCESS(status = NtQueryInformationFile(h,
1354 FileStreamInformation)))
1358 case STATUS_BUFFER_OVERFLOW:
1364 newbuf = MALLOC(bufsize);
1366 newbuf = REALLOC(buf, bufsize);
1368 ret = WIMLIB_ERR_NOMEM;
1374 case STATUS_NOT_IMPLEMENTED:
1375 case STATUS_NOT_SUPPORTED:
1376 case STATUS_INVALID_INFO_CLASS:
1380 L"\"%ls\": Failed to query stream information",
1381 printable_path(ctx));
1382 ret = WIMLIB_ERR_READ;
1387 if (iosb.Information == 0) {
1388 /* No stream information. */
1393 /* Parse one or more stream information structures. */
1394 info = (FILE_STREAM_INFORMATION *)buf;
1396 /* Load the stream information. */
1397 ret = winnt_scan_data_stream(info->StreamName,
1398 info->StreamNameLength / 2,
1399 info->StreamSize.QuadPart,
1404 if (info->NextEntryOffset == 0) {
1405 /* No more stream information. */
1408 /* Advance to next stream information. */
1409 info = (FILE_STREAM_INFORMATION *)
1410 ((u8 *)info + info->NextEntryOffset);
1416 /* The volume does not support named streams. Only capture the unnamed
1418 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1419 FILE_ATTRIBUTE_REPARSE_POINT))
1426 wchar_t stream_name[] = L"::$DATA";
1427 ret = winnt_scan_data_stream(stream_name, 7, file_size,
1431 /* Free buffer if allocated on heap. */
1432 if (unlikely(buf != _buf))
1438 extract_starting_lcn(const RETRIEVAL_POINTERS_BUFFER *extents)
1440 if (extents->ExtentCount < 1)
1443 return extents->Extents[0].Lcn.QuadPart;
1446 static noinline_for_stack u64
1447 get_sort_key(HANDLE h)
1449 STARTING_VCN_INPUT_BUFFER in = { .StartingVcn.QuadPart = 0 };
1450 RETRIEVAL_POINTERS_BUFFER out;
1452 if (!NT_SUCCESS(winnt_fsctl(h, FSCTL_GET_RETRIEVAL_POINTERS,
1453 &in, sizeof(in), &out, sizeof(out), NULL)))
1456 return extract_starting_lcn(&out);
1460 set_sort_key(struct wim_inode *inode, u64 sort_key)
1462 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1463 struct wim_inode_stream *strm = &inode->i_streams[i];
1464 struct blob_descriptor *blob = stream_blob_resolved(strm);
1465 if (blob && blob->blob_location == BLOB_IN_WINDOWS_FILE)
1466 blob->windows_file->sort_key = sort_key;
1471 should_try_to_use_wimboot_hash(const struct wim_inode *inode,
1472 const struct winnt_scan_ctx *ctx)
1474 /* Directories and encrypted files aren't valid for external backing. */
1475 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1476 FILE_ATTRIBUTE_ENCRYPTED))
1479 /* If the file is a reparse point, then try the hash fixup if it's a WOF
1480 * reparse point and we're in WIMBOOT mode. Otherwise, try the hash
1481 * fixup if WOF may be attached. */
1482 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1483 return (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_WOF) &&
1484 (ctx->params->add_flags & WIMLIB_ADD_FLAG_WIMBOOT);
1485 return !ctx->wof_not_attached;
1489 * This function implements an optimization for capturing files from a
1490 * filesystem with a backing WIM(s). If a file is WIM-backed, then we can
1491 * retrieve the SHA-1 message digest of its original contents from its reparse
1492 * point. This may eliminate the need to read the file's data and/or allow the
1493 * file's data to be immediately deduplicated with existing data in the WIM.
1495 * If WOF is attached, then this function is merely an optimization, but
1496 * potentially a very effective one. If WOF is detached, then this function
1497 * really causes WIM-backed files to be, effectively, automatically
1498 * "dereferenced" when possible; the unnamed data stream is updated to reference
1499 * the original contents and the reparse point is removed.
1501 * This function returns 0 if the fixup succeeded or was intentionally not
1502 * executed. Otherwise it returns an error code.
1504 static noinline_for_stack int
1505 try_to_use_wimboot_hash(HANDLE h, struct wim_inode *inode,
1506 struct winnt_scan_ctx *ctx)
1508 struct blob_table *blob_table = ctx->params->blob_table;
1509 struct wim_inode_stream *reparse_strm = NULL;
1510 struct wim_inode_stream *strm;
1511 struct blob_descriptor *blob;
1512 u8 hash[SHA1_HASH_SIZE];
1515 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1516 struct reparse_buffer_disk rpbuf;
1518 struct wof_external_info wof_info;
1519 struct wim_provider_rpdata wim_info;
1520 } *rpdata = (void *)rpbuf.rpdata;
1521 struct blob_descriptor *reparse_blob;
1523 /* The file has a WOF reparse point, so WOF must be detached.
1524 * We can read the reparse point directly. */
1525 ctx->wof_not_attached = true;
1526 reparse_strm = inode_get_unnamed_stream(inode, STREAM_TYPE_REPARSE_POINT);
1527 reparse_blob = stream_blob_resolved(reparse_strm);
1529 if (!reparse_blob || reparse_blob->size < sizeof(*rpdata))
1530 return 0; /* Not a WIM-backed file */
1532 ret = read_blob_into_buf(reparse_blob, rpdata);
1536 if (rpdata->wof_info.version != WOF_CURRENT_VERSION ||
1537 rpdata->wof_info.provider != WOF_PROVIDER_WIM ||
1538 rpdata->wim_info.version != 2)
1539 return 0; /* Not a WIM-backed file */
1541 /* Okay, this is a WIM backed file. Get its SHA-1 hash. */
1542 copy_hash(hash, rpdata->wim_info.unnamed_data_stream_hash);
1545 struct wof_external_info wof_info;
1546 struct wim_provider_external_info wim_info;
1550 /* WOF may be attached. Try reading this file's external
1552 status = winnt_fsctl(h, FSCTL_GET_EXTERNAL_BACKING,
1553 NULL, 0, &out, sizeof(out), NULL);
1555 /* Is WOF not attached? */
1556 if (status == STATUS_INVALID_DEVICE_REQUEST ||
1557 status == STATUS_NOT_SUPPORTED) {
1558 ctx->wof_not_attached = true;
1562 /* Is this file not externally backed? */
1563 if (status == STATUS_OBJECT_NOT_EXTERNALLY_BACKED)
1566 /* Does this file have an unknown type of external backing that
1567 * needed a larger information buffer? */
1568 if (status == STATUS_BUFFER_TOO_SMALL)
1571 /* Was there some other failure? */
1572 if (status != STATUS_SUCCESS) {
1574 L"\"%ls\": FSCTL_GET_EXTERNAL_BACKING failed",
1575 printable_path(ctx));
1576 return WIMLIB_ERR_STAT;
1579 /* Is this file backed by a WIM? */
1580 if (out.wof_info.version != WOF_CURRENT_VERSION ||
1581 out.wof_info.provider != WOF_PROVIDER_WIM ||
1582 out.wim_info.version != WIM_PROVIDER_CURRENT_VERSION)
1585 /* Okay, this is a WIM backed file. Get its SHA-1 hash. */
1586 copy_hash(hash, out.wim_info.unnamed_data_stream_hash);
1589 /* If the file's unnamed data stream is nonempty, then fill in its hash
1590 * and deduplicate it if possible.
1592 * With WOF detached, we require that the blob *must* de-duplicable for
1593 * any action can be taken, since without WOF we can't fall back to
1594 * getting the "dereferenced" data by reading the stream (the real
1595 * stream is sparse and contains all zeroes). */
1596 strm = inode_get_unnamed_data_stream(inode);
1597 if (strm && (blob = stream_blob_resolved(strm))) {
1598 struct blob_descriptor **back_ptr;
1600 if (reparse_strm && !lookup_blob(blob_table, hash))
1602 back_ptr = retrieve_pointer_to_unhashed_blob(blob);
1603 copy_hash(blob->hash, hash);
1604 if (after_blob_hashed(blob, back_ptr, blob_table) != blob)
1605 free_blob_descriptor(blob);
1608 /* Remove the reparse point, if present. */
1610 inode_remove_stream(inode, reparse_strm, blob_table);
1611 inode->i_attributes &= ~(FILE_ATTRIBUTE_REPARSE_POINT |
1612 FILE_ATTRIBUTE_SPARSE_FILE);
1613 if (inode->i_attributes == 0)
1614 inode->i_attributes = FILE_ATTRIBUTE_NORMAL;
1624 u64 last_write_time;
1625 u64 last_access_time;
1631 static noinline_for_stack NTSTATUS
1632 get_file_info(HANDLE h, struct file_info *info)
1634 IO_STATUS_BLOCK iosb;
1636 FILE_ALL_INFORMATION all_info;
1638 status = NtQueryInformationFile(h, &iosb, &all_info, sizeof(all_info),
1639 FileAllInformation);
1641 if (unlikely(!NT_SUCCESS(status) && status != STATUS_BUFFER_OVERFLOW))
1644 info->attributes = all_info.BasicInformation.FileAttributes;
1645 info->num_links = all_info.StandardInformation.NumberOfLinks;
1646 info->creation_time = all_info.BasicInformation.CreationTime.QuadPart;
1647 info->last_write_time = all_info.BasicInformation.LastWriteTime.QuadPart;
1648 info->last_access_time = all_info.BasicInformation.LastAccessTime.QuadPart;
1649 info->ino = all_info.InternalInformation.IndexNumber.QuadPart;
1650 info->end_of_file = all_info.StandardInformation.EndOfFile.QuadPart;
1651 info->ea_size = all_info.EaInformation.EaSize;
1652 return STATUS_SUCCESS;
1656 get_volume_information(HANDLE h, struct winnt_scan_ctx *ctx)
1658 u8 _attr_info[sizeof(FILE_FS_ATTRIBUTE_INFORMATION) + 128] _aligned_attribute(8);
1659 FILE_FS_ATTRIBUTE_INFORMATION *attr_info = (void *)_attr_info;
1660 FILE_FS_VOLUME_INFORMATION vol_info;
1661 struct file_info file_info;
1662 IO_STATUS_BLOCK iosb;
1665 /* Get volume flags */
1666 status = NtQueryVolumeInformationFile(h, &iosb, attr_info,
1668 FileFsAttributeInformation);
1669 if (NT_SUCCESS(status)) {
1670 ctx->vol_flags = attr_info->FileSystemAttributes;
1671 ctx->is_ntfs = (attr_info->FileSystemNameLength == 4 * sizeof(wchar_t)) &&
1672 !wmemcmp(attr_info->FileSystemName, L"NTFS", 4);
1674 winnt_warning(status, L"\"%ls\": Can't get volume attributes",
1675 printable_path(ctx));
1678 /* Get volume ID. */
1679 status = NtQueryVolumeInformationFile(h, &iosb, &vol_info,
1681 FileFsVolumeInformation);
1682 if ((NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW) &&
1683 (iosb.Information >= offsetof(FILE_FS_VOLUME_INFORMATION,
1684 VolumeSerialNumber) +
1685 sizeof(vol_info.VolumeSerialNumber)))
1687 ctx->params->capture_root_dev = vol_info.VolumeSerialNumber;
1689 winnt_warning(status, L"\"%ls\": Can't get volume ID",
1690 printable_path(ctx));
1693 /* Get inode number. */
1694 status = get_file_info(h, &file_info);
1695 if (NT_SUCCESS(status)) {
1696 ctx->params->capture_root_ino = file_info.ino;
1698 winnt_warning(status, L"\"%ls\": Can't get file information",
1699 printable_path(ctx));
1704 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1706 const wchar_t *relative_path,
1707 size_t relative_path_nchars,
1708 const wchar_t *filename,
1709 struct winnt_scan_ctx *ctx)
1711 struct wim_dentry *root = NULL;
1712 struct wim_inode *inode = NULL;
1716 struct file_info file_info;
1719 ret = try_exclude(ctx->params);
1720 if (unlikely(ret < 0)) /* Excluded? */
1722 if (unlikely(ret > 0)) /* Error? */
1725 /* Open the file with permission to read metadata. Although we will
1726 * later need a handle with FILE_LIST_DIRECTORY permission (or,
1727 * equivalently, FILE_READ_DATA; they're the same numeric value) if the
1728 * file is a directory, it can significantly slow things down to request
1729 * this permission on all nondirectories. Perhaps it causes Windows to
1730 * start prefetching the file contents... */
1731 status = winnt_openat(cur_dir, relative_path, relative_path_nchars,
1732 FILE_READ_ATTRIBUTES | FILE_READ_EA |
1733 READ_CONTROL | ACCESS_SYSTEM_SECURITY,
1735 if (unlikely(!NT_SUCCESS(status))) {
1736 if (status == STATUS_DELETE_PENDING) {
1737 WARNING("\"%ls\": Deletion pending; skipping file",
1738 printable_path(ctx));
1742 if (status == STATUS_SHARING_VIOLATION) {
1743 ERROR("Can't open \"%ls\":\n"
1744 " File is in use by another process! "
1745 "Consider using snapshot (VSS) mode.",
1746 printable_path(ctx));
1747 ret = WIMLIB_ERR_OPEN;
1750 winnt_error(status, L"\"%ls\": Can't open file",
1751 printable_path(ctx));
1752 if (status == STATUS_FVE_LOCKED_VOLUME)
1753 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1755 ret = WIMLIB_ERR_OPEN;
1759 /* Get information about the file. */
1760 status = get_file_info(h, &file_info);
1761 if (!NT_SUCCESS(status)) {
1762 winnt_error(status, L"\"%ls\": Can't get file information",
1763 printable_path(ctx));
1764 ret = WIMLIB_ERR_STAT;
1768 /* Create a WIM dentry with an associated inode, which may be shared.
1770 * However, we need to explicitly check for directories and files with
1771 * only 1 link and refuse to hard link them. This is because Windows
1772 * has a bug where it can return duplicate File IDs for files and
1773 * directories on the FAT filesystem.
1775 * Since we don't follow mount points on Windows, we don't need to query
1776 * the volume ID per-file. Just once, for the root, is enough. But we
1777 * can't simply pass 0, because then there could be inode collisions
1778 * among multiple calls to win32_build_dentry_tree() that are scanning
1779 * files on different volumes. */
1780 ret = inode_table_new_dentry(ctx->params->inode_table,
1783 ctx->params->capture_root_dev,
1784 (file_info.num_links <= 1),
1789 /* Get the short (DOS) name of the file. */
1790 status = winnt_get_short_name(h, root);
1792 /* If we can't read the short filename for any reason other than
1793 * out-of-memory, just ignore the error and assume the file has no short
1794 * name. This shouldn't be an issue, since the short names are
1795 * essentially obsolete anyway. */
1796 if (unlikely(status == STATUS_NO_MEMORY)) {
1797 ret = WIMLIB_ERR_NOMEM;
1801 inode = root->d_inode;
1803 if (inode->i_nlink > 1) {
1804 /* Shared inode (hard link); skip reading per-inode information.
1809 inode->i_attributes = file_info.attributes;
1810 inode->i_creation_time = file_info.creation_time;
1811 inode->i_last_write_time = file_info.last_write_time;
1812 inode->i_last_access_time = file_info.last_access_time;
1814 /* Get the file's security descriptor, unless we are capturing in
1815 * NO_ACLS mode or the volume does not support security descriptors. */
1816 if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1817 && (ctx->vol_flags & FILE_PERSISTENT_ACLS))
1819 ret = winnt_load_security_descriptor(h, inode, ctx);
1824 /* Get the file's object ID. */
1825 ret = winnt_load_object_id(h, inode, ctx);
1829 /* Get the file's extended attributes. */
1830 if (unlikely(file_info.ea_size != 0)) {
1831 ret = winnt_load_xattrs(h, inode, ctx, file_info.ea_size);
1836 /* If this is a reparse point, load the reparse data. */
1837 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1838 ret = winnt_load_reparse_data(h, inode, ctx);
1843 sort_key = get_sort_key(h);
1845 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1846 /* Load information about the raw encrypted data. This is
1847 * needed for any directory or non-directory that has
1848 * FILE_ATTRIBUTE_ENCRYPTED set.
1850 * Note: since OpenEncryptedFileRaw() fails with
1851 * ERROR_SHARING_VIOLATION if there are any open handles to the
1852 * file, we have to close the file and re-open it later if
1856 ret = winnt_scan_efsrpc_raw_data(inode, ctx);
1861 * Load information about data streams (unnamed and named).
1863 * Skip this step for encrypted files, since the data from
1864 * ReadEncryptedFileRaw() already contains all data streams (and
1865 * they do in fact all get restored by WriteEncryptedFileRaw().)
1867 * Note: WIMGAPI (as of Windows 8.1) gets wrong and stores both
1868 * the EFSRPC data and the named data stream(s)...!
1870 ret = winnt_scan_data_streams(h,
1872 file_info.end_of_file,
1878 if (unlikely(should_try_to_use_wimboot_hash(inode, ctx))) {
1879 ret = try_to_use_wimboot_hash(h, inode, ctx);
1884 set_sort_key(inode, sort_key);
1886 if (inode_is_directory(inode)) {
1888 /* Directory: recurse to children. */
1890 /* Re-open the directory with FILE_LIST_DIRECTORY access. */
1895 status = winnt_openat(cur_dir, relative_path,
1896 relative_path_nchars, FILE_LIST_DIRECTORY,
1898 if (!NT_SUCCESS(status)) {
1899 winnt_error(status, L"\"%ls\": Can't open directory",
1900 printable_path(ctx));
1901 ret = WIMLIB_ERR_OPEN;
1904 ret = winnt_recurse_directory(h, root, ctx);
1911 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_OK, inode);
1913 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1917 if (unlikely(ret)) {
1918 free_dentry_tree(root, ctx->params->blob_table);
1920 ret = report_scan_error(ctx->params, ret);
1927 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_ctx *ctx)
1929 if (likely(ctx->num_get_sacl_priv_notheld == 0 &&
1930 ctx->num_get_sd_access_denied == 0))
1933 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1934 if (ctx->num_get_sacl_priv_notheld != 0) {
1935 WARNING("- Could not capture SACL (System Access Control List)\n"
1936 " on %lu files or directories.",
1937 ctx->num_get_sacl_priv_notheld);
1939 if (ctx->num_get_sd_access_denied != 0) {
1940 WARNING("- Could not capture security descriptor at all\n"
1941 " on %lu files or directories.",
1942 ctx->num_get_sd_access_denied);
1944 WARNING("To fully capture all security descriptors, run the program\n"
1945 " with Administrator rights.");
1948 /*----------------------------------------------------------------------------*
1949 * Fast MFT scan implementation *
1950 *----------------------------------------------------------------------------*/
1952 #define ENABLE_FAST_MFT_SCAN 1
1954 #ifdef ENABLE_FAST_MFT_SCAN
1957 u64 StartingCluster;
1962 u64 StartingFileReferenceNumber;
1963 u64 EndingFileReferenceNumber;
1964 } FILE_REFERENCE_RANGE;
1966 /* The FSCTL_QUERY_FILE_LAYOUT ioctl. This ioctl can be used on Windows 8 and
1967 * later to scan the MFT of an NTFS volume. */
1968 #define FSCTL_QUERY_FILE_LAYOUT CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 157, METHOD_NEITHER, FILE_ANY_ACCESS)
1970 /* The input to FSCTL_QUERY_FILE_LAYOUT */
1973 #define QUERY_FILE_LAYOUT_RESTART 0x00000001
1974 #define QUERY_FILE_LAYOUT_INCLUDE_NAMES 0x00000002
1975 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS 0x00000004
1976 #define QUERY_FILE_LAYOUT_INCLUDE_EXTENTS 0x00000008
1977 #define QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO 0x00000010
1978 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED 0x00000020
1980 #define QUERY_FILE_LAYOUT_FILTER_TYPE_NONE 0
1981 #define QUERY_FILE_LAYOUT_FILTER_TYPE_CLUSTERS 1
1982 #define QUERY_FILE_LAYOUT_FILTER_TYPE_FILEID 2
1983 #define QUERY_FILE_LAYOUT_NUM_FILTER_TYPES 3
1987 CLUSTER_RANGE ClusterRanges[1];
1988 FILE_REFERENCE_RANGE FileReferenceRanges[1];
1990 } QUERY_FILE_LAYOUT_INPUT;
1992 /* The header of the buffer returned by FSCTL_QUERY_FILE_LAYOUT */
1995 u32 FirstFileOffset;
1996 #define QUERY_FILE_LAYOUT_SINGLE_INSTANCED 0x00000001
1999 } QUERY_FILE_LAYOUT_OUTPUT;
2001 /* Inode information returned by FSCTL_QUERY_FILE_LAYOUT */
2007 u64 FileReferenceNumber;
2008 u32 FirstNameOffset;
2009 u32 FirstStreamOffset;
2010 u32 ExtraInfoOffset;
2012 } FILE_LAYOUT_ENTRY;
2014 /* Extra inode information returned by FSCTL_QUERY_FILE_LAYOUT */
2026 } FILE_LAYOUT_INFO_ENTRY;
2028 /* Filename (or dentry) information returned by FSCTL_QUERY_FILE_LAYOUT */
2031 #define FILE_LAYOUT_NAME_ENTRY_PRIMARY 0x00000001
2032 #define FILE_LAYOUT_NAME_ENTRY_DOS 0x00000002
2034 u64 ParentFileReferenceNumber;
2037 wchar_t FileName[1];
2038 } FILE_LAYOUT_NAME_ENTRY;
2040 /* Stream information returned by FSCTL_QUERY_FILE_LAYOUT */
2043 u32 NextStreamOffset;
2044 #define STREAM_LAYOUT_ENTRY_IMMOVABLE 0x00000001
2045 #define STREAM_LAYOUT_ENTRY_PINNED 0x00000002
2046 #define STREAM_LAYOUT_ENTRY_RESIDENT 0x00000004
2047 #define STREAM_LAYOUT_ENTRY_NO_CLUSTERS_ALLOCATED 0x00000008
2049 u32 ExtentInformationOffset;
2054 u32 StreamIdentifierLength;
2055 wchar_t StreamIdentifier[1];
2056 } STREAM_LAYOUT_ENTRY;
2060 #define STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS 0x00000001
2061 #define STREAM_EXTENT_ENTRY_ALL_EXTENTS 0x00000002
2064 RETRIEVAL_POINTERS_BUFFER RetrievalPointers;
2065 } ExtentInformation;
2066 } STREAM_EXTENT_ENTRY;
2068 /* Extract the MFT number part of the full inode number */
2069 #define NTFS_MFT_NO(ref) ((ref) & (((u64)1 << 48) - 1))
2071 /* Is the file the root directory of the NTFS volume? The root directory always
2072 * occupies MFT record 5. */
2073 #define NTFS_IS_ROOT_FILE(ino) (NTFS_MFT_NO(ino) == 5)
2075 /* Is the file a special NTFS file, other than the root directory? The special
2076 * files are the first 16 records in the MFT. */
2077 #define NTFS_IS_SPECIAL_FILE(ino) \
2078 (NTFS_MFT_NO(ino) <= 15 && !NTFS_IS_ROOT_FILE(ino))
2080 #define NTFS_SPECIAL_STREAM_OBJECT_ID 0x00000001
2081 #define NTFS_SPECIAL_STREAM_EA 0x00000002
2082 #define NTFS_SPECIAL_STREAM_EA_INFORMATION 0x00000004
2084 /* Intermediate inode structure. This is used to temporarily save information
2085 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_inode'. */
2087 struct avl_tree_node index_node;
2090 u64 last_access_time;
2091 u64 last_write_time;
2097 u32 special_streams;
2098 u32 first_stream_offset;
2099 struct ntfs_dentry *first_child;
2100 wchar_t short_name[13];
2103 /* Intermediate dentry structure. This is used to temporarily save information
2104 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_dentry'. */
2105 struct ntfs_dentry {
2106 u32 offset_from_inode : 31;
2109 /* Note: build_children_lists() replaces 'parent_ino' with
2112 struct ntfs_dentry *next_child;
2117 /* Intermediate stream structure. This is used to temporarily save information
2118 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct
2119 * wim_inode_stream'. */
2120 struct ntfs_stream {
2125 /* Map of all known NTFS inodes, keyed by inode number */
2126 struct ntfs_inode_map {
2127 struct avl_tree_node *root;
2130 #define NTFS_INODE(node) \
2131 avl_tree_entry((node), struct ntfs_inode, index_node)
2133 #define SKIP_ALIGNED(p, size) ((void *)(p) + ALIGN((size), 8))
2135 /* Get a pointer to the first dentry of the inode. */
2136 #define FIRST_DENTRY(ni) SKIP_ALIGNED((ni), sizeof(struct ntfs_inode))
2138 /* Get a pointer to the first stream of the inode. */
2139 #define FIRST_STREAM(ni) ((const void *)ni + ni->first_stream_offset)
2141 /* Advance to the next dentry of the inode. */
2142 #define NEXT_DENTRY(nd) SKIP_ALIGNED((nd), sizeof(struct ntfs_dentry) + \
2143 (wcslen((nd)->name) + 1) * sizeof(wchar_t))
2145 /* Advance to the next stream of the inode. */
2146 #define NEXT_STREAM(ns) SKIP_ALIGNED((ns), sizeof(struct ntfs_stream) + \
2147 (wcslen((ns)->name) + 1) * sizeof(wchar_t))
2150 _avl_cmp_ntfs_inodes(const struct avl_tree_node *node1,
2151 const struct avl_tree_node *node2)
2153 return cmp_u64(NTFS_INODE(node1)->ino, NTFS_INODE(node2)->ino);
2156 /* Adds an NTFS inode to the map. */
2158 ntfs_inode_map_add_inode(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2160 if (avl_tree_insert(&map->root, &ni->index_node, _avl_cmp_ntfs_inodes)) {
2161 WARNING("Inode 0x%016"PRIx64" is a duplicate!", ni->ino);
2166 /* Find an ntfs_inode in the map by inode number. Returns NULL if not found. */
2167 static struct ntfs_inode *
2168 ntfs_inode_map_lookup(struct ntfs_inode_map *map, u64 ino)
2170 struct ntfs_inode tmp;
2171 struct avl_tree_node *res;
2174 res = avl_tree_lookup_node(map->root, &tmp.index_node, _avl_cmp_ntfs_inodes);
2177 return NTFS_INODE(res);
2180 /* Remove an ntfs_inode from the map and free it. */
2182 ntfs_inode_map_remove(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2184 avl_tree_remove(&map->root, &ni->index_node);
2188 /* Free all ntfs_inodes in the map. */
2190 ntfs_inode_map_destroy(struct ntfs_inode_map *map)
2192 struct ntfs_inode *ni;
2194 avl_tree_for_each_in_postorder(ni, map->root, struct ntfs_inode, index_node)
2199 file_has_streams(const FILE_LAYOUT_ENTRY *file)
2201 return (file->FirstStreamOffset != 0) &&
2202 !(file->FileAttributes & FILE_ATTRIBUTE_ENCRYPTED);
2206 is_valid_name_entry(const FILE_LAYOUT_NAME_ENTRY *name)
2208 return name->FileNameLength > 0 &&
2209 name->FileNameLength % 2 == 0 &&
2210 !wmemchr(name->FileName, L'\0', name->FileNameLength / 2) &&
2211 (!(name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) ||
2212 name->FileNameLength <= 24);
2215 /* Validate the FILE_LAYOUT_NAME_ENTRYs of the specified file and compute the
2216 * total length in bytes of the ntfs_dentry structures needed to hold the name
2219 validate_names_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2220 size_t *total_length_ret)
2222 const FILE_LAYOUT_NAME_ENTRY *name =
2223 (const void *)file + file->FirstNameOffset;
2225 size_t num_long_names = 0;
2228 if (unlikely(!is_valid_name_entry(name))) {
2229 ERROR("Invalid FILE_LAYOUT_NAME_ENTRY! "
2230 "FileReferenceNumber=0x%016"PRIx64", "
2231 "FileNameLength=%"PRIu32", "
2232 "FileName=%.*ls, Flags=0x%08"PRIx32,
2233 file->FileReferenceNumber,
2234 name->FileNameLength,
2235 (int)(name->FileNameLength / 2),
2236 name->FileName, name->Flags);
2237 return WIMLIB_ERR_UNSUPPORTED;
2239 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2241 total += ALIGN(sizeof(struct ntfs_dentry) +
2242 name->FileNameLength + sizeof(wchar_t),
2245 if (name->NextNameOffset == 0)
2247 name = (const void *)name + name->NextNameOffset;
2250 if (unlikely(num_long_names == 0)) {
2251 ERROR("Inode 0x%016"PRIx64" has no long names!",
2252 file->FileReferenceNumber);
2253 return WIMLIB_ERR_UNSUPPORTED;
2256 *total_length_ret = total;
2261 is_valid_stream_entry(const STREAM_LAYOUT_ENTRY *stream)
2263 return stream->StreamIdentifierLength % 2 == 0 &&
2264 !wmemchr(stream->StreamIdentifier , L'\0',
2265 stream->StreamIdentifierLength / 2);
2268 /* assumes that 'id' is a wide string literal */
2269 #define stream_has_identifier(stream, id) \
2270 ((stream)->StreamIdentifierLength == sizeof(id) - 2 && \
2271 !memcmp((stream)->StreamIdentifier, id, sizeof(id) - 2))
2273 * If the specified STREAM_LAYOUT_ENTRY represents a DATA stream as opposed to
2274 * some other type of NTFS stream such as a STANDARD_INFORMATION stream, return
2275 * true and set *stream_name_ret and *stream_name_nchars_ret to specify just the
2276 * stream name. For example, ":foo:$DATA" would become "foo" with length 3
2277 * characters. Otherwise return false.
2280 use_stream(const FILE_LAYOUT_ENTRY *file, const STREAM_LAYOUT_ENTRY *stream,
2281 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
2283 const wchar_t *stream_name;
2284 size_t stream_name_nchars;
2286 if (stream->StreamIdentifierLength == 0) {
2287 /* The unnamed data stream may be given as an empty string
2288 * rather than as "::$DATA". Handle it both ways. */
2290 stream_name_nchars = 0;
2291 } else if (!get_data_stream_name(stream->StreamIdentifier,
2292 stream->StreamIdentifierLength / 2,
2293 &stream_name, &stream_name_nchars))
2296 /* Skip the unnamed data stream for directories. */
2297 if (stream_name_nchars == 0 &&
2298 (file->FileAttributes & FILE_ATTRIBUTE_DIRECTORY))
2301 *stream_name_ret = stream_name;
2302 *stream_name_nchars_ret = stream_name_nchars;
2306 /* Validate the STREAM_LAYOUT_ENTRYs of the specified file and compute the total
2307 * length in bytes of the ntfs_stream structures needed to hold the stream
2308 * information. In addition, set *special_streams_ret to a bitmask of special
2309 * stream types that were found. */
2311 validate_streams_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2312 size_t *total_length_ret,
2313 u32 *special_streams_ret)
2315 const STREAM_LAYOUT_ENTRY *stream =
2316 (const void *)file + file->FirstStreamOffset;
2318 u32 special_streams = 0;
2321 const wchar_t *name;
2324 if (unlikely(!is_valid_stream_entry(stream))) {
2325 WARNING("Invalid STREAM_LAYOUT_ENTRY! "
2326 "FileReferenceNumber=0x%016"PRIx64", "
2327 "StreamIdentifierLength=%"PRIu32", "
2328 "StreamIdentifier=%.*ls",
2329 file->FileReferenceNumber,
2330 stream->StreamIdentifierLength,
2331 (int)(stream->StreamIdentifierLength / 2),
2332 stream->StreamIdentifier);
2333 return WIMLIB_ERR_UNSUPPORTED;
2336 if (use_stream(file, stream, &name, &name_nchars)) {
2337 total += ALIGN(sizeof(struct ntfs_stream) +
2338 (name_nchars + 1) * sizeof(wchar_t), 8);
2339 } else if (stream_has_identifier(stream, L"::$OBJECT_ID")) {
2340 special_streams |= NTFS_SPECIAL_STREAM_OBJECT_ID;
2341 } else if (stream_has_identifier(stream, L"::$EA")) {
2342 special_streams |= NTFS_SPECIAL_STREAM_EA;
2343 } else if (stream_has_identifier(stream, L"::$EA_INFORMATION")) {
2344 special_streams |= NTFS_SPECIAL_STREAM_EA_INFORMATION;
2346 if (stream->NextStreamOffset == 0)
2348 stream = (const void *)stream + stream->NextStreamOffset;
2351 *total_length_ret = total;
2352 *special_streams_ret = special_streams;
2357 load_name_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2360 const FILE_LAYOUT_NAME_ENTRY *name =
2361 (const void *)file + file->FirstNameOffset;
2363 struct ntfs_dentry *nd = p;
2364 /* Note that a name may be just a short (DOS) name, just a long
2365 * name, or both a short name and a long name. If there is a
2366 * short name, one name should also be marked as "primary" to
2367 * indicate which long name the short name is associated with.
2368 * Also, there should be at most one short name per inode. */
2369 if (name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) {
2370 memcpy(ni->short_name,
2371 name->FileName, name->FileNameLength);
2372 ni->short_name[name->FileNameLength / 2] = L'\0';
2374 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2376 nd->offset_from_inode = (u8 *)nd - (u8 *)ni;
2377 nd->is_primary = ((name->Flags &
2378 FILE_LAYOUT_NAME_ENTRY_PRIMARY) != 0);
2379 nd->parent_ino = name->ParentFileReferenceNumber;
2380 memcpy(nd->name, name->FileName, name->FileNameLength);
2381 nd->name[name->FileNameLength / 2] = L'\0';
2382 p += ALIGN(sizeof(struct ntfs_dentry) +
2383 name->FileNameLength + sizeof(wchar_t), 8);
2385 if (name->NextNameOffset == 0)
2387 name = (const void *)name + name->NextNameOffset;
2393 load_starting_lcn(const STREAM_LAYOUT_ENTRY *stream)
2395 const STREAM_EXTENT_ENTRY *entry;
2397 if (stream->ExtentInformationOffset == 0)
2400 entry = (const void *)stream + stream->ExtentInformationOffset;
2402 if (!(entry->Flags & STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS))
2405 return extract_starting_lcn(&entry->ExtentInformation.RetrievalPointers);
2409 load_stream_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2412 const STREAM_LAYOUT_ENTRY *stream =
2413 (const void *)file + file->FirstStreamOffset;
2414 const u32 first_stream_offset = (const u8 *)p - (const u8 *)ni;
2416 struct ntfs_stream *ns = p;
2417 const wchar_t *name;
2420 if (use_stream(file, stream, &name, &name_nchars)) {
2421 ni->first_stream_offset = first_stream_offset;
2423 if (name_nchars == 0)
2424 ni->starting_lcn = load_starting_lcn(stream);
2425 ns->size = stream->EndOfFile;
2426 wmemcpy(ns->name, name, name_nchars);
2427 ns->name[name_nchars] = L'\0';
2428 p += ALIGN(sizeof(struct ntfs_stream) +
2429 (name_nchars + 1) * sizeof(wchar_t), 8);
2431 if (stream->NextStreamOffset == 0)
2433 stream = (const void *)stream + stream->NextStreamOffset;
2438 /* Process the information for a file given by FSCTL_QUERY_FILE_LAYOUT. */
2440 load_one_file(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode_map *inode_map)
2442 const FILE_LAYOUT_INFO_ENTRY *info =
2443 (const void *)file + file->ExtraInfoOffset;
2445 struct ntfs_inode *ni;
2449 u32 special_streams = 0;
2451 inode_size = ALIGN(sizeof(struct ntfs_inode), 8);
2453 /* The root file should have no names, and all other files should have
2454 * at least one name. But just in case, we ignore the names of the root
2455 * file, and we ignore any non-root file with no names. */
2456 if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber)) {
2457 if (file->FirstNameOffset == 0)
2459 ret = validate_names_and_compute_total_length(file, &n);
2465 if (file_has_streams(file)) {
2466 ret = validate_streams_and_compute_total_length(file, &n,
2473 /* To save memory, we allocate the ntfs_dentry's and ntfs_stream's in
2474 * the same memory block as their ntfs_inode. */
2475 ni = CALLOC(1, inode_size);
2477 return WIMLIB_ERR_NOMEM;
2479 ni->ino = file->FileReferenceNumber;
2480 ni->attributes = info->BasicInformation.FileAttributes;
2481 ni->creation_time = info->BasicInformation.CreationTime;
2482 ni->last_write_time = info->BasicInformation.LastWriteTime;
2483 ni->last_access_time = info->BasicInformation.LastAccessTime;
2484 ni->security_id = info->SecurityId;
2485 ni->special_streams = special_streams;
2487 p = FIRST_DENTRY(ni);
2489 if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber))
2490 p = load_name_information(file, ni, p);
2492 if (file_has_streams(file))
2493 p = load_stream_information(file, ni, p);
2495 wimlib_assert((u8 *)p - (u8 *)ni == inode_size);
2497 ntfs_inode_map_add_inode(inode_map, ni);
2502 * Quickly find all files on an NTFS volume by using FSCTL_QUERY_FILE_LAYOUT to
2503 * scan the MFT. The NTFS volume is specified by the NT namespace path @path.
2504 * For each file, allocate an 'ntfs_inode' structure for each file and add it to
2505 * 'inode_map' keyed by inode number. Include NTFS special files such as
2506 * $Bitmap (they will be removed later).
2509 load_files_from_mft(const wchar_t *path, struct ntfs_inode_map *inode_map)
2512 QUERY_FILE_LAYOUT_INPUT in = (QUERY_FILE_LAYOUT_INPUT) {
2514 .Flags = QUERY_FILE_LAYOUT_RESTART |
2515 QUERY_FILE_LAYOUT_INCLUDE_NAMES |
2516 QUERY_FILE_LAYOUT_INCLUDE_STREAMS |
2517 QUERY_FILE_LAYOUT_INCLUDE_EXTENTS |
2518 QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO |
2519 QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED,
2520 .FilterType = QUERY_FILE_LAYOUT_FILTER_TYPE_NONE,
2522 size_t outsize = 32768;
2523 QUERY_FILE_LAYOUT_OUTPUT *out = NULL;
2527 status = winnt_open(path, wcslen(path),
2528 FILE_READ_DATA | FILE_READ_ATTRIBUTES, &h);
2529 if (!NT_SUCCESS(status)) {
2530 ret = -1; /* Silently try standard recursive scan instead */
2535 /* Allocate a buffer for the output of the ioctl. */
2536 out = MALLOC(outsize);
2538 ret = WIMLIB_ERR_NOMEM;
2542 /* Execute FSCTL_QUERY_FILE_LAYOUT until it fails. */
2543 while (NT_SUCCESS(status = winnt_fsctl(h,
2544 FSCTL_QUERY_FILE_LAYOUT,
2546 out, outsize, NULL)))
2548 const FILE_LAYOUT_ENTRY *file =
2549 (const void *)out + out->FirstFileOffset;
2551 ret = load_one_file(file, inode_map);
2554 if (file->NextFileOffset == 0)
2556 file = (const void *)file + file->NextFileOffset;
2558 in.Flags &= ~QUERY_FILE_LAYOUT_RESTART;
2561 /* Enlarge the buffer if needed. */
2562 if (status != STATUS_BUFFER_TOO_SMALL)
2568 /* Normally, FSCTL_QUERY_FILE_LAYOUT fails with STATUS_END_OF_FILE after
2569 * all files have been enumerated. */
2570 if (status != STATUS_END_OF_FILE) {
2571 if (status == STATUS_INVALID_DEVICE_REQUEST /* old OS */ ||
2572 status == STATUS_NOT_SUPPORTED /* Samba volume, WinXP */ ||
2573 status == STATUS_INVALID_PARAMETER /* not root directory */ )
2575 /* Silently try standard recursive scan instead */
2579 L"Error enumerating files on volume \"%ls\"",
2581 /* Try standard recursive scan instead */
2582 ret = WIMLIB_ERR_UNSUPPORTED;
2593 /* Build the list of child dentries for each inode in @map. This is done by
2594 * iterating through each name of each inode and adding it to its parent's
2595 * children list. Note that every name should have a parent, i.e. should belong
2596 * to some directory. The root directory does not have any names. */
2598 build_children_lists(struct ntfs_inode_map *map, struct ntfs_inode **root_ret)
2600 struct ntfs_inode *ni;
2602 avl_tree_for_each_in_order(ni, map->root, struct ntfs_inode, index_node)
2604 struct ntfs_dentry *nd;
2607 if (NTFS_IS_ROOT_FILE(ni->ino)) {
2612 n = ni->num_aliases;
2613 nd = FIRST_DENTRY(ni);
2615 struct ntfs_inode *parent;
2617 parent = ntfs_inode_map_lookup(map, nd->parent_ino);
2618 if (unlikely(!parent)) {
2619 ERROR("Parent inode 0x%016"PRIx64" of"
2620 "directory entry \"%ls\" (inode "
2621 "0x%016"PRIx64") was missing from the "
2623 nd->parent_ino, nd->name, ni->ino);
2624 return WIMLIB_ERR_UNSUPPORTED;
2626 nd->next_child = parent->first_child;
2627 parent->first_child = nd;
2630 nd = NEXT_DENTRY(nd);
2636 struct security_map_node {
2637 struct avl_tree_node index_node;
2638 u32 disk_security_id;
2639 u32 wim_security_id;
2642 /* Map from disk security IDs to WIM security IDs */
2643 struct security_map {
2644 struct avl_tree_node *root;
2647 #define SECURITY_MAP_NODE(node) \
2648 avl_tree_entry((node), struct security_map_node, index_node)
2651 _avl_cmp_security_map_nodes(const struct avl_tree_node *node1,
2652 const struct avl_tree_node *node2)
2654 return cmp_u32(SECURITY_MAP_NODE(node1)->disk_security_id,
2655 SECURITY_MAP_NODE(node2)->disk_security_id);
2659 security_map_lookup(struct security_map *map, u32 disk_security_id)
2661 struct security_map_node tmp;
2662 const struct avl_tree_node *res;
2664 if (disk_security_id == 0) /* No on-disk security ID; uncacheable */
2667 tmp.disk_security_id = disk_security_id;
2668 res = avl_tree_lookup_node(map->root, &tmp.index_node,
2669 _avl_cmp_security_map_nodes);
2672 return SECURITY_MAP_NODE(res)->wim_security_id;
2676 security_map_insert(struct security_map *map, u32 disk_security_id,
2677 u32 wim_security_id)
2679 struct security_map_node *node;
2681 if (disk_security_id == 0) /* No on-disk security ID; uncacheable */
2684 node = MALLOC(sizeof(*node));
2686 return WIMLIB_ERR_NOMEM;
2688 node->disk_security_id = disk_security_id;
2689 node->wim_security_id = wim_security_id;
2690 avl_tree_insert(&map->root, &node->index_node,
2691 _avl_cmp_security_map_nodes);
2696 security_map_destroy(struct security_map *map)
2698 struct security_map_node *node;
2700 avl_tree_for_each_in_postorder(node, map->root,
2701 struct security_map_node, index_node)
2706 * Turn our temporary NTFS structures into the final WIM structures:
2708 * ntfs_inode => wim_inode
2709 * ntfs_dentry => wim_dentry
2710 * ntfs_stream => wim_inode_stream
2712 * This also handles things such as exclusions and issuing progress messages.
2713 * It's similar to winnt_build_dentry_tree_recursive(), but this is much faster
2714 * because almost all information we need is already loaded in memory in the
2715 * ntfs_* structures. However, in some cases we still fall back to
2716 * winnt_build_dentry_tree_recursive() and/or opening the file.
2719 generate_wim_structures_recursive(struct wim_dentry **root_ret,
2720 const wchar_t *filename, bool is_primary_name,
2721 struct ntfs_inode *ni,
2722 struct winnt_scan_ctx *ctx,
2723 struct ntfs_inode_map *inode_map,
2724 struct security_map *security_map)
2727 struct wim_dentry *root = NULL;
2728 struct wim_inode *inode = NULL;
2729 const struct ntfs_stream *ns;
2731 /* Completely ignore NTFS special files. */
2732 if (NTFS_IS_SPECIAL_FILE(ni->ino))
2735 /* Fall back to a recursive scan for unhandled cases. Reparse points,
2736 * in particular, can't be properly handled here because a commonly used
2737 * filter driver (WOF) hides reparse points from regular filesystem APIs
2738 * but not from FSCTL_QUERY_FILE_LAYOUT. */
2739 if (ni->attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
2740 FILE_ATTRIBUTE_ENCRYPTED) ||
2741 ni->special_streams != 0)
2743 ret = winnt_build_dentry_tree_recursive(&root,
2745 ctx->params->cur_path,
2746 ctx->params->cur_path_nchars,
2752 /* Test for exclusion based on path. */
2753 ret = try_exclude(ctx->params);
2754 if (unlikely(ret < 0)) /* Excluded? */
2756 if (unlikely(ret > 0)) /* Error? */
2759 /* Create the WIM dentry and possibly a new WIM inode */
2760 ret = inode_table_new_dentry(ctx->params->inode_table, filename,
2761 ni->ino, ctx->params->capture_root_dev,
2766 inode = root->d_inode;
2768 /* Set the short name if needed. */
2769 if (is_primary_name && *ni->short_name) {
2770 size_t nbytes = wcslen(ni->short_name) * sizeof(wchar_t);
2771 root->d_short_name = memdup(ni->short_name,
2772 nbytes + sizeof(wchar_t));
2773 if (!root->d_short_name) {
2774 ret = WIMLIB_ERR_NOMEM;
2777 root->d_short_name_nbytes = nbytes;
2780 if (inode->i_nlink > 1) { /* Already seen this inode? */
2785 /* The file attributes and timestamps were cached from the MFT. */
2786 inode->i_attributes = ni->attributes;
2787 inode->i_creation_time = ni->creation_time;
2788 inode->i_last_write_time = ni->last_write_time;
2789 inode->i_last_access_time = ni->last_access_time;
2791 /* Set the security descriptor if needed. */
2792 if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)) {
2793 /* Look up the WIM security ID that corresponds to the on-disk
2795 s32 wim_security_id =
2796 security_map_lookup(security_map, ni->security_id);
2797 if (likely(wim_security_id >= 0)) {
2798 /* The mapping for this security ID is already cached.*/
2799 inode->i_security_id = wim_security_id;
2804 /* Create a mapping for this security ID and insert it
2805 * into the security map. */
2807 status = winnt_open(ctx->params->cur_path,
2808 ctx->params->cur_path_nchars,
2810 ACCESS_SYSTEM_SECURITY, &h);
2811 if (!NT_SUCCESS(status)) {
2812 winnt_error(status, L"Can't open \"%ls\" to "
2813 "read security descriptor",
2814 printable_path(ctx));
2815 ret = WIMLIB_ERR_OPEN;
2818 ret = winnt_load_security_descriptor(h, inode, ctx);
2823 ret = security_map_insert(security_map, ni->security_id,
2824 inode->i_security_id);
2830 /* Add data streams based on the cached information from the MFT. */
2831 ns = FIRST_STREAM(ni);
2832 for (u32 i = 0; i < ni->num_streams; i++) {
2833 struct windows_file *windows_file;
2835 /* Reference the stream by path if it's a named data stream, or
2836 * if the volume doesn't support "open by file ID", or if the
2837 * application hasn't explicitly opted in to "open by file ID".
2838 * Otherwise, only save the inode number (file ID). */
2840 !(ctx->vol_flags & FILE_SUPPORTS_OPEN_BY_FILE_ID) ||
2841 !(ctx->params->add_flags & WIMLIB_ADD_FLAG_FILE_PATHS_UNNEEDED))
2843 windows_file = alloc_windows_file(ctx->params->cur_path,
2844 ctx->params->cur_path_nchars,
2850 windows_file = alloc_windows_file_for_file_id(ni->ino,
2851 ctx->params->cur_path,
2852 ctx->params->root_path_nchars,
2856 ret = add_stream(inode, windows_file, ns->size,
2857 STREAM_TYPE_DATA, ns->name,
2858 ctx->params->unhashed_blobs);
2861 ns = NEXT_STREAM(ns);
2864 set_sort_key(inode, ni->starting_lcn);
2866 /* If processing a directory, then recurse to its children. In this
2867 * version there is no need to go to disk, as we already have the list
2868 * of children cached from the MFT. */
2869 if (inode_is_directory(inode)) {
2870 const struct ntfs_dentry *nd = ni->first_child;
2872 while (nd != NULL) {
2873 size_t orig_path_nchars;
2874 struct wim_dentry *child;
2875 const struct ntfs_dentry *next = nd->next_child;
2877 ret = WIMLIB_ERR_NOMEM;
2878 if (!pathbuf_append_name(ctx->params, nd->name,
2883 ret = generate_wim_structures_recursive(
2887 (void *)nd - nd->offset_from_inode,
2892 pathbuf_truncate(ctx->params, orig_path_nchars);
2897 attach_scanned_tree(root, child, ctx->params->blob_table);
2904 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_OK, inode);
2906 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
2908 if (--ni->num_aliases == 0) {
2909 /* Memory usage optimization: when we don't need the ntfs_inode
2910 * (and its names and streams) anymore, free it. */
2911 ntfs_inode_map_remove(inode_map, ni);
2913 if (unlikely(ret)) {
2914 free_dentry_tree(root, ctx->params->blob_table);
2922 winnt_build_dentry_tree_fast(struct wim_dentry **root_ret,
2923 struct winnt_scan_ctx *ctx)
2925 struct ntfs_inode_map inode_map = { .root = NULL };
2926 struct security_map security_map = { .root = NULL };
2927 struct ntfs_inode *root = NULL;
2928 wchar_t *path = ctx->params->cur_path;
2929 size_t path_nchars = ctx->params->cur_path_nchars;
2933 adjust_path = (path[path_nchars - 1] == L'\\');
2935 path[path_nchars - 1] = L'\0';
2937 ret = load_files_from_mft(path, &inode_map);
2940 path[path_nchars - 1] = L'\\';
2945 ret = build_children_lists(&inode_map, &root);
2950 ERROR("The MFT listing for volume \"%ls\" did not include a "
2951 "root directory!", path);
2952 ret = WIMLIB_ERR_UNSUPPORTED;
2956 root->num_aliases = 1;
2958 ret = generate_wim_structures_recursive(root_ret, L"", false, root, ctx,
2959 &inode_map, &security_map);
2961 ntfs_inode_map_destroy(&inode_map);
2962 security_map_destroy(&security_map);
2966 #endif /* ENABLE_FAST_MFT_SCAN */
2968 /*----------------------------------------------------------------------------*
2969 * Entry point for directory tree scans on Windows *
2970 *----------------------------------------------------------------------------*/
2973 win32_build_dentry_tree(struct wim_dentry **root_ret,
2974 const wchar_t *root_disk_path,
2975 struct scan_params *params)
2977 struct winnt_scan_ctx ctx = { .params = params };
2978 UNICODE_STRING ntpath;
2983 if (params->add_flags & WIMLIB_ADD_FLAG_SNAPSHOT)
2984 ret = vss_create_snapshot(root_disk_path, &ntpath, &ctx.snapshot);
2986 ret = win32_path_to_nt_path(root_disk_path, &ntpath);
2991 if (ntpath.Length < 4 * sizeof(wchar_t) ||
2992 wmemcmp(ntpath.Buffer, L"\\??\\", 4))
2994 ERROR("\"%ls\": unrecognized path format", root_disk_path);
2995 ret = WIMLIB_ERR_INVALID_PARAM;
2997 ret = pathbuf_init(params, ntpath.Buffer);
2999 HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
3003 status = winnt_open(params->cur_path, params->cur_path_nchars,
3004 FILE_READ_ATTRIBUTES, &h);
3005 if (!NT_SUCCESS(status)) {
3006 winnt_error(status, L"Can't open \"%ls\"", root_disk_path);
3007 if (status == STATUS_FVE_LOCKED_VOLUME)
3008 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
3010 ret = WIMLIB_ERR_OPEN;
3014 get_volume_information(h, &ctx);
3018 #ifdef ENABLE_FAST_MFT_SCAN
3019 if (ctx.is_ntfs && !_wgetenv(L"WIMLIB_DISABLE_QUERY_FILE_LAYOUT")) {
3020 ret = winnt_build_dentry_tree_fast(root_ret, &ctx);
3021 if (ret >= 0 && ret != WIMLIB_ERR_UNSUPPORTED)
3024 WARNING("A problem occurred during the fast MFT scan.\n"
3025 " Falling back to the standard "
3026 "recursive directory tree scan.");
3030 ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
3032 params->cur_path_nchars,
3035 vss_put_snapshot(ctx.snapshot);
3037 winnt_do_scan_warnings(root_disk_path, &ctx);
3041 #endif /* __WIN32__ */