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-2021 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 https://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] __attribute__((aligned(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,
494 const struct windows_file *file = blob->windows_file;
496 if (unlikely(file->is_encrypted)) {
497 bool is_dir = (blob->file_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY);
498 return read_win32_encrypted_file_prefix(file->path, is_dir, size, cb);
501 return read_winnt_stream_prefix(file, size, cb);
505 * Load the short name of a file into a WIM dentry.
507 static noinline_for_stack NTSTATUS
508 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
510 /* It's not any harder to just make the NtQueryInformationFile() system
511 * call ourselves, and it saves a dumb call to FindFirstFile() which of
512 * course has to create its own handle. */
514 IO_STATUS_BLOCK iosb;
515 u8 buf[128] __attribute__((aligned(8)));
516 const FILE_NAME_INFORMATION *info;
518 status = NtQueryInformationFile(h, &iosb, buf, sizeof(buf),
519 FileAlternateNameInformation);
520 info = (const FILE_NAME_INFORMATION *)buf;
521 if (NT_SUCCESS(status) && info->FileNameLength != 0) {
522 dentry->d_short_name = utf16le_dupz(info->FileName,
523 info->FileNameLength);
524 if (!dentry->d_short_name)
525 return STATUS_NO_MEMORY;
526 dentry->d_short_name_nbytes = info->FileNameLength;
532 * Load the security descriptor of a file into the corresponding inode and the
533 * WIM image's security descriptor set.
535 static noinline_for_stack int
536 winnt_load_security_descriptor(HANDLE h, struct wim_inode *inode,
537 struct winnt_scan_ctx *ctx)
539 SECURITY_INFORMATION requestedInformation;
540 u8 _buf[4096] __attribute__((aligned(8)));
547 * LABEL_SECURITY_INFORMATION is needed on Windows Vista and 7 because
548 * Microsoft decided to add mandatory integrity labels to the SACL but
549 * not have them returned by SACL_SECURITY_INFORMATION.
551 * BACKUP_SECURITY_INFORMATION is needed on Windows 8 because Microsoft
552 * decided to add even more stuff to the SACL and still not have it
553 * returned by SACL_SECURITY_INFORMATION; but they did remember that
554 * backup applications exist and simply want to read the stupid thing
555 * once and for all, so they added a flag to read the entire security
558 * Older versions of Windows tolerate these new flags being passed in.
560 requestedInformation = OWNER_SECURITY_INFORMATION |
561 GROUP_SECURITY_INFORMATION |
562 DACL_SECURITY_INFORMATION |
563 SACL_SECURITY_INFORMATION |
564 LABEL_SECURITY_INFORMATION |
565 BACKUP_SECURITY_INFORMATION;
568 bufsize = sizeof(_buf);
571 * We need the file's security descriptor in
572 * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
573 * opened with as many relevant permissions as possible. At this point,
574 * on Windows there are a number of options for reading a file's
575 * security descriptor:
577 * GetFileSecurity(): This takes in a path and returns the
578 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle,
579 * not ours, and the handle created internally doesn't specify
580 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied
581 * errors on some files and directories, even when running as the
584 * GetSecurityInfo(): This takes in a handle and returns the security
585 * descriptor split into a bunch of different parts. This should work,
586 * but it's dumb because we have to put the security descriptor back
589 * BackupRead(): This can read the security descriptor, but this is a
590 * difficult-to-use API, probably only works as the Administrator, and
591 * the format of the returned data is not well documented.
593 * NtQuerySecurityObject(): This is exactly what we need, as it takes
594 * in a handle and returns the security descriptor in
595 * SECURITY_DESCRIPTOR_RELATIVE format. Only problem is that it's a
596 * ntdll function and therefore not officially part of the Win32 API.
599 while (!NT_SUCCESS(status = NtQuerySecurityObject(h,
600 requestedInformation,
601 (PSECURITY_DESCRIPTOR)buf,
606 case STATUS_BUFFER_TOO_SMALL:
607 wimlib_assert(buf == _buf);
608 buf = MALLOC(len_needed);
610 status = STATUS_NO_MEMORY;
613 bufsize = len_needed;
615 case STATUS_PRIVILEGE_NOT_HELD:
616 case STATUS_ACCESS_DENIED:
617 if (ctx->params->add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
619 /* Permission denied in STRICT_ACLS mode, or
623 if (requestedInformation & SACL_SECURITY_INFORMATION) {
624 /* Try again without the SACL. */
625 ctx->num_get_sacl_priv_notheld++;
626 requestedInformation &= ~(SACL_SECURITY_INFORMATION |
627 LABEL_SECURITY_INFORMATION |
628 BACKUP_SECURITY_INFORMATION);
631 /* Fake success (useful when capturing as
632 * non-Administrator). */
633 ctx->num_get_sd_access_denied++;
634 status = STATUS_SUCCESS;
639 /* We can get a length of 0 with Samba. Assume that means "no security
644 /* Add the security descriptor to the WIM image, and save its ID in
645 * the file's inode. */
646 inode->i_security_id = sd_set_add_sd(ctx->params->sd_set, buf, len_needed);
647 if (unlikely(inode->i_security_id < 0))
648 status = STATUS_NO_MEMORY;
650 if (unlikely(buf != _buf))
652 if (!NT_SUCCESS(status)) {
653 winnt_error(status, L"\"%ls\": Can't read security descriptor",
654 printable_path(ctx));
655 return WIMLIB_ERR_STAT;
660 /* Load a file's object ID into the corresponding WIM inode. */
661 static noinline_for_stack int
662 winnt_load_object_id(HANDLE h, struct wim_inode *inode,
663 struct winnt_scan_ctx *ctx)
665 FILE_OBJECTID_BUFFER buffer;
669 if (!(ctx->vol_flags & FILE_SUPPORTS_OBJECT_IDS))
672 status = winnt_fsctl(h, FSCTL_GET_OBJECT_ID, NULL, 0,
673 &buffer, sizeof(buffer), &len);
675 if (status == STATUS_OBJECTID_NOT_FOUND) /* No object ID */
678 if (status == STATUS_INVALID_DEVICE_REQUEST ||
679 status == STATUS_NOT_SUPPORTED /* Samba volume, WinXP */) {
680 /* The filesystem claimed to support object IDs, but we can't
681 * actually read them. This happens with Samba. */
682 ctx->vol_flags &= ~FILE_SUPPORTS_OBJECT_IDS;
686 if (!NT_SUCCESS(status)) {
687 winnt_error(status, L"\"%ls\": Can't read object ID",
688 printable_path(ctx));
689 return WIMLIB_ERR_STAT;
692 if (len == 0) /* No object ID (for directories) */
695 if (!inode_set_object_id(inode, &buffer, len))
696 return WIMLIB_ERR_NOMEM;
701 /* Load a file's extended attributes into the corresponding WIM inode. */
702 static noinline_for_stack int
703 winnt_load_xattrs(HANDLE h, struct wim_inode *inode,
704 struct winnt_scan_ctx *ctx, u32 ea_size)
706 IO_STATUS_BLOCK iosb;
708 u8 _buf[1024] __attribute__((aligned(4)));
710 const FILE_FULL_EA_INFORMATION *ea;
711 struct wim_xattr_entry *entry;
716 * EaSize from FILE_EA_INFORMATION is apparently supposed to give the
717 * size of the buffer required for NtQueryEaFile(), but it doesn't
718 * actually work correctly; it can be off by about 4 bytes per xattr.
720 * So just start out by doubling the advertised size, and also handle
721 * STATUS_BUFFER_OVERFLOW just in case.
724 if (unlikely(ea_size * 2 < ea_size))
725 ea_size = UINT32_MAX;
728 if (unlikely(ea_size > sizeof(_buf))) {
729 buf = MALLOC(ea_size);
731 if (ea_size >= (1 << 20)) {
732 WARNING("\"%ls\": EaSize was extremely large (%u)",
733 printable_path(ctx), ea_size);
735 return WIMLIB_ERR_NOMEM;
739 status = NtQueryEaFile(h, &iosb, buf, ea_size,
740 FALSE, NULL, 0, NULL, TRUE);
742 if (unlikely(!NT_SUCCESS(status))) {
743 if (status == STATUS_BUFFER_OVERFLOW) {
750 if (status == STATUS_NO_EAS_ON_FILE) {
752 * FILE_EA_INFORMATION.EaSize was nonzero so this
753 * shouldn't happen, but just in case...
758 winnt_error(status, L"\"%ls\": Can't read extended attributes",
759 printable_path(ctx));
760 ret = WIMLIB_ERR_STAT;
764 ea = (const FILE_FULL_EA_INFORMATION *)buf;
765 entry = (struct wim_xattr_entry *)buf;
768 * wim_xattr_entry is not larger than FILE_FULL_EA_INFORMATION,
769 * so we can reuse the same buffer by overwriting the
770 * FILE_FULL_EA_INFORMATION with the wim_xattr_entry in-place.
772 FILE_FULL_EA_INFORMATION _ea;
774 STATIC_ASSERT(offsetof(struct wim_xattr_entry, name) <=
775 offsetof(FILE_FULL_EA_INFORMATION, EaName));
776 wimlib_assert((u8 *)entry <= (const u8 *)ea);
778 memcpy(&_ea, ea, sizeof(_ea));
780 entry->value_len = cpu_to_le16(_ea.EaValueLength);
781 entry->name_len = _ea.EaNameLength;
782 entry->flags = _ea.Flags;
783 memmove(entry->name, ea->EaName, _ea.EaNameLength);
784 entry->name[_ea.EaNameLength] = '\0';
785 memmove(&entry->name[_ea.EaNameLength + 1],
786 &ea->EaName[_ea.EaNameLength + 1], _ea.EaValueLength);
787 entry = (struct wim_xattr_entry *)
788 &entry->name[_ea.EaNameLength + 1 + _ea.EaValueLength];
789 if (_ea.NextEntryOffset == 0)
791 ea = (const FILE_FULL_EA_INFORMATION *)
792 ((const u8 *)ea + _ea.NextEntryOffset);
794 wimlib_assert((u8 *)entry - buf <= ea_size);
796 ret = WIMLIB_ERR_NOMEM;
797 if (!inode_set_xattrs(inode, buf, (u8 *)entry - buf))
801 if (unlikely(buf != _buf))
807 winnt_build_dentry_tree(struct wim_dentry **root_ret,
809 const wchar_t *relative_path,
810 size_t relative_path_nchars,
811 const wchar_t *filename,
812 struct winnt_scan_ctx *ctx,
816 winnt_recurse_directory(HANDLE h,
817 struct wim_dentry *parent,
818 struct winnt_scan_ctx *ctx)
821 const size_t bufsize = 8192;
822 IO_STATUS_BLOCK iosb;
826 buf = MALLOC(bufsize);
828 return WIMLIB_ERR_NOMEM;
830 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
831 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
833 while (NT_SUCCESS(status = NtQueryDirectoryFile(h, NULL, NULL, NULL,
835 FileNamesInformation,
836 FALSE, NULL, FALSE)))
838 const FILE_NAMES_INFORMATION *info = buf;
840 if (!should_ignore_filename(info->FileName,
841 info->FileNameLength / 2))
843 struct wim_dentry *child;
844 size_t orig_path_nchars;
845 const wchar_t *filename;
847 ret = WIMLIB_ERR_NOMEM;
848 filename = pathbuf_append_name(ctx->params,
850 info->FileNameLength / 2,
855 ret = winnt_build_dentry_tree(
859 info->FileNameLength / 2,
864 pathbuf_truncate(ctx->params, orig_path_nchars);
868 attach_scanned_tree(parent, child,
869 ctx->params->blob_table);
871 if (info->NextEntryOffset == 0)
873 info = (const FILE_NAMES_INFORMATION *)
874 ((const u8 *)info + info->NextEntryOffset);
878 if (unlikely(status != STATUS_NO_MORE_FILES)) {
879 winnt_error(status, L"\"%ls\": Can't read directory",
880 printable_path(ctx));
881 ret = WIMLIB_ERR_READ;
888 /* Reparse point fixup status code */
889 #define RP_FIXED (-1)
892 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
895 IO_STATUS_BLOCK iosb;
896 FILE_INTERNAL_INFORMATION int_info;
897 FILE_FS_VOLUME_INFORMATION vol_info;
899 status = NtQueryInformationFile(h, &iosb, &int_info, sizeof(int_info),
900 FileInternalInformation);
901 if (!NT_SUCCESS(status))
904 if (int_info.IndexNumber.QuadPart != ino)
907 status = NtQueryVolumeInformationFile(h, &iosb,
908 &vol_info, sizeof(vol_info),
909 FileFsVolumeInformation);
910 if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
913 if (iosb.Information <
914 offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
915 sizeof(vol_info.VolumeSerialNumber))
918 return (vol_info.VolumeSerialNumber == dev);
922 * This is the Windows equivalent of unix_relativize_link_target(); see there
923 * for general details. This version works with an "absolute" Windows link
924 * target, specified from the root of the Windows kernel object namespace. Note
925 * that we have to open directories with a trailing slash when present because
926 * \??\E: opens the E: device itself and not the filesystem root directory.
928 static const wchar_t *
929 winnt_relativize_link_target(const wchar_t *target, size_t target_nbytes,
933 OBJECT_ATTRIBUTES attr;
934 IO_STATUS_BLOCK iosb;
936 const wchar_t *target_end;
939 target_end = target + (target_nbytes / sizeof(wchar_t));
942 if (target_end == target)
945 /* No leading slash??? */
946 if (target[0] != L'\\')
950 if ((target_end - target) >= 2 &&
951 target[0] == L'\\' && target[1] == L'\\')
954 attr.Length = sizeof(attr);
955 attr.RootDirectory = NULL;
956 attr.ObjectName = &name;
958 attr.SecurityDescriptor = NULL;
959 attr.SecurityQualityOfService = NULL;
961 name.Buffer = (wchar_t *)target;
966 const wchar_t *orig_p = p;
968 /* Skip non-backslashes */
969 while (p != target_end && *p != L'\\')
972 /* Skip backslashes */
973 while (p != target_end && *p == L'\\')
976 /* Append path component */
977 name.Length += (p - orig_p) * sizeof(wchar_t);
978 name.MaximumLength = name.Length;
980 /* Try opening the file */
981 status = NtOpenFile(&h,
982 FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
985 FILE_SHARE_VALID_FLAGS,
986 FILE_OPEN_FOR_BACKUP_INTENT);
988 if (NT_SUCCESS(status)) {
989 /* Reset root directory */
990 if (attr.RootDirectory)
991 NtClose(attr.RootDirectory);
992 attr.RootDirectory = h;
993 name.Buffer = (wchar_t *)p;
996 if (file_has_ino_and_dev(h, ino, dev))
997 goto out_close_root_dir;
999 } while (p != target_end);
1004 if (attr.RootDirectory)
1005 NtClose(attr.RootDirectory);
1006 while (p > target && *(p - 1) == L'\\')
1012 winnt_rpfix_progress(struct scan_params *params,
1013 const struct link_reparse_point *link, int scan_status)
1015 size_t print_name_nchars = link->print_name_nbytes / sizeof(wchar_t);
1016 wchar_t print_name0[print_name_nchars + 1];
1018 wmemcpy(print_name0, link->print_name, print_name_nchars);
1019 print_name0[print_name_nchars] = L'\0';
1021 params->progress.scan.symlink_target = print_name0;
1022 return do_scan_progress(params, scan_status, NULL);
1026 winnt_try_rpfix(struct reparse_buffer_disk *rpbuf, u16 *rpbuflen_p,
1027 struct scan_params *params)
1029 struct link_reparse_point link;
1030 const wchar_t *rel_target;
1033 if (parse_link_reparse_point(rpbuf, *rpbuflen_p, &link)) {
1034 /* Couldn't understand the reparse data; don't do the fixup. */
1039 * Don't do reparse point fixups on relative symbolic links.
1041 * On Windows, a relative symbolic link is supposed to be identifiable
1042 * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
1043 * SYMBOLIC_LINK_RELATIVE. We will use this information, although this
1044 * may not always do what the user expects, since drive-relative
1045 * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
1046 * set, in addition to truly relative symbolic links such as "Users" or
1047 * "Users\Public". However, WIMGAPI (as of Windows 8.1) has this same
1050 * Otherwise, as far as I can tell, the targets of symbolic links that
1051 * are NOT relative, as well as junctions (note: a mountpoint is the
1052 * sames thing as a junction), must be NT namespace paths, for example:
1054 * - \??\e:\Users\Public
1055 * - \DosDevices\e:\Users\Public
1056 * - \Device\HardDiskVolume4\Users\Public
1057 * - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
1058 * - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
1060 if (link_is_relative_symlink(&link))
1063 rel_target = winnt_relativize_link_target(link.substitute_name,
1064 link.substitute_name_nbytes,
1065 params->capture_root_ino,
1066 params->capture_root_dev);
1068 if (rel_target == link.substitute_name) {
1069 /* Target points outside of the tree being captured or had an
1070 * unrecognized path format. Don't adjust it. */
1071 return winnt_rpfix_progress(params, &link,
1072 WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK);
1075 /* We have an absolute target pointing within the directory being
1076 * captured. @rel_target is the suffix of the link target that is the
1077 * part relative to the directory being captured.
1079 * We will cut off the prefix before this part (which is the path to the
1080 * directory being captured) and add a dummy prefix. Since the process
1081 * will need to be reversed when applying the image, it doesn't matter
1082 * what exactly the prefix is, as long as it looks like an absolute
1085 static const wchar_t prefix[6] = L"\\??\\X:";
1086 static const size_t num_unprintable_chars = 4;
1088 size_t rel_target_nbytes =
1089 link.substitute_name_nbytes - ((const u8 *)rel_target -
1090 (const u8 *)link.substitute_name);
1092 wchar_t tmp[(sizeof(prefix) + rel_target_nbytes) / sizeof(wchar_t)];
1094 memcpy(tmp, prefix, sizeof(prefix));
1095 memcpy(tmp + ARRAY_LEN(prefix), rel_target, rel_target_nbytes);
1097 link.substitute_name = tmp;
1098 link.substitute_name_nbytes = sizeof(tmp);
1100 link.print_name = link.substitute_name + num_unprintable_chars;
1101 link.print_name_nbytes = link.substitute_name_nbytes -
1102 (num_unprintable_chars * sizeof(wchar_t));
1104 if (make_link_reparse_point(&link, rpbuf, rpbuflen_p))
1107 ret = winnt_rpfix_progress(params, &link,
1108 WIMLIB_SCAN_DENTRY_FIXED_SYMLINK);
1114 /* Load the reparse data of a file into the corresponding WIM inode. If the
1115 * reparse point is a symbolic link or junction with an absolute target and
1116 * RPFIX mode is enabled, then also rewrite its target to be relative to the
1118 static noinline_for_stack int
1119 winnt_load_reparse_data(HANDLE h, struct wim_inode *inode,
1120 struct winnt_scan_ctx *ctx)
1122 struct reparse_buffer_disk rpbuf;
1128 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1129 /* See comment above assign_stream_types_encrypted() */
1130 WARNING("Ignoring reparse data of encrypted file \"%ls\"",
1131 printable_path(ctx));
1135 status = winnt_fsctl(h, FSCTL_GET_REPARSE_POINT,
1136 NULL, 0, &rpbuf, sizeof(rpbuf), &len);
1137 if (!NT_SUCCESS(status)) {
1138 winnt_error(status, L"\"%ls\": Can't get reparse point",
1139 printable_path(ctx));
1140 return WIMLIB_ERR_READLINK;
1145 if (unlikely(rpbuflen < REPARSE_DATA_OFFSET)) {
1146 ERROR("\"%ls\": reparse point buffer is too short",
1147 printable_path(ctx));
1148 return WIMLIB_ERR_INVALID_REPARSE_DATA;
1151 if (le32_to_cpu(rpbuf.rptag) == WIM_IO_REPARSE_TAG_DEDUP) {
1153 * Windows treats Data Deduplication reparse points specially.
1154 * Reads from the unnamed data stream actually return the
1155 * redirected file contents, even with FILE_OPEN_REPARSE_POINT.
1156 * Deduplicated files also cannot be properly restored without
1157 * also restoring the "System Volume Information" directory,
1158 * which wimlib excludes by default. Therefore, the logical
1159 * behavior for us seems to be to ignore the reparse point and
1160 * treat the file as a normal file.
1162 inode->i_attributes &= ~FILE_ATTRIBUTE_REPARSE_POINT;
1166 if (ctx->params->add_flags & WIMLIB_ADD_FLAG_RPFIX) {
1167 ret = winnt_try_rpfix(&rpbuf, &rpbuflen, ctx->params);
1168 if (ret == RP_FIXED)
1169 inode->i_rp_flags &= ~WIM_RP_FLAG_NOT_FIXED;
1174 inode->i_reparse_tag = le32_to_cpu(rpbuf.rptag);
1175 inode->i_rp_reserved = le16_to_cpu(rpbuf.rpreserved);
1177 if (!inode_add_stream_with_data(inode,
1178 STREAM_TYPE_REPARSE_POINT,
1181 rpbuflen - REPARSE_DATA_OFFSET,
1182 ctx->params->blob_table))
1183 return WIMLIB_ERR_NOMEM;
1189 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
1192 *(u64*)_size_ret += len;
1193 return ERROR_SUCCESS;
1197 win32_get_encrypted_file_size(const wchar_t *path, bool is_dir, u64 *size_ret)
1205 flags |= CREATE_FOR_DIR;
1207 err = OpenEncryptedFileRaw(path, flags, &file_ctx);
1208 if (err != ERROR_SUCCESS) {
1210 L"Failed to open encrypted file \"%ls\" for raw read",
1212 return WIMLIB_ERR_OPEN;
1215 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
1216 size_ret, file_ctx);
1217 if (err != ERROR_SUCCESS) {
1219 L"Failed to read raw encrypted data from \"%ls\"",
1221 ret = WIMLIB_ERR_READ;
1225 CloseEncryptedFileRaw(file_ctx);
1230 winnt_scan_efsrpc_raw_data(struct wim_inode *inode,
1231 struct winnt_scan_ctx *ctx)
1233 wchar_t *path = ctx->params->cur_path;
1234 size_t path_nchars = ctx->params->cur_path_nchars;
1235 const bool is_dir = (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY);
1236 struct windows_file *windows_file;
1240 /* OpenEncryptedFileRaw() expects a Win32 name. */
1241 wimlib_assert(!wmemcmp(path, L"\\??\\", 4));
1244 ret = win32_get_encrypted_file_size(path, is_dir, &size);
1248 /* Empty EFSRPC data does not make sense */
1249 wimlib_assert(size != 0);
1251 windows_file = alloc_windows_file(path, path_nchars, NULL, 0,
1252 ctx->snapshot, true);
1253 ret = add_stream(inode, windows_file, size, STREAM_TYPE_EFSRPC_RAW_DATA,
1254 NO_STREAM_NAME, ctx->params->unhashed_blobs);
1261 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1262 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
1264 const wchar_t *sep, *type, *end;
1266 /* The stream name should be returned as :NAME:TYPE */
1267 if (raw_stream_name_nchars < 1)
1269 if (raw_stream_name[0] != L':')
1273 raw_stream_name_nchars--;
1275 end = raw_stream_name + raw_stream_name_nchars;
1277 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
1282 if (end - type != 5)
1285 if (wmemcmp(type, L"$DATA", 5))
1288 *stream_name_ret = raw_stream_name;
1289 *stream_name_nchars_ret = sep - raw_stream_name;
1294 winnt_scan_data_stream(wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1295 u64 stream_size, struct wim_inode *inode,
1296 struct winnt_scan_ctx *ctx)
1298 wchar_t *stream_name;
1299 size_t stream_name_nchars;
1300 struct windows_file *windows_file;
1302 /* Given the raw stream name (which is something like
1303 * :streamname:$DATA), extract just the stream name part (streamname).
1304 * Ignore any non-$DATA streams. */
1305 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
1306 (const wchar_t **)&stream_name,
1307 &stream_name_nchars))
1310 stream_name[stream_name_nchars] = L'\0';
1312 windows_file = alloc_windows_file(ctx->params->cur_path,
1313 ctx->params->cur_path_nchars,
1314 stream_name, stream_name_nchars,
1315 ctx->snapshot, false);
1316 return add_stream(inode, windows_file, stream_size, STREAM_TYPE_DATA,
1317 stream_name, ctx->params->unhashed_blobs);
1321 * Load information about the data streams of an open file into a WIM inode.
1323 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
1324 * and FindNextStream(), since FindFirstStream() opens its own handle to the
1325 * file or directory and apparently does so without specifying
1326 * FILE_FLAG_BACKUP_SEMANTICS. This causing access denied errors on certain
1327 * files, even when running as the Administrator.
1329 static noinline_for_stack int
1330 winnt_scan_data_streams(HANDLE h, struct wim_inode *inode, u64 file_size,
1331 struct winnt_scan_ctx *ctx)
1334 u8 _buf[4096] __attribute__((aligned(8)));
1337 IO_STATUS_BLOCK iosb;
1339 FILE_STREAM_INFORMATION *info;
1342 bufsize = sizeof(_buf);
1344 if (!(ctx->vol_flags & FILE_NAMED_STREAMS))
1347 /* Get a buffer containing the stream information. */
1348 while (!NT_SUCCESS(status = NtQueryInformationFile(h,
1352 FileStreamInformation)))
1356 case STATUS_BUFFER_OVERFLOW:
1362 newbuf = MALLOC(bufsize);
1364 newbuf = REALLOC(buf, bufsize);
1366 ret = WIMLIB_ERR_NOMEM;
1372 case STATUS_NOT_IMPLEMENTED:
1373 case STATUS_NOT_SUPPORTED:
1374 case STATUS_INVALID_INFO_CLASS:
1378 L"\"%ls\": Failed to query stream information",
1379 printable_path(ctx));
1380 ret = WIMLIB_ERR_READ;
1385 if (iosb.Information == 0) {
1386 /* No stream information. */
1391 /* Parse one or more stream information structures. */
1392 info = (FILE_STREAM_INFORMATION *)buf;
1394 /* Load the stream information. */
1395 ret = winnt_scan_data_stream(info->StreamName,
1396 info->StreamNameLength / 2,
1397 info->StreamSize.QuadPart,
1402 if (info->NextEntryOffset == 0) {
1403 /* No more stream information. */
1406 /* Advance to next stream information. */
1407 info = (FILE_STREAM_INFORMATION *)
1408 ((u8 *)info + info->NextEntryOffset);
1414 /* The volume does not support named streams. Only capture the unnamed
1416 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1417 FILE_ATTRIBUTE_REPARSE_POINT))
1424 wchar_t stream_name[] = L"::$DATA";
1425 ret = winnt_scan_data_stream(stream_name, 7, file_size,
1429 /* Free buffer if allocated on heap. */
1430 if (unlikely(buf != _buf))
1436 extract_starting_lcn(const RETRIEVAL_POINTERS_BUFFER *extents)
1438 if (extents->ExtentCount < 1)
1441 return extents->Extents[0].Lcn.QuadPart;
1444 static noinline_for_stack u64
1445 get_sort_key(HANDLE h)
1447 STARTING_VCN_INPUT_BUFFER in = { .StartingVcn.QuadPart = 0 };
1448 RETRIEVAL_POINTERS_BUFFER out;
1450 if (!NT_SUCCESS(winnt_fsctl(h, FSCTL_GET_RETRIEVAL_POINTERS,
1451 &in, sizeof(in), &out, sizeof(out), NULL)))
1454 return extract_starting_lcn(&out);
1458 set_sort_key(struct wim_inode *inode, u64 sort_key)
1460 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1461 struct wim_inode_stream *strm = &inode->i_streams[i];
1462 struct blob_descriptor *blob = stream_blob_resolved(strm);
1463 if (blob && blob->blob_location == BLOB_IN_WINDOWS_FILE)
1464 blob->windows_file->sort_key = sort_key;
1469 should_try_to_use_wimboot_hash(const struct wim_inode *inode,
1470 const struct winnt_scan_ctx *ctx)
1472 /* Directories and encrypted files aren't valid for external backing. */
1473 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1474 FILE_ATTRIBUTE_ENCRYPTED))
1477 /* If the file is a reparse point, then try the hash fixup if it's a WOF
1478 * reparse point and we're in WIMBOOT mode. Otherwise, try the hash
1479 * fixup if WOF may be attached. */
1480 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1481 return (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_WOF) &&
1482 (ctx->params->add_flags & WIMLIB_ADD_FLAG_WIMBOOT);
1483 return !ctx->wof_not_attached;
1487 * This function implements an optimization for capturing files from a
1488 * filesystem with a backing WIM(s). If a file is WIM-backed, then we can
1489 * retrieve the SHA-1 message digest of its original contents from its reparse
1490 * point. This may eliminate the need to read the file's data and/or allow the
1491 * file's data to be immediately deduplicated with existing data in the WIM.
1493 * If WOF is attached, then this function is merely an optimization, but
1494 * potentially a very effective one. If WOF is detached, then this function
1495 * really causes WIM-backed files to be, effectively, automatically
1496 * "dereferenced" when possible; the unnamed data stream is updated to reference
1497 * the original contents and the reparse point is removed.
1499 * This function returns 0 if the fixup succeeded or was intentionally not
1500 * executed. Otherwise it returns an error code.
1502 static noinline_for_stack int
1503 try_to_use_wimboot_hash(HANDLE h, struct wim_inode *inode,
1504 struct winnt_scan_ctx *ctx)
1506 struct blob_table *blob_table = ctx->params->blob_table;
1507 struct wim_inode_stream *reparse_strm = NULL;
1508 struct wim_inode_stream *strm;
1509 struct blob_descriptor *blob;
1510 u8 hash[SHA1_HASH_SIZE];
1513 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1514 struct reparse_buffer_disk rpbuf;
1516 WOF_EXTERNAL_INFO wof_info;
1517 struct wim_provider_rpdata wim_info;
1518 } *rpdata = (void *)rpbuf.rpdata;
1519 struct blob_descriptor *reparse_blob;
1521 /* The file has a WOF reparse point, so WOF must be detached.
1522 * We can read the reparse point directly. */
1523 ctx->wof_not_attached = true;
1524 reparse_strm = inode_get_unnamed_stream(inode, STREAM_TYPE_REPARSE_POINT);
1525 reparse_blob = stream_blob_resolved(reparse_strm);
1527 if (!reparse_blob || reparse_blob->size < sizeof(*rpdata))
1528 return 0; /* Not a WIM-backed file */
1530 ret = read_blob_into_buf(reparse_blob, rpdata);
1534 if (rpdata->wof_info.Version != WOF_CURRENT_VERSION ||
1535 rpdata->wof_info.Provider != WOF_PROVIDER_WIM ||
1536 rpdata->wim_info.version != 2)
1537 return 0; /* Not a WIM-backed file */
1539 /* Okay, this is a WIM backed file. Get its SHA-1 hash. */
1540 copy_hash(hash, rpdata->wim_info.unnamed_data_stream_hash);
1543 WOF_EXTERNAL_INFO wof_info;
1544 WIM_PROVIDER_EXTERNAL_INFO wim_info;
1548 /* WOF may be attached. Try reading this file's external
1550 status = winnt_fsctl(h, FSCTL_GET_EXTERNAL_BACKING,
1551 NULL, 0, &out, sizeof(out), NULL);
1553 /* Is WOF not attached? */
1554 if (status == STATUS_INVALID_DEVICE_REQUEST ||
1555 status == STATUS_NOT_SUPPORTED) {
1556 ctx->wof_not_attached = true;
1560 /* Is this file not externally backed? */
1561 if (status == STATUS_OBJECT_NOT_EXTERNALLY_BACKED)
1564 /* Does this file have an unknown type of external backing that
1565 * needed a larger information buffer? */
1566 if (status == STATUS_BUFFER_TOO_SMALL)
1569 /* Was there some other failure? */
1570 if (status != STATUS_SUCCESS) {
1572 L"\"%ls\": FSCTL_GET_EXTERNAL_BACKING failed",
1573 printable_path(ctx));
1574 return WIMLIB_ERR_STAT;
1577 /* Is this file backed by a WIM? */
1578 if (out.wof_info.Version != WOF_CURRENT_VERSION ||
1579 out.wof_info.Provider != WOF_PROVIDER_WIM ||
1580 out.wim_info.Version != WIM_PROVIDER_CURRENT_VERSION)
1583 /* Okay, this is a WIM backed file. Get its SHA-1 hash. */
1584 copy_hash(hash, out.wim_info.ResourceHash);
1587 /* If the file's unnamed data stream is nonempty, then fill in its hash
1588 * and deduplicate it if possible.
1590 * With WOF detached, we require that the blob *must* de-duplicable for
1591 * any action can be taken, since without WOF we can't fall back to
1592 * getting the "dereferenced" data by reading the stream (the real
1593 * stream is sparse and contains all zeroes). */
1594 strm = inode_get_unnamed_data_stream(inode);
1595 if (strm && (blob = stream_blob_resolved(strm))) {
1596 struct blob_descriptor **back_ptr;
1598 if (reparse_strm && !lookup_blob(blob_table, hash))
1600 back_ptr = retrieve_pointer_to_unhashed_blob(blob);
1601 copy_hash(blob->hash, hash);
1602 if (after_blob_hashed(blob, back_ptr, blob_table,
1604 free_blob_descriptor(blob);
1607 /* Remove the reparse point, if present. */
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;
1623 u64 last_write_time;
1624 u64 last_access_time;
1630 static noinline_for_stack NTSTATUS
1631 get_file_info(HANDLE h, struct file_info *info)
1633 IO_STATUS_BLOCK iosb;
1635 FILE_ALL_INFORMATION all_info;
1637 status = NtQueryInformationFile(h, &iosb, &all_info, sizeof(all_info),
1638 FileAllInformation);
1640 if (unlikely(!NT_SUCCESS(status) && status != STATUS_BUFFER_OVERFLOW))
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;
1655 get_volume_information(HANDLE h, struct winnt_scan_ctx *ctx)
1657 u8 _attr_info[sizeof(FILE_FS_ATTRIBUTE_INFORMATION) + 128]
1658 __attribute__((aligned(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(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,
1712 struct wim_dentry *root = NULL;
1713 struct wim_inode *inode = NULL;
1717 struct file_info file_info;
1720 ret = try_exclude(ctx->params);
1721 if (unlikely(ret < 0)) /* Excluded? */
1723 if (unlikely(ret > 0)) /* Error? */
1726 /* Open the file with permission to read metadata. Although we will
1727 * later need a handle with FILE_LIST_DIRECTORY permission (or,
1728 * equivalently, FILE_READ_DATA; they're the same numeric value) if the
1729 * file is a directory, it can significantly slow things down to request
1730 * this permission on all nondirectories. Perhaps it causes Windows to
1731 * start prefetching the file contents... */
1732 status = winnt_openat(cur_dir, relative_path, relative_path_nchars,
1733 FILE_READ_ATTRIBUTES | FILE_READ_EA |
1734 READ_CONTROL | ACCESS_SYSTEM_SECURITY,
1736 if (unlikely(!NT_SUCCESS(status))) {
1737 if (status == STATUS_DELETE_PENDING) {
1738 WARNING("\"%ls\": Deletion pending; skipping file",
1739 printable_path(ctx));
1743 if (status == STATUS_SHARING_VIOLATION) {
1744 ERROR("Can't open \"%ls\":\n"
1745 " File is in use by another process! "
1746 "Consider using snapshot (VSS) mode.",
1747 printable_path(ctx));
1748 ret = WIMLIB_ERR_OPEN;
1751 winnt_error(status, L"\"%ls\": Can't open file",
1752 printable_path(ctx));
1753 if (status == STATUS_FVE_LOCKED_VOLUME)
1754 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1756 ret = WIMLIB_ERR_OPEN;
1760 /* Get information about the file. */
1761 status = get_file_info(h, &file_info);
1762 if (!NT_SUCCESS(status)) {
1763 winnt_error(status, L"\"%ls\": Can't get file information",
1764 printable_path(ctx));
1765 ret = WIMLIB_ERR_STAT;
1769 /* Create a WIM dentry with an associated inode, which may be shared.
1771 * However, we need to explicitly check for directories and files with
1772 * only 1 link and refuse to hard link them. This is because Windows
1773 * has a bug where it can return duplicate File IDs for files and
1774 * directories on the FAT filesystem.
1776 * Since we don't follow mount points on Windows, we don't need to query
1777 * the volume ID per-file. Just once, for the root, is enough. But we
1778 * can't simply pass 0, because then there could be inode collisions
1779 * among multiple calls to win32_build_dentry_tree() that are scanning
1780 * files on different volumes. */
1781 ret = inode_table_new_dentry(ctx->params->inode_table,
1784 ctx->params->capture_root_dev,
1785 (file_info.num_links <= 1),
1790 /* Get the short (DOS) name of the file. */
1791 status = winnt_get_short_name(h, root);
1793 /* If we can't read the short filename for any reason other than
1794 * out-of-memory, just ignore the error and assume the file has no short
1795 * name. This shouldn't be an issue, since the short names are
1796 * essentially obsolete anyway. */
1797 if (unlikely(status == STATUS_NO_MEMORY)) {
1798 ret = WIMLIB_ERR_NOMEM;
1802 inode = root->d_inode;
1804 if (inode->i_nlink > 1) {
1805 /* Shared inode (hard link); skip reading per-inode information.
1810 inode->i_attributes = file_info.attributes;
1811 inode->i_creation_time = file_info.creation_time;
1812 inode->i_last_write_time = file_info.last_write_time;
1813 inode->i_last_access_time = file_info.last_access_time;
1815 /* Get the file's security descriptor, unless we are capturing in
1816 * NO_ACLS mode or the volume does not support security descriptors. */
1817 if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1818 && (ctx->vol_flags & FILE_PERSISTENT_ACLS))
1820 ret = winnt_load_security_descriptor(h, inode, ctx);
1825 /* Get the file's object ID. */
1826 ret = winnt_load_object_id(h, inode, ctx);
1830 /* Get the file's extended attributes. */
1831 if (unlikely(file_info.ea_size != 0)) {
1832 ret = winnt_load_xattrs(h, inode, ctx, file_info.ea_size);
1837 /* If this is a reparse point, load the reparse data. */
1838 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1839 ret = winnt_load_reparse_data(h, inode, ctx);
1844 sort_key = get_sort_key(h);
1846 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1847 /* Load information about the raw encrypted data. This is
1848 * needed for any directory or non-directory that has
1849 * FILE_ATTRIBUTE_ENCRYPTED set.
1851 * Note: since OpenEncryptedFileRaw() fails with
1852 * ERROR_SHARING_VIOLATION if there are any open handles to the
1853 * file, we have to close the file and re-open it later if
1857 ret = winnt_scan_efsrpc_raw_data(inode, ctx);
1862 * Load information about data streams (unnamed and named).
1864 * Skip this step for encrypted files, since the data from
1865 * ReadEncryptedFileRaw() already contains all data streams (and
1866 * they do in fact all get restored by WriteEncryptedFileRaw().)
1868 * Note: WIMGAPI (as of Windows 8.1) gets wrong and stores both
1869 * the EFSRPC data and the named data stream(s)...!
1871 ret = winnt_scan_data_streams(h,
1873 file_info.end_of_file,
1879 if (unlikely(should_try_to_use_wimboot_hash(inode, ctx))) {
1880 ret = try_to_use_wimboot_hash(h, inode, ctx);
1885 set_sort_key(inode, sort_key);
1887 if (inode_is_directory(inode) && recursive) {
1889 /* Directory: recurse to children. */
1891 /* Re-open the directory with FILE_LIST_DIRECTORY access. */
1896 status = winnt_openat(cur_dir, relative_path,
1897 relative_path_nchars, FILE_LIST_DIRECTORY,
1899 if (!NT_SUCCESS(status)) {
1900 winnt_error(status, L"\"%ls\": Can't open directory",
1901 printable_path(ctx));
1902 ret = WIMLIB_ERR_OPEN;
1905 ret = winnt_recurse_directory(h, root, ctx);
1912 if (recursive) { /* if !recursive, caller handles progress */
1914 ret = do_scan_progress(ctx->params,
1915 WIMLIB_SCAN_DENTRY_OK, inode);
1917 ret = do_scan_progress(ctx->params,
1918 WIMLIB_SCAN_DENTRY_EXCLUDED,
1924 if (unlikely(ret)) {
1925 free_dentry_tree(root, ctx->params->blob_table);
1927 ret = report_scan_error(ctx->params, ret);
1934 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_ctx *ctx)
1936 if (likely(ctx->num_get_sacl_priv_notheld == 0 &&
1937 ctx->num_get_sd_access_denied == 0))
1940 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1941 if (ctx->num_get_sacl_priv_notheld != 0) {
1942 WARNING("- Could not capture SACL (System Access Control List)\n"
1943 " on %lu files or directories.",
1944 ctx->num_get_sacl_priv_notheld);
1946 if (ctx->num_get_sd_access_denied != 0) {
1947 WARNING("- Could not capture security descriptor at all\n"
1948 " on %lu files or directories.",
1949 ctx->num_get_sd_access_denied);
1951 WARNING("To fully capture all security descriptors, run the program\n"
1952 " with Administrator rights.");
1955 /*----------------------------------------------------------------------------*
1956 * Fast MFT scan implementation *
1957 *----------------------------------------------------------------------------*/
1959 #define ENABLE_FAST_MFT_SCAN 1
1961 #ifdef ENABLE_FAST_MFT_SCAN
1964 u64 StartingCluster;
1969 u64 StartingFileReferenceNumber;
1970 u64 EndingFileReferenceNumber;
1971 } FILE_REFERENCE_RANGE;
1973 /* The FSCTL_QUERY_FILE_LAYOUT ioctl. This ioctl can be used on Windows 8 and
1974 * later to scan the MFT of an NTFS volume. */
1975 #define FSCTL_QUERY_FILE_LAYOUT CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 157, METHOD_NEITHER, FILE_ANY_ACCESS)
1977 /* The input to FSCTL_QUERY_FILE_LAYOUT */
1980 #define QUERY_FILE_LAYOUT_RESTART 0x00000001
1981 #define QUERY_FILE_LAYOUT_INCLUDE_NAMES 0x00000002
1982 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS 0x00000004
1983 #define QUERY_FILE_LAYOUT_INCLUDE_EXTENTS 0x00000008
1984 #define QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO 0x00000010
1985 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED 0x00000020
1987 #define QUERY_FILE_LAYOUT_FILTER_TYPE_NONE 0
1988 #define QUERY_FILE_LAYOUT_FILTER_TYPE_CLUSTERS 1
1989 #define QUERY_FILE_LAYOUT_FILTER_TYPE_FILEID 2
1990 #define QUERY_FILE_LAYOUT_NUM_FILTER_TYPES 3
1994 CLUSTER_RANGE ClusterRanges[1];
1995 FILE_REFERENCE_RANGE FileReferenceRanges[1];
1997 } QUERY_FILE_LAYOUT_INPUT;
1999 /* The header of the buffer returned by FSCTL_QUERY_FILE_LAYOUT */
2002 u32 FirstFileOffset;
2003 #define QUERY_FILE_LAYOUT_SINGLE_INSTANCED 0x00000001
2006 } QUERY_FILE_LAYOUT_OUTPUT;
2008 /* Inode information returned by FSCTL_QUERY_FILE_LAYOUT */
2014 u64 FileReferenceNumber;
2015 u32 FirstNameOffset;
2016 u32 FirstStreamOffset;
2017 u32 ExtraInfoOffset;
2019 } FILE_LAYOUT_ENTRY;
2021 /* Extra inode information returned by FSCTL_QUERY_FILE_LAYOUT */
2033 } FILE_LAYOUT_INFO_ENTRY;
2035 /* Filename (or dentry) information returned by FSCTL_QUERY_FILE_LAYOUT */
2038 #define FILE_LAYOUT_NAME_ENTRY_PRIMARY 0x00000001
2039 #define FILE_LAYOUT_NAME_ENTRY_DOS 0x00000002
2041 u64 ParentFileReferenceNumber;
2044 wchar_t FileName[1];
2045 } FILE_LAYOUT_NAME_ENTRY;
2047 /* Stream information returned by FSCTL_QUERY_FILE_LAYOUT */
2050 u32 NextStreamOffset;
2051 #define STREAM_LAYOUT_ENTRY_IMMOVABLE 0x00000001
2052 #define STREAM_LAYOUT_ENTRY_PINNED 0x00000002
2053 #define STREAM_LAYOUT_ENTRY_RESIDENT 0x00000004
2054 #define STREAM_LAYOUT_ENTRY_NO_CLUSTERS_ALLOCATED 0x00000008
2056 u32 ExtentInformationOffset;
2061 u32 StreamIdentifierLength;
2062 wchar_t StreamIdentifier[1];
2063 } STREAM_LAYOUT_ENTRY;
2067 #define STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS 0x00000001
2068 #define STREAM_EXTENT_ENTRY_ALL_EXTENTS 0x00000002
2071 RETRIEVAL_POINTERS_BUFFER RetrievalPointers;
2072 } ExtentInformation;
2073 } STREAM_EXTENT_ENTRY;
2075 /* Extract the MFT number part of the full inode number */
2076 #define NTFS_MFT_NO(ref) ((ref) & (((u64)1 << 48) - 1))
2078 /* Is the file the root directory of the NTFS volume? The root directory always
2079 * occupies MFT record 5. */
2080 #define NTFS_IS_ROOT_FILE(ino) (NTFS_MFT_NO(ino) == 5)
2082 /* Is the file a special NTFS file, other than the root directory? The special
2083 * files are the first 16 records in the MFT. */
2084 #define NTFS_IS_SPECIAL_FILE(ino) \
2085 (NTFS_MFT_NO(ino) <= 15 && !NTFS_IS_ROOT_FILE(ino))
2087 #define NTFS_SPECIAL_STREAM_OBJECT_ID 0x00000001
2088 #define NTFS_SPECIAL_STREAM_EA 0x00000002
2089 #define NTFS_SPECIAL_STREAM_EA_INFORMATION 0x00000004
2091 /* Intermediate inode structure. This is used to temporarily save information
2092 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_inode'. */
2094 struct avl_tree_node index_node;
2097 u64 last_access_time;
2098 u64 last_write_time;
2104 u32 special_streams;
2105 u32 first_stream_offset;
2106 struct ntfs_dentry *first_child;
2107 wchar_t short_name[13];
2110 /* Intermediate dentry structure. This is used to temporarily save information
2111 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_dentry'. */
2112 struct ntfs_dentry {
2113 u32 offset_from_inode : 31;
2116 /* Note: build_children_lists() replaces 'parent_ino' with
2119 struct ntfs_dentry *next_child;
2124 /* Intermediate stream structure. This is used to temporarily save information
2125 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct
2126 * wim_inode_stream'. */
2127 struct ntfs_stream {
2132 /* Map of all known NTFS inodes, keyed by inode number */
2133 struct ntfs_inode_map {
2134 struct avl_tree_node *root;
2137 #define NTFS_INODE(node) \
2138 avl_tree_entry((node), struct ntfs_inode, index_node)
2140 #define SKIP_ALIGNED(p, size) ((void *)(p) + ALIGN((size), 8))
2142 /* Get a pointer to the first dentry of the inode. */
2143 #define FIRST_DENTRY(ni) SKIP_ALIGNED((ni), sizeof(struct ntfs_inode))
2145 /* Get a pointer to the first stream of the inode. */
2146 #define FIRST_STREAM(ni) ((const void *)ni + ni->first_stream_offset)
2148 /* Advance to the next dentry of the inode. */
2149 #define NEXT_DENTRY(nd) SKIP_ALIGNED((nd), sizeof(struct ntfs_dentry) + \
2150 (wcslen((nd)->name) + 1) * sizeof(wchar_t))
2152 /* Advance to the next stream of the inode. */
2153 #define NEXT_STREAM(ns) SKIP_ALIGNED((ns), sizeof(struct ntfs_stream) + \
2154 (wcslen((ns)->name) + 1) * sizeof(wchar_t))
2157 _avl_cmp_ntfs_inodes(const struct avl_tree_node *node1,
2158 const struct avl_tree_node *node2)
2160 return cmp_u64(NTFS_INODE(node1)->ino, NTFS_INODE(node2)->ino);
2163 /* Adds an NTFS inode to the map. */
2165 ntfs_inode_map_add_inode(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2167 if (avl_tree_insert(&map->root, &ni->index_node, _avl_cmp_ntfs_inodes)) {
2168 WARNING("Inode 0x%016"PRIx64" is a duplicate!", ni->ino);
2173 /* Find an ntfs_inode in the map by inode number. Returns NULL if not found. */
2174 static struct ntfs_inode *
2175 ntfs_inode_map_lookup(struct ntfs_inode_map *map, u64 ino)
2177 struct ntfs_inode tmp;
2178 struct avl_tree_node *res;
2181 res = avl_tree_lookup_node(map->root, &tmp.index_node, _avl_cmp_ntfs_inodes);
2184 return NTFS_INODE(res);
2187 /* Remove an ntfs_inode from the map and free it. */
2189 ntfs_inode_map_remove(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2191 avl_tree_remove(&map->root, &ni->index_node);
2195 /* Free all ntfs_inodes in the map. */
2197 ntfs_inode_map_destroy(struct ntfs_inode_map *map)
2199 struct ntfs_inode *ni;
2201 avl_tree_for_each_in_postorder(ni, map->root, struct ntfs_inode, index_node)
2206 file_has_streams(const FILE_LAYOUT_ENTRY *file)
2208 return (file->FirstStreamOffset != 0) &&
2209 !(file->FileAttributes & FILE_ATTRIBUTE_ENCRYPTED);
2213 is_valid_name_entry(const FILE_LAYOUT_NAME_ENTRY *name)
2215 return name->FileNameLength > 0 &&
2216 name->FileNameLength % 2 == 0 &&
2217 !wmemchr(name->FileName, L'\0', name->FileNameLength / 2) &&
2218 (!(name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) ||
2219 name->FileNameLength <= 24);
2222 /* Validate the FILE_LAYOUT_NAME_ENTRYs of the specified file and compute the
2223 * total length in bytes of the ntfs_dentry structures needed to hold the name
2226 validate_names_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2227 size_t *total_length_ret)
2229 const FILE_LAYOUT_NAME_ENTRY *name =
2230 (const void *)file + file->FirstNameOffset;
2232 size_t num_long_names = 0;
2235 if (unlikely(!is_valid_name_entry(name))) {
2236 ERROR("Invalid FILE_LAYOUT_NAME_ENTRY! "
2237 "FileReferenceNumber=0x%016"PRIx64", "
2238 "FileNameLength=%"PRIu32", "
2239 "FileName=%.*ls, Flags=0x%08"PRIx32,
2240 file->FileReferenceNumber,
2241 name->FileNameLength,
2242 (int)(name->FileNameLength / 2),
2243 name->FileName, name->Flags);
2244 return WIMLIB_ERR_UNSUPPORTED;
2246 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2248 total += ALIGN(sizeof(struct ntfs_dentry) +
2249 name->FileNameLength + sizeof(wchar_t),
2252 if (name->NextNameOffset == 0)
2254 name = (const void *)name + name->NextNameOffset;
2257 if (unlikely(num_long_names == 0)) {
2258 ERROR("Inode 0x%016"PRIx64" has no long names!",
2259 file->FileReferenceNumber);
2260 return WIMLIB_ERR_UNSUPPORTED;
2263 *total_length_ret = total;
2268 is_valid_stream_entry(const STREAM_LAYOUT_ENTRY *stream)
2270 return stream->StreamIdentifierLength % 2 == 0 &&
2271 !wmemchr(stream->StreamIdentifier , L'\0',
2272 stream->StreamIdentifierLength / 2);
2275 /* assumes that 'id' is a wide string literal */
2276 #define stream_has_identifier(stream, id) \
2277 ((stream)->StreamIdentifierLength == sizeof(id) - 2 && \
2278 !memcmp((stream)->StreamIdentifier, id, sizeof(id) - 2))
2280 * If the specified STREAM_LAYOUT_ENTRY represents a DATA stream as opposed to
2281 * some other type of NTFS stream such as a STANDARD_INFORMATION stream, return
2282 * true and set *stream_name_ret and *stream_name_nchars_ret to specify just the
2283 * stream name. For example, ":foo:$DATA" would become "foo" with length 3
2284 * characters. Otherwise return false.
2287 use_stream(const FILE_LAYOUT_ENTRY *file, const STREAM_LAYOUT_ENTRY *stream,
2288 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
2290 const wchar_t *stream_name;
2291 size_t stream_name_nchars;
2293 if (stream->StreamIdentifierLength == 0) {
2294 /* The unnamed data stream may be given as an empty string
2295 * rather than as "::$DATA". Handle it both ways. */
2297 stream_name_nchars = 0;
2298 } else if (!get_data_stream_name(stream->StreamIdentifier,
2299 stream->StreamIdentifierLength / 2,
2300 &stream_name, &stream_name_nchars))
2303 /* Skip the unnamed data stream for directories. */
2304 if (stream_name_nchars == 0 &&
2305 (file->FileAttributes & FILE_ATTRIBUTE_DIRECTORY))
2308 *stream_name_ret = stream_name;
2309 *stream_name_nchars_ret = stream_name_nchars;
2313 /* Validate the STREAM_LAYOUT_ENTRYs of the specified file and compute the total
2314 * length in bytes of the ntfs_stream structures needed to hold the stream
2315 * information. In addition, set *special_streams_ret to a bitmask of special
2316 * stream types that were found. */
2318 validate_streams_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2319 size_t *total_length_ret,
2320 u32 *special_streams_ret)
2322 const STREAM_LAYOUT_ENTRY *stream =
2323 (const void *)file + file->FirstStreamOffset;
2325 u32 special_streams = 0;
2328 const wchar_t *name;
2331 if (unlikely(!is_valid_stream_entry(stream))) {
2332 WARNING("Invalid STREAM_LAYOUT_ENTRY! "
2333 "FileReferenceNumber=0x%016"PRIx64", "
2334 "StreamIdentifierLength=%"PRIu32", "
2335 "StreamIdentifier=%.*ls",
2336 file->FileReferenceNumber,
2337 stream->StreamIdentifierLength,
2338 (int)(stream->StreamIdentifierLength / 2),
2339 stream->StreamIdentifier);
2340 return WIMLIB_ERR_UNSUPPORTED;
2343 if (use_stream(file, stream, &name, &name_nchars)) {
2344 total += ALIGN(sizeof(struct ntfs_stream) +
2345 (name_nchars + 1) * sizeof(wchar_t), 8);
2346 } else if (stream_has_identifier(stream, L"::$OBJECT_ID")) {
2347 special_streams |= NTFS_SPECIAL_STREAM_OBJECT_ID;
2348 } else if (stream_has_identifier(stream, L"::$EA")) {
2349 special_streams |= NTFS_SPECIAL_STREAM_EA;
2350 } else if (stream_has_identifier(stream, L"::$EA_INFORMATION")) {
2351 special_streams |= NTFS_SPECIAL_STREAM_EA_INFORMATION;
2353 if (stream->NextStreamOffset == 0)
2355 stream = (const void *)stream + stream->NextStreamOffset;
2358 *total_length_ret = total;
2359 *special_streams_ret = special_streams;
2364 load_name_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2367 const FILE_LAYOUT_NAME_ENTRY *name =
2368 (const void *)file + file->FirstNameOffset;
2370 struct ntfs_dentry *nd = p;
2371 /* Note that a name may be just a short (DOS) name, just a long
2372 * name, or both a short name and a long name. If there is a
2373 * short name, one name should also be marked as "primary" to
2374 * indicate which long name the short name is associated with.
2375 * Also, there should be at most one short name per inode. */
2376 if (name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) {
2377 memcpy(ni->short_name,
2378 name->FileName, name->FileNameLength);
2379 ni->short_name[name->FileNameLength / 2] = L'\0';
2381 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2383 nd->offset_from_inode = (u8 *)nd - (u8 *)ni;
2384 nd->is_primary = ((name->Flags &
2385 FILE_LAYOUT_NAME_ENTRY_PRIMARY) != 0);
2386 nd->parent_ino = name->ParentFileReferenceNumber;
2387 memcpy(nd->name, name->FileName, name->FileNameLength);
2388 nd->name[name->FileNameLength / 2] = L'\0';
2389 p += ALIGN(sizeof(struct ntfs_dentry) +
2390 name->FileNameLength + sizeof(wchar_t), 8);
2392 if (name->NextNameOffset == 0)
2394 name = (const void *)name + name->NextNameOffset;
2400 load_starting_lcn(const STREAM_LAYOUT_ENTRY *stream)
2402 const STREAM_EXTENT_ENTRY *entry;
2404 if (stream->ExtentInformationOffset == 0)
2407 entry = (const void *)stream + stream->ExtentInformationOffset;
2409 if (!(entry->Flags & STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS))
2412 return extract_starting_lcn(&entry->ExtentInformation.RetrievalPointers);
2416 load_stream_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2419 const STREAM_LAYOUT_ENTRY *stream =
2420 (const void *)file + file->FirstStreamOffset;
2421 const u32 first_stream_offset = (const u8 *)p - (const u8 *)ni;
2423 struct ntfs_stream *ns = p;
2424 const wchar_t *name;
2427 if (use_stream(file, stream, &name, &name_nchars)) {
2428 ni->first_stream_offset = first_stream_offset;
2430 if (name_nchars == 0)
2431 ni->starting_lcn = load_starting_lcn(stream);
2432 ns->size = stream->EndOfFile;
2433 wmemcpy(ns->name, name, name_nchars);
2434 ns->name[name_nchars] = L'\0';
2435 p += ALIGN(sizeof(struct ntfs_stream) +
2436 (name_nchars + 1) * sizeof(wchar_t), 8);
2438 if (stream->NextStreamOffset == 0)
2440 stream = (const void *)stream + stream->NextStreamOffset;
2445 /* Process the information for a file given by FSCTL_QUERY_FILE_LAYOUT. */
2447 load_one_file(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode_map *inode_map)
2449 const FILE_LAYOUT_INFO_ENTRY *info =
2450 (const void *)file + file->ExtraInfoOffset;
2452 struct ntfs_inode *ni;
2456 u32 special_streams = 0;
2458 inode_size = ALIGN(sizeof(struct ntfs_inode), 8);
2460 /* The root file should have no names, and all other files should have
2461 * at least one name. But just in case, we ignore the names of the root
2462 * file, and we ignore any non-root file with no names. */
2463 if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber)) {
2464 if (file->FirstNameOffset == 0)
2466 ret = validate_names_and_compute_total_length(file, &n);
2472 if (file_has_streams(file)) {
2473 ret = validate_streams_and_compute_total_length(file, &n,
2480 /* To save memory, we allocate the ntfs_dentry's and ntfs_stream's in
2481 * the same memory block as their ntfs_inode. */
2482 ni = CALLOC(1, inode_size);
2484 return WIMLIB_ERR_NOMEM;
2486 ni->ino = file->FileReferenceNumber;
2487 ni->attributes = info->BasicInformation.FileAttributes;
2488 ni->creation_time = info->BasicInformation.CreationTime;
2489 ni->last_write_time = info->BasicInformation.LastWriteTime;
2490 ni->last_access_time = info->BasicInformation.LastAccessTime;
2491 ni->security_id = info->SecurityId;
2492 ni->special_streams = special_streams;
2494 p = FIRST_DENTRY(ni);
2496 if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber))
2497 p = load_name_information(file, ni, p);
2499 if (file_has_streams(file))
2500 p = load_stream_information(file, ni, p);
2502 wimlib_assert((u8 *)p - (u8 *)ni == inode_size);
2504 ntfs_inode_map_add_inode(inode_map, ni);
2509 * Quickly find all files on an NTFS volume by using FSCTL_QUERY_FILE_LAYOUT to
2510 * scan the MFT. The NTFS volume is specified by the NT namespace path @path.
2511 * For each file, allocate an 'ntfs_inode' structure for each file and add it to
2512 * 'inode_map' keyed by inode number. Include NTFS special files such as
2513 * $Bitmap (they will be removed later).
2516 load_files_from_mft(const wchar_t *path, struct ntfs_inode_map *inode_map)
2519 QUERY_FILE_LAYOUT_INPUT in = (QUERY_FILE_LAYOUT_INPUT) {
2521 .Flags = QUERY_FILE_LAYOUT_RESTART |
2522 QUERY_FILE_LAYOUT_INCLUDE_NAMES |
2523 QUERY_FILE_LAYOUT_INCLUDE_STREAMS |
2524 QUERY_FILE_LAYOUT_INCLUDE_EXTENTS |
2525 QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO |
2526 QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED,
2527 .FilterType = QUERY_FILE_LAYOUT_FILTER_TYPE_NONE,
2529 size_t outsize = 32768;
2530 QUERY_FILE_LAYOUT_OUTPUT *out = NULL;
2534 status = winnt_open(path, wcslen(path),
2535 FILE_READ_DATA | FILE_READ_ATTRIBUTES, &h);
2536 if (!NT_SUCCESS(status)) {
2537 ret = -1; /* Silently try standard recursive scan instead */
2542 /* Allocate a buffer for the output of the ioctl. */
2543 out = MALLOC(outsize);
2545 ret = WIMLIB_ERR_NOMEM;
2549 /* Execute FSCTL_QUERY_FILE_LAYOUT until it fails. */
2550 while (NT_SUCCESS(status = winnt_fsctl(h,
2551 FSCTL_QUERY_FILE_LAYOUT,
2553 out, outsize, NULL)))
2555 const FILE_LAYOUT_ENTRY *file =
2556 (const void *)out + out->FirstFileOffset;
2558 ret = load_one_file(file, inode_map);
2561 if (file->NextFileOffset == 0)
2563 file = (const void *)file + file->NextFileOffset;
2565 in.Flags &= ~QUERY_FILE_LAYOUT_RESTART;
2568 /* Enlarge the buffer if needed. */
2569 if (status != STATUS_BUFFER_TOO_SMALL)
2575 /* Normally, FSCTL_QUERY_FILE_LAYOUT fails with STATUS_END_OF_FILE after
2576 * all files have been enumerated. */
2577 if (status != STATUS_END_OF_FILE) {
2578 if (status == STATUS_INVALID_DEVICE_REQUEST /* old OS */ ||
2579 status == STATUS_NOT_SUPPORTED /* Samba volume, WinXP */ ||
2580 status == STATUS_INVALID_PARAMETER /* not root directory */ )
2582 /* Silently try standard recursive scan instead */
2586 L"Error enumerating files on volume \"%ls\"",
2588 /* Try standard recursive scan instead */
2589 ret = WIMLIB_ERR_UNSUPPORTED;
2600 /* Build the list of child dentries for each inode in @map. This is done by
2601 * iterating through each name of each inode and adding it to its parent's
2602 * children list. Note that every name should have a parent, i.e. should belong
2603 * to some directory. The root directory does not have any names. */
2605 build_children_lists(struct ntfs_inode_map *map, struct ntfs_inode **root_ret)
2607 struct ntfs_inode *ni;
2609 avl_tree_for_each_in_order(ni, map->root, struct ntfs_inode, index_node)
2611 struct ntfs_dentry *nd;
2614 if (NTFS_IS_ROOT_FILE(ni->ino)) {
2619 n = ni->num_aliases;
2620 nd = FIRST_DENTRY(ni);
2622 struct ntfs_inode *parent;
2624 parent = ntfs_inode_map_lookup(map, nd->parent_ino);
2625 if (unlikely(!parent)) {
2626 ERROR("Parent inode 0x%016"PRIx64" of"
2627 "directory entry \"%ls\" (inode "
2628 "0x%016"PRIx64") was missing from the "
2630 nd->parent_ino, nd->name, ni->ino);
2631 return WIMLIB_ERR_UNSUPPORTED;
2633 nd->next_child = parent->first_child;
2634 parent->first_child = nd;
2637 nd = NEXT_DENTRY(nd);
2643 struct security_map_node {
2644 struct avl_tree_node index_node;
2645 u32 disk_security_id;
2646 u32 wim_security_id;
2649 /* Map from disk security IDs to WIM security IDs */
2650 struct security_map {
2651 struct avl_tree_node *root;
2654 #define SECURITY_MAP_NODE(node) \
2655 avl_tree_entry((node), struct security_map_node, index_node)
2658 _avl_cmp_security_map_nodes(const struct avl_tree_node *node1,
2659 const struct avl_tree_node *node2)
2661 return cmp_u32(SECURITY_MAP_NODE(node1)->disk_security_id,
2662 SECURITY_MAP_NODE(node2)->disk_security_id);
2666 security_map_lookup(struct security_map *map, u32 disk_security_id)
2668 struct security_map_node tmp;
2669 const struct avl_tree_node *res;
2671 if (disk_security_id == 0) /* No on-disk security ID; uncacheable */
2674 tmp.disk_security_id = disk_security_id;
2675 res = avl_tree_lookup_node(map->root, &tmp.index_node,
2676 _avl_cmp_security_map_nodes);
2679 return SECURITY_MAP_NODE(res)->wim_security_id;
2683 security_map_insert(struct security_map *map, u32 disk_security_id,
2684 u32 wim_security_id)
2686 struct security_map_node *node;
2688 if (disk_security_id == 0) /* No on-disk security ID; uncacheable */
2691 node = MALLOC(sizeof(*node));
2693 return WIMLIB_ERR_NOMEM;
2695 node->disk_security_id = disk_security_id;
2696 node->wim_security_id = wim_security_id;
2697 avl_tree_insert(&map->root, &node->index_node,
2698 _avl_cmp_security_map_nodes);
2703 security_map_destroy(struct security_map *map)
2705 struct security_map_node *node;
2707 avl_tree_for_each_in_postorder(node, map->root,
2708 struct security_map_node, index_node)
2713 * Turn our temporary NTFS structures into the final WIM structures:
2715 * ntfs_inode => wim_inode
2716 * ntfs_dentry => wim_dentry
2717 * ntfs_stream => wim_inode_stream
2719 * This also handles things such as exclusions and issuing progress messages.
2720 * It's similar to winnt_build_dentry_tree(), but this is much faster because
2721 * almost all information we need is already loaded in memory in the ntfs_*
2722 * structures. However, in some cases we still fall back to
2723 * winnt_build_dentry_tree() and/or opening the file.
2726 generate_wim_structures_recursive(struct wim_dentry **root_ret,
2727 const wchar_t *filename, bool is_primary_name,
2728 struct ntfs_inode *ni,
2729 struct winnt_scan_ctx *ctx,
2730 struct ntfs_inode_map *inode_map,
2731 struct security_map *security_map)
2734 struct wim_dentry *root = NULL;
2735 struct wim_inode *inode = NULL;
2736 const struct ntfs_stream *ns;
2738 /* Completely ignore NTFS special files. */
2739 if (NTFS_IS_SPECIAL_FILE(ni->ino))
2742 /* Fall back to the standard scan for unhandled cases. Reparse points,
2743 * in particular, can't be properly handled here because a commonly used
2744 * filter driver (WOF) hides reparse points from regular filesystem APIs
2745 * but not from FSCTL_QUERY_FILE_LAYOUT. */
2746 if (ni->attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
2747 FILE_ATTRIBUTE_ENCRYPTED) ||
2748 ni->special_streams != 0)
2750 ret = winnt_build_dentry_tree(&root, NULL,
2751 ctx->params->cur_path,
2752 ctx->params->cur_path_nchars,
2753 filename, ctx, false);
2754 if (ret) /* Error? */
2756 if (!root) /* Excluded? */
2758 inode = root->d_inode;
2759 goto process_children;
2762 /* Test for exclusion based on path. */
2763 ret = try_exclude(ctx->params);
2764 if (unlikely(ret < 0)) /* Excluded? */
2766 if (unlikely(ret > 0)) /* Error? */
2769 /* Create the WIM dentry and possibly a new WIM inode */
2770 ret = inode_table_new_dentry(ctx->params->inode_table, filename,
2771 ni->ino, ctx->params->capture_root_dev,
2776 inode = root->d_inode;
2778 /* Set the short name if needed. */
2779 if (is_primary_name && *ni->short_name) {
2780 size_t nbytes = wcslen(ni->short_name) * sizeof(wchar_t);
2781 root->d_short_name = memdup(ni->short_name,
2782 nbytes + sizeof(wchar_t));
2783 if (!root->d_short_name) {
2784 ret = WIMLIB_ERR_NOMEM;
2787 root->d_short_name_nbytes = nbytes;
2790 if (inode->i_nlink > 1) { /* Already seen this inode? */
2795 /* The file attributes and timestamps were cached from the MFT. */
2796 inode->i_attributes = ni->attributes;
2797 inode->i_creation_time = ni->creation_time;
2798 inode->i_last_write_time = ni->last_write_time;
2799 inode->i_last_access_time = ni->last_access_time;
2801 /* Set the security descriptor if needed. */
2802 if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)) {
2803 /* Look up the WIM security ID that corresponds to the on-disk
2805 s32 wim_security_id =
2806 security_map_lookup(security_map, ni->security_id);
2807 if (likely(wim_security_id >= 0)) {
2808 /* The mapping for this security ID is already cached.*/
2809 inode->i_security_id = wim_security_id;
2814 /* Create a mapping for this security ID and insert it
2815 * into the security map. */
2817 status = winnt_open(ctx->params->cur_path,
2818 ctx->params->cur_path_nchars,
2820 ACCESS_SYSTEM_SECURITY, &h);
2821 if (!NT_SUCCESS(status)) {
2822 winnt_error(status, L"Can't open \"%ls\" to "
2823 "read security descriptor",
2824 printable_path(ctx));
2825 ret = WIMLIB_ERR_OPEN;
2828 ret = winnt_load_security_descriptor(h, inode, ctx);
2833 ret = security_map_insert(security_map, ni->security_id,
2834 inode->i_security_id);
2840 /* Add data streams based on the cached information from the MFT. */
2841 ns = FIRST_STREAM(ni);
2842 for (u32 i = 0; i < ni->num_streams; i++) {
2843 struct windows_file *windows_file;
2845 /* Reference the stream by path if it's a named data stream, or
2846 * if the volume doesn't support "open by file ID", or if the
2847 * application hasn't explicitly opted in to "open by file ID".
2848 * Otherwise, only save the inode number (file ID). */
2850 !(ctx->vol_flags & FILE_SUPPORTS_OPEN_BY_FILE_ID) ||
2851 !(ctx->params->add_flags & WIMLIB_ADD_FLAG_FILE_PATHS_UNNEEDED))
2853 windows_file = alloc_windows_file(ctx->params->cur_path,
2854 ctx->params->cur_path_nchars,
2860 windows_file = alloc_windows_file_for_file_id(ni->ino,
2861 ctx->params->cur_path,
2862 ctx->params->root_path_nchars,
2866 ret = add_stream(inode, windows_file, ns->size,
2867 STREAM_TYPE_DATA, ns->name,
2868 ctx->params->unhashed_blobs);
2871 ns = NEXT_STREAM(ns);
2874 set_sort_key(inode, ni->starting_lcn);
2876 /* If processing a directory, then recurse to its children. In this
2877 * version there is no need to go to disk, as we already have the list
2878 * of children cached from the MFT. */
2880 if (inode_is_directory(inode)) {
2881 const struct ntfs_dentry *nd = ni->first_child;
2883 while (nd != NULL) {
2884 size_t orig_path_nchars;
2885 struct wim_dentry *child;
2886 const struct ntfs_dentry *next = nd->next_child;
2888 ret = WIMLIB_ERR_NOMEM;
2889 if (!pathbuf_append_name(ctx->params, nd->name,
2894 ret = generate_wim_structures_recursive(
2898 (void *)nd - nd->offset_from_inode,
2903 pathbuf_truncate(ctx->params, orig_path_nchars);
2908 attach_scanned_tree(root, child, ctx->params->blob_table);
2915 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_OK, inode);
2917 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
2919 if (--ni->num_aliases == 0) {
2920 /* Memory usage optimization: when we don't need the ntfs_inode
2921 * (and its names and streams) anymore, free it. */
2922 ntfs_inode_map_remove(inode_map, ni);
2924 if (unlikely(ret)) {
2925 free_dentry_tree(root, ctx->params->blob_table);
2933 winnt_build_dentry_tree_fast(struct wim_dentry **root_ret,
2934 struct winnt_scan_ctx *ctx)
2936 struct ntfs_inode_map inode_map = { .root = NULL };
2937 struct security_map security_map = { .root = NULL };
2938 struct ntfs_inode *root = NULL;
2939 wchar_t *path = ctx->params->cur_path;
2940 size_t path_nchars = ctx->params->cur_path_nchars;
2944 adjust_path = (path[path_nchars - 1] == L'\\');
2946 path[path_nchars - 1] = L'\0';
2948 ret = load_files_from_mft(path, &inode_map);
2951 path[path_nchars - 1] = L'\\';
2956 ret = build_children_lists(&inode_map, &root);
2961 ERROR("The MFT listing for volume \"%ls\" did not include a "
2962 "root directory!", path);
2963 ret = WIMLIB_ERR_UNSUPPORTED;
2967 root->num_aliases = 1;
2969 ret = generate_wim_structures_recursive(root_ret, L"", false, root, ctx,
2970 &inode_map, &security_map);
2972 ntfs_inode_map_destroy(&inode_map);
2973 security_map_destroy(&security_map);
2977 #endif /* ENABLE_FAST_MFT_SCAN */
2979 /*----------------------------------------------------------------------------*
2980 * Entry point for directory tree scans on Windows *
2981 *----------------------------------------------------------------------------*/
2984 win32_build_dentry_tree(struct wim_dentry **root_ret,
2985 const wchar_t *root_disk_path,
2986 struct scan_params *params)
2988 struct winnt_scan_ctx ctx = { .params = params };
2989 UNICODE_STRING ntpath;
2994 if (params->add_flags & WIMLIB_ADD_FLAG_SNAPSHOT)
2995 ret = vss_create_snapshot(root_disk_path, &ntpath, &ctx.snapshot);
2997 ret = win32_path_to_nt_path(root_disk_path, &ntpath);
3002 if (ntpath.Length < 4 * sizeof(wchar_t) ||
3003 wmemcmp(ntpath.Buffer, L"\\??\\", 4))
3005 ERROR("\"%ls\": unrecognized path format", root_disk_path);
3006 ret = WIMLIB_ERR_INVALID_PARAM;
3008 ret = pathbuf_init(params, ntpath.Buffer);
3010 HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
3014 status = winnt_open(params->cur_path, params->cur_path_nchars,
3015 FILE_READ_ATTRIBUTES, &h);
3016 if (!NT_SUCCESS(status)) {
3017 winnt_error(status, L"Can't open \"%ls\"", root_disk_path);
3018 if (status == STATUS_FVE_LOCKED_VOLUME)
3019 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
3021 ret = WIMLIB_ERR_OPEN;
3025 get_volume_information(h, &ctx);
3029 #ifdef ENABLE_FAST_MFT_SCAN
3030 if (ctx.is_ntfs && !_wgetenv(L"WIMLIB_DISABLE_QUERY_FILE_LAYOUT")) {
3031 ret = winnt_build_dentry_tree_fast(root_ret, &ctx);
3032 if (ret >= 0 && ret != WIMLIB_ERR_UNSUPPORTED)
3035 WARNING("A problem occurred during the fast MFT scan.\n"
3036 " Falling back to the standard "
3037 "recursive directory tree scan.");
3041 ret = winnt_build_dentry_tree(root_ret, NULL, params->cur_path,
3042 params->cur_path_nchars, L"", &ctx, true);
3044 vss_put_snapshot(ctx.snapshot);
3046 winnt_do_scan_warnings(root_disk_path, &ctx);