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 /* The filesystem claimed to support object IDs, but we can't
679 * actually read them. This happens with Samba. */
680 ctx->vol_flags &= ~FILE_SUPPORTS_OBJECT_IDS;
684 if (!NT_SUCCESS(status)) {
685 winnt_error(status, L"\"%ls\": Can't read object ID",
686 printable_path(ctx));
687 return WIMLIB_ERR_STAT;
690 if (len == 0) /* No object ID (for directories) */
693 if (!inode_set_object_id(inode, &buffer, len))
694 return WIMLIB_ERR_NOMEM;
699 /* Load a file's extended attributes into the corresponding WIM inode. */
700 static noinline_for_stack int
701 winnt_load_xattrs(HANDLE h, struct wim_inode *inode,
702 struct winnt_scan_ctx *ctx, u32 ea_size)
704 IO_STATUS_BLOCK iosb;
706 u8 _buf[1024] _aligned_attribute(4);
708 const FILE_FULL_EA_INFORMATION *ea;
709 struct wim_xattr_entry *entry;
714 * EaSize from FILE_EA_INFORMATION is apparently supposed to give the
715 * size of the buffer required for NtQueryEaFile(), but it doesn't
716 * actually work correctly; it can be off by about 4 bytes per xattr.
718 * So just start out by doubling the advertised size, and also handle
719 * STATUS_BUFFER_OVERFLOW just in case.
722 if (unlikely(ea_size * 2 < ea_size))
723 ea_size = UINT32_MAX;
726 if (unlikely(ea_size > sizeof(_buf))) {
727 buf = MALLOC(ea_size);
729 if (ea_size >= (1 << 20)) {
730 WARNING("\"%ls\": EaSize was extremely large (%u)",
731 printable_path(ctx), ea_size);
733 return WIMLIB_ERR_NOMEM;
737 status = NtQueryEaFile(h, &iosb, buf, ea_size,
738 FALSE, NULL, 0, NULL, TRUE);
740 if (unlikely(!NT_SUCCESS(status))) {
741 if (status == STATUS_BUFFER_OVERFLOW) {
748 if (status == STATUS_NO_EAS_ON_FILE) {
750 * FILE_EA_INFORMATION.EaSize was nonzero so this
751 * shouldn't happen, but just in case...
756 winnt_error(status, L"\"%ls\": Can't read extended attributes",
757 printable_path(ctx));
758 ret = WIMLIB_ERR_STAT;
762 ea = (const FILE_FULL_EA_INFORMATION *)buf;
763 entry = (struct wim_xattr_entry *)buf;
766 * wim_xattr_entry is not larger than FILE_FULL_EA_INFORMATION,
767 * so we can reuse the same buffer by overwriting the
768 * FILE_FULL_EA_INFORMATION with the wim_xattr_entry in-place.
770 FILE_FULL_EA_INFORMATION _ea;
772 STATIC_ASSERT(offsetof(struct wim_xattr_entry, name) <=
773 offsetof(FILE_FULL_EA_INFORMATION, EaName));
774 wimlib_assert((u8 *)entry <= (const u8 *)ea);
776 memcpy(&_ea, ea, sizeof(_ea));
778 entry->value_len = cpu_to_le16(_ea.EaValueLength);
779 entry->name_len = _ea.EaNameLength;
780 entry->flags = _ea.Flags;
781 memmove(entry->name, ea->EaName, _ea.EaNameLength);
782 entry->name[_ea.EaNameLength] = '\0';
783 memmove(&entry->name[_ea.EaNameLength + 1],
784 &ea->EaName[_ea.EaNameLength + 1], _ea.EaValueLength);
785 entry = (struct wim_xattr_entry *)
786 &entry->name[_ea.EaNameLength + 1 + _ea.EaValueLength];
787 if (_ea.NextEntryOffset == 0)
789 ea = (const FILE_FULL_EA_INFORMATION *)
790 ((const u8 *)ea + _ea.NextEntryOffset);
792 wimlib_assert((u8 *)entry - buf <= ea_size);
794 ret = WIMLIB_ERR_NOMEM;
795 if (!inode_set_xattrs(inode, buf, (u8 *)entry - buf))
799 if (unlikely(buf != _buf))
805 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
807 const wchar_t *relative_path,
808 size_t relative_path_nchars,
809 const wchar_t *filename,
810 struct winnt_scan_ctx *ctx);
813 winnt_recurse_directory(HANDLE h,
814 struct wim_dentry *parent,
815 struct winnt_scan_ctx *ctx)
818 const size_t bufsize = 8192;
819 IO_STATUS_BLOCK iosb;
823 buf = MALLOC(bufsize);
825 return WIMLIB_ERR_NOMEM;
827 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
828 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
830 while (NT_SUCCESS(status = NtQueryDirectoryFile(h, NULL, NULL, NULL,
832 FileNamesInformation,
833 FALSE, NULL, FALSE)))
835 const FILE_NAMES_INFORMATION *info = buf;
837 if (!should_ignore_filename(info->FileName,
838 info->FileNameLength / 2))
840 struct wim_dentry *child;
841 size_t orig_path_nchars;
842 const wchar_t *filename;
844 ret = WIMLIB_ERR_NOMEM;
845 filename = pathbuf_append_name(ctx->params,
847 info->FileNameLength / 2,
852 ret = winnt_build_dentry_tree_recursive(
856 info->FileNameLength / 2,
860 pathbuf_truncate(ctx->params, orig_path_nchars);
864 attach_scanned_tree(parent, child,
865 ctx->params->blob_table);
867 if (info->NextEntryOffset == 0)
869 info = (const FILE_NAMES_INFORMATION *)
870 ((const u8 *)info + info->NextEntryOffset);
874 if (unlikely(status != STATUS_NO_MORE_FILES)) {
875 winnt_error(status, L"\"%ls\": Can't read directory",
876 printable_path(ctx));
877 ret = WIMLIB_ERR_READ;
884 /* Reparse point fixup status code */
885 #define RP_FIXED (-1)
888 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
891 IO_STATUS_BLOCK iosb;
892 FILE_INTERNAL_INFORMATION int_info;
893 FILE_FS_VOLUME_INFORMATION vol_info;
895 status = NtQueryInformationFile(h, &iosb, &int_info, sizeof(int_info),
896 FileInternalInformation);
897 if (!NT_SUCCESS(status))
900 if (int_info.IndexNumber.QuadPart != ino)
903 status = NtQueryVolumeInformationFile(h, &iosb,
904 &vol_info, sizeof(vol_info),
905 FileFsVolumeInformation);
906 if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
909 if (iosb.Information <
910 offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
911 sizeof(vol_info.VolumeSerialNumber))
914 return (vol_info.VolumeSerialNumber == dev);
918 * This is the Windows equivalent of unix_relativize_link_target(); see there
919 * for general details. This version works with an "absolute" Windows link
920 * target, specified from the root of the Windows kernel object namespace. Note
921 * that we have to open directories with a trailing slash when present because
922 * \??\E: opens the E: device itself and not the filesystem root directory.
924 static const wchar_t *
925 winnt_relativize_link_target(const wchar_t *target, size_t target_nbytes,
929 OBJECT_ATTRIBUTES attr;
930 IO_STATUS_BLOCK iosb;
932 const wchar_t *target_end;
935 target_end = target + (target_nbytes / sizeof(wchar_t));
938 if (target_end == target)
941 /* No leading slash??? */
942 if (target[0] != L'\\')
946 if ((target_end - target) >= 2 &&
947 target[0] == L'\\' && target[1] == L'\\')
950 attr.Length = sizeof(attr);
951 attr.RootDirectory = NULL;
952 attr.ObjectName = &name;
954 attr.SecurityDescriptor = NULL;
955 attr.SecurityQualityOfService = NULL;
957 name.Buffer = (wchar_t *)target;
962 const wchar_t *orig_p = p;
964 /* Skip non-backslashes */
965 while (p != target_end && *p != L'\\')
968 /* Skip backslashes */
969 while (p != target_end && *p == L'\\')
972 /* Append path component */
973 name.Length += (p - orig_p) * sizeof(wchar_t);
974 name.MaximumLength = name.Length;
976 /* Try opening the file */
977 status = NtOpenFile(&h,
978 FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
981 FILE_SHARE_VALID_FLAGS,
982 FILE_OPEN_FOR_BACKUP_INTENT);
984 if (NT_SUCCESS(status)) {
985 /* Reset root directory */
986 if (attr.RootDirectory)
987 NtClose(attr.RootDirectory);
988 attr.RootDirectory = h;
989 name.Buffer = (wchar_t *)p;
992 if (file_has_ino_and_dev(h, ino, dev))
993 goto out_close_root_dir;
995 } while (p != target_end);
1000 if (attr.RootDirectory)
1001 NtClose(attr.RootDirectory);
1002 while (p > target && *(p - 1) == L'\\')
1008 winnt_rpfix_progress(struct scan_params *params,
1009 const struct link_reparse_point *link, int scan_status)
1011 size_t print_name_nchars = link->print_name_nbytes / sizeof(wchar_t);
1012 wchar_t print_name0[print_name_nchars + 1];
1014 wmemcpy(print_name0, link->print_name, print_name_nchars);
1015 print_name0[print_name_nchars] = L'\0';
1017 params->progress.scan.symlink_target = print_name0;
1018 return do_scan_progress(params, scan_status, NULL);
1022 winnt_try_rpfix(struct reparse_buffer_disk *rpbuf, u16 *rpbuflen_p,
1023 struct scan_params *params)
1025 struct link_reparse_point link;
1026 const wchar_t *rel_target;
1029 if (parse_link_reparse_point(rpbuf, *rpbuflen_p, &link)) {
1030 /* Couldn't understand the reparse data; don't do the fixup. */
1035 * Don't do reparse point fixups on relative symbolic links.
1037 * On Windows, a relative symbolic link is supposed to be identifiable
1038 * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
1039 * SYMBOLIC_LINK_RELATIVE. We will use this information, although this
1040 * may not always do what the user expects, since drive-relative
1041 * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
1042 * set, in addition to truly relative symbolic links such as "Users" or
1043 * "Users\Public". However, WIMGAPI (as of Windows 8.1) has this same
1046 * Otherwise, as far as I can tell, the targets of symbolic links that
1047 * are NOT relative, as well as junctions (note: a mountpoint is the
1048 * sames thing as a junction), must be NT namespace paths, for example:
1050 * - \??\e:\Users\Public
1051 * - \DosDevices\e:\Users\Public
1052 * - \Device\HardDiskVolume4\Users\Public
1053 * - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
1054 * - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
1056 if (link_is_relative_symlink(&link))
1059 rel_target = winnt_relativize_link_target(link.substitute_name,
1060 link.substitute_name_nbytes,
1061 params->capture_root_ino,
1062 params->capture_root_dev);
1064 if (rel_target == link.substitute_name) {
1065 /* Target points outside of the tree being captured or had an
1066 * unrecognized path format. Don't adjust it. */
1067 return winnt_rpfix_progress(params, &link,
1068 WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK);
1071 /* We have an absolute target pointing within the directory being
1072 * captured. @rel_target is the suffix of the link target that is the
1073 * part relative to the directory being captured.
1075 * We will cut off the prefix before this part (which is the path to the
1076 * directory being captured) and add a dummy prefix. Since the process
1077 * will need to be reversed when applying the image, it doesn't matter
1078 * what exactly the prefix is, as long as it looks like an absolute
1081 static const wchar_t prefix[6] = L"\\??\\X:";
1082 static const size_t num_unprintable_chars = 4;
1084 size_t rel_target_nbytes =
1085 link.substitute_name_nbytes - ((const u8 *)rel_target -
1086 (const u8 *)link.substitute_name);
1088 wchar_t tmp[(sizeof(prefix) + rel_target_nbytes) / sizeof(wchar_t)];
1090 memcpy(tmp, prefix, sizeof(prefix));
1091 memcpy(tmp + ARRAY_LEN(prefix), rel_target, rel_target_nbytes);
1093 link.substitute_name = tmp;
1094 link.substitute_name_nbytes = sizeof(tmp);
1096 link.print_name = link.substitute_name + num_unprintable_chars;
1097 link.print_name_nbytes = link.substitute_name_nbytes -
1098 (num_unprintable_chars * sizeof(wchar_t));
1100 if (make_link_reparse_point(&link, rpbuf, rpbuflen_p))
1103 ret = winnt_rpfix_progress(params, &link,
1104 WIMLIB_SCAN_DENTRY_FIXED_SYMLINK);
1110 /* Load the reparse data of a file into the corresponding WIM inode. If the
1111 * reparse point is a symbolic link or junction with an absolute target and
1112 * RPFIX mode is enabled, then also rewrite its target to be relative to the
1114 static noinline_for_stack int
1115 winnt_load_reparse_data(HANDLE h, struct wim_inode *inode,
1116 struct winnt_scan_ctx *ctx)
1118 struct reparse_buffer_disk rpbuf;
1124 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1125 /* See comment above assign_stream_types_encrypted() */
1126 WARNING("Ignoring reparse data of encrypted file \"%ls\"",
1127 printable_path(ctx));
1131 status = winnt_fsctl(h, FSCTL_GET_REPARSE_POINT,
1132 NULL, 0, &rpbuf, sizeof(rpbuf), &len);
1133 if (!NT_SUCCESS(status)) {
1134 winnt_error(status, L"\"%ls\": Can't get reparse point",
1135 printable_path(ctx));
1136 return WIMLIB_ERR_READLINK;
1141 if (unlikely(rpbuflen < REPARSE_DATA_OFFSET)) {
1142 ERROR("\"%ls\": reparse point buffer is too short",
1143 printable_path(ctx));
1144 return WIMLIB_ERR_INVALID_REPARSE_DATA;
1147 if (le32_to_cpu(rpbuf.rptag) == WIM_IO_REPARSE_TAG_DEDUP) {
1149 * Windows treats Data Deduplication reparse points specially.
1150 * Reads from the unnamed data stream actually return the
1151 * redirected file contents, even with FILE_OPEN_REPARSE_POINT.
1152 * Deduplicated files also cannot be properly restored without
1153 * also restoring the "System Volume Information" directory,
1154 * which wimlib excludes by default. Therefore, the logical
1155 * behavior for us seems to be to ignore the reparse point and
1156 * treat the file as a normal file.
1158 inode->i_attributes &= ~FILE_ATTRIBUTE_REPARSE_POINT;
1162 if (ctx->params->add_flags & WIMLIB_ADD_FLAG_RPFIX) {
1163 ret = winnt_try_rpfix(&rpbuf, &rpbuflen, ctx->params);
1164 if (ret == RP_FIXED)
1165 inode->i_rp_flags &= ~WIM_RP_FLAG_NOT_FIXED;
1170 inode->i_reparse_tag = le32_to_cpu(rpbuf.rptag);
1171 inode->i_rp_reserved = le16_to_cpu(rpbuf.rpreserved);
1173 if (!inode_add_stream_with_data(inode,
1174 STREAM_TYPE_REPARSE_POINT,
1177 rpbuflen - REPARSE_DATA_OFFSET,
1178 ctx->params->blob_table))
1179 return WIMLIB_ERR_NOMEM;
1185 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
1188 *(u64*)_size_ret += len;
1189 return ERROR_SUCCESS;
1193 win32_get_encrypted_file_size(const wchar_t *path, bool is_dir, u64 *size_ret)
1201 flags |= CREATE_FOR_DIR;
1203 err = OpenEncryptedFileRaw(path, flags, &file_ctx);
1204 if (err != ERROR_SUCCESS) {
1206 L"Failed to open encrypted file \"%ls\" for raw read",
1208 return WIMLIB_ERR_OPEN;
1211 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
1212 size_ret, file_ctx);
1213 if (err != ERROR_SUCCESS) {
1215 L"Failed to read raw encrypted data from \"%ls\"",
1217 ret = WIMLIB_ERR_READ;
1221 CloseEncryptedFileRaw(file_ctx);
1226 winnt_scan_efsrpc_raw_data(struct wim_inode *inode,
1227 struct winnt_scan_ctx *ctx)
1229 wchar_t *path = ctx->params->cur_path;
1230 size_t path_nchars = ctx->params->cur_path_nchars;
1231 const bool is_dir = (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY);
1232 struct windows_file *windows_file;
1236 /* OpenEncryptedFileRaw() expects a Win32 name. */
1237 wimlib_assert(!wmemcmp(path, L"\\??\\", 4));
1240 ret = win32_get_encrypted_file_size(path, is_dir, &size);
1244 /* Empty EFSRPC data does not make sense */
1245 wimlib_assert(size != 0);
1247 windows_file = alloc_windows_file(path, path_nchars, NULL, 0,
1248 ctx->snapshot, true);
1249 ret = add_stream(inode, windows_file, size, STREAM_TYPE_EFSRPC_RAW_DATA,
1250 NO_STREAM_NAME, ctx->params->unhashed_blobs);
1257 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1258 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
1260 const wchar_t *sep, *type, *end;
1262 /* The stream name should be returned as :NAME:TYPE */
1263 if (raw_stream_name_nchars < 1)
1265 if (raw_stream_name[0] != L':')
1269 raw_stream_name_nchars--;
1271 end = raw_stream_name + raw_stream_name_nchars;
1273 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
1278 if (end - type != 5)
1281 if (wmemcmp(type, L"$DATA", 5))
1284 *stream_name_ret = raw_stream_name;
1285 *stream_name_nchars_ret = sep - raw_stream_name;
1290 winnt_scan_data_stream(wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1291 u64 stream_size, struct wim_inode *inode,
1292 struct winnt_scan_ctx *ctx)
1294 wchar_t *stream_name;
1295 size_t stream_name_nchars;
1296 struct windows_file *windows_file;
1298 /* Given the raw stream name (which is something like
1299 * :streamname:$DATA), extract just the stream name part (streamname).
1300 * Ignore any non-$DATA streams. */
1301 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
1302 (const wchar_t **)&stream_name,
1303 &stream_name_nchars))
1306 stream_name[stream_name_nchars] = L'\0';
1308 windows_file = alloc_windows_file(ctx->params->cur_path,
1309 ctx->params->cur_path_nchars,
1310 stream_name, stream_name_nchars,
1311 ctx->snapshot, false);
1312 return add_stream(inode, windows_file, stream_size, STREAM_TYPE_DATA,
1313 stream_name, ctx->params->unhashed_blobs);
1317 * Load information about the data streams of an open file into a WIM inode.
1319 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
1320 * and FindNextStream(). This is done for two reasons:
1322 * - FindFirstStream() opens its own handle to the file or directory and
1323 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
1324 * causing access denied errors on certain files (even when running as the
1326 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
1327 * and later, whereas the stream support in NtQueryInformationFile() was
1328 * already present in Windows XP.
1330 static noinline_for_stack int
1331 winnt_scan_data_streams(HANDLE h, struct wim_inode *inode, u64 file_size,
1332 struct winnt_scan_ctx *ctx)
1335 u8 _buf[4096] _aligned_attribute(8);
1338 IO_STATUS_BLOCK iosb;
1340 FILE_STREAM_INFORMATION *info;
1343 bufsize = sizeof(_buf);
1345 if (!(ctx->vol_flags & FILE_NAMED_STREAMS))
1348 /* Get a buffer containing the stream information. */
1349 while (!NT_SUCCESS(status = NtQueryInformationFile(h,
1353 FileStreamInformation)))
1357 case STATUS_BUFFER_OVERFLOW:
1363 newbuf = MALLOC(bufsize);
1365 newbuf = REALLOC(buf, bufsize);
1367 ret = WIMLIB_ERR_NOMEM;
1373 case STATUS_NOT_IMPLEMENTED:
1374 case STATUS_NOT_SUPPORTED:
1375 case STATUS_INVALID_INFO_CLASS:
1379 L"\"%ls\": Failed to query stream information",
1380 printable_path(ctx));
1381 ret = WIMLIB_ERR_READ;
1386 if (iosb.Information == 0) {
1387 /* No stream information. */
1392 /* Parse one or more stream information structures. */
1393 info = (FILE_STREAM_INFORMATION *)buf;
1395 /* Load the stream information. */
1396 ret = winnt_scan_data_stream(info->StreamName,
1397 info->StreamNameLength / 2,
1398 info->StreamSize.QuadPart,
1403 if (info->NextEntryOffset == 0) {
1404 /* No more stream information. */
1407 /* Advance to next stream information. */
1408 info = (FILE_STREAM_INFORMATION *)
1409 ((u8 *)info + info->NextEntryOffset);
1415 /* The volume does not support named streams. Only capture the unnamed
1417 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1418 FILE_ATTRIBUTE_REPARSE_POINT))
1425 wchar_t stream_name[] = L"::$DATA";
1426 ret = winnt_scan_data_stream(stream_name, 7, file_size,
1430 /* Free buffer if allocated on heap. */
1431 if (unlikely(buf != _buf))
1437 extract_starting_lcn(const RETRIEVAL_POINTERS_BUFFER *extents)
1439 if (extents->ExtentCount < 1)
1442 return extents->Extents[0].Lcn.QuadPart;
1445 static noinline_for_stack u64
1446 get_sort_key(HANDLE h)
1448 STARTING_VCN_INPUT_BUFFER in = { .StartingVcn.QuadPart = 0 };
1449 RETRIEVAL_POINTERS_BUFFER out;
1451 if (!NT_SUCCESS(winnt_fsctl(h, FSCTL_GET_RETRIEVAL_POINTERS,
1452 &in, sizeof(in), &out, sizeof(out), NULL)))
1455 return extract_starting_lcn(&out);
1459 set_sort_key(struct wim_inode *inode, u64 sort_key)
1461 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1462 struct wim_inode_stream *strm = &inode->i_streams[i];
1463 struct blob_descriptor *blob = stream_blob_resolved(strm);
1464 if (blob && blob->blob_location == BLOB_IN_WINDOWS_FILE)
1465 blob->windows_file->sort_key = sort_key;
1470 should_try_to_use_wimboot_hash(const struct wim_inode *inode,
1471 const struct winnt_scan_ctx *ctx)
1473 /* Directories and encrypted files aren't valid for external backing. */
1474 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1475 FILE_ATTRIBUTE_ENCRYPTED))
1478 /* If the file is a reparse point, then try the hash fixup if it's a WOF
1479 * reparse point and we're in WIMBOOT mode. Otherwise, try the hash
1480 * fixup if WOF may be attached. */
1481 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1482 return (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_WOF) &&
1483 (ctx->params->add_flags & WIMLIB_ADD_FLAG_WIMBOOT);
1484 return !ctx->wof_not_attached;
1488 * This function implements an optimization for capturing files from a
1489 * filesystem with a backing WIM(s). If a file is WIM-backed, then we can
1490 * retrieve the SHA-1 message digest of its original contents from its reparse
1491 * point. This may eliminate the need to read the file's data and/or allow the
1492 * file's data to be immediately deduplicated with existing data in the WIM.
1494 * If WOF is attached, then this function is merely an optimization, but
1495 * potentially a very effective one. If WOF is detached, then this function
1496 * really causes WIM-backed files to be, effectively, automatically
1497 * "dereferenced" when possible; the unnamed data stream is updated to reference
1498 * the original contents and the reparse point is removed.
1500 * This function returns 0 if the fixup succeeded or was intentionally not
1501 * executed. Otherwise it returns an error code.
1503 static noinline_for_stack int
1504 try_to_use_wimboot_hash(HANDLE h, struct wim_inode *inode,
1505 struct winnt_scan_ctx *ctx)
1507 struct blob_table *blob_table = ctx->params->blob_table;
1508 struct wim_inode_stream *reparse_strm = NULL;
1509 struct wim_inode_stream *strm;
1510 struct blob_descriptor *blob;
1511 u8 hash[SHA1_HASH_SIZE];
1514 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1515 struct reparse_buffer_disk rpbuf;
1517 struct wof_external_info wof_info;
1518 struct wim_provider_rpdata wim_info;
1519 } *rpdata = (void *)rpbuf.rpdata;
1520 struct blob_descriptor *reparse_blob;
1522 /* The file has a WOF reparse point, so WOF must be detached.
1523 * We can read the reparse point directly. */
1524 ctx->wof_not_attached = true;
1525 reparse_strm = inode_get_unnamed_stream(inode, STREAM_TYPE_REPARSE_POINT);
1526 reparse_blob = stream_blob_resolved(reparse_strm);
1528 if (!reparse_blob || reparse_blob->size < sizeof(*rpdata))
1529 return 0; /* Not a WIM-backed file */
1531 ret = read_blob_into_buf(reparse_blob, rpdata);
1535 if (rpdata->wof_info.version != WOF_CURRENT_VERSION ||
1536 rpdata->wof_info.provider != WOF_PROVIDER_WIM ||
1537 rpdata->wim_info.version != 2)
1538 return 0; /* Not a WIM-backed file */
1540 /* Okay, this is a WIM backed file. Get its SHA-1 hash. */
1541 copy_hash(hash, rpdata->wim_info.unnamed_data_stream_hash);
1544 struct wof_external_info wof_info;
1545 struct wim_provider_external_info wim_info;
1549 /* WOF may be attached. Try reading this file's external
1551 status = winnt_fsctl(h, FSCTL_GET_EXTERNAL_BACKING,
1552 NULL, 0, &out, sizeof(out), NULL);
1554 /* Is WOF not attached? */
1555 if (status == STATUS_INVALID_DEVICE_REQUEST ||
1556 status == STATUS_NOT_SUPPORTED) {
1557 ctx->wof_not_attached = true;
1561 /* Is this file not externally backed? */
1562 if (status == STATUS_OBJECT_NOT_EXTERNALLY_BACKED)
1565 /* Does this file have an unknown type of external backing that
1566 * needed a larger information buffer? */
1567 if (status == STATUS_BUFFER_TOO_SMALL)
1570 /* Was there some other failure? */
1571 if (status != STATUS_SUCCESS) {
1573 L"\"%ls\": FSCTL_GET_EXTERNAL_BACKING failed",
1574 printable_path(ctx));
1575 return WIMLIB_ERR_STAT;
1578 /* Is this file backed by a WIM? */
1579 if (out.wof_info.version != WOF_CURRENT_VERSION ||
1580 out.wof_info.provider != WOF_PROVIDER_WIM ||
1581 out.wim_info.version != WIM_PROVIDER_CURRENT_VERSION)
1584 /* Okay, this is a WIM backed file. Get its SHA-1 hash. */
1585 copy_hash(hash, out.wim_info.unnamed_data_stream_hash);
1588 /* If the file's unnamed data stream is nonempty, then fill in its hash
1589 * and deduplicate it if possible.
1591 * With WOF detached, we require that the blob *must* de-duplicable for
1592 * any action can be taken, since without WOF we can't fall back to
1593 * getting the "dereferenced" data by reading the stream (the real
1594 * stream is sparse and contains all zeroes). */
1595 strm = inode_get_unnamed_data_stream(inode);
1596 if (strm && (blob = stream_blob_resolved(strm))) {
1597 struct blob_descriptor **back_ptr;
1599 if (reparse_strm && !lookup_blob(blob_table, hash))
1601 back_ptr = retrieve_pointer_to_unhashed_blob(blob);
1602 copy_hash(blob->hash, hash);
1603 if (after_blob_hashed(blob, back_ptr, blob_table) != blob)
1604 free_blob_descriptor(blob);
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] _aligned_attribute(8);
1658 FILE_FS_ATTRIBUTE_INFORMATION *attr_info = (void *)_attr_info;
1659 FILE_FS_VOLUME_INFORMATION vol_info;
1660 struct file_info file_info;
1661 IO_STATUS_BLOCK iosb;
1664 /* Get volume flags */
1665 status = NtQueryVolumeInformationFile(h, &iosb, attr_info,
1667 FileFsAttributeInformation);
1668 if (NT_SUCCESS(status)) {
1669 ctx->vol_flags = attr_info->FileSystemAttributes;
1670 ctx->is_ntfs = (attr_info->FileSystemNameLength == 4 * sizeof(wchar_t)) &&
1671 !wmemcmp(attr_info->FileSystemName, L"NTFS", 4);
1673 winnt_warning(status, L"\"%ls\": Can't get volume attributes",
1674 printable_path(ctx));
1677 /* Get volume ID. */
1678 status = NtQueryVolumeInformationFile(h, &iosb, &vol_info,
1680 FileFsVolumeInformation);
1681 if ((NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW) &&
1682 (iosb.Information >= offsetof(FILE_FS_VOLUME_INFORMATION,
1683 VolumeSerialNumber) +
1684 sizeof(vol_info.VolumeSerialNumber)))
1686 ctx->params->capture_root_dev = vol_info.VolumeSerialNumber;
1688 winnt_warning(status, L"\"%ls\": Can't get volume ID",
1689 printable_path(ctx));
1692 /* Get inode number. */
1693 status = get_file_info(h, &file_info);
1694 if (NT_SUCCESS(status)) {
1695 ctx->params->capture_root_ino = file_info.ino;
1697 winnt_warning(status, L"\"%ls\": Can't get file information",
1698 printable_path(ctx));
1703 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1705 const wchar_t *relative_path,
1706 size_t relative_path_nchars,
1707 const wchar_t *filename,
1708 struct winnt_scan_ctx *ctx)
1710 struct wim_dentry *root = NULL;
1711 struct wim_inode *inode = NULL;
1715 struct file_info file_info;
1718 ret = try_exclude(ctx->params);
1719 if (unlikely(ret < 0)) /* Excluded? */
1721 if (unlikely(ret > 0)) /* Error? */
1724 /* Open the file with permission to read metadata. Although we will
1725 * later need a handle with FILE_LIST_DIRECTORY permission (or,
1726 * equivalently, FILE_READ_DATA; they're the same numeric value) if the
1727 * file is a directory, it can significantly slow things down to request
1728 * this permission on all nondirectories. Perhaps it causes Windows to
1729 * start prefetching the file contents... */
1730 status = winnt_openat(cur_dir, relative_path, relative_path_nchars,
1731 FILE_READ_ATTRIBUTES | FILE_READ_EA |
1732 READ_CONTROL | ACCESS_SYSTEM_SECURITY,
1734 if (unlikely(!NT_SUCCESS(status))) {
1735 if (status == STATUS_DELETE_PENDING) {
1736 WARNING("\"%ls\": Deletion pending; skipping file",
1737 printable_path(ctx));
1741 if (status == STATUS_SHARING_VIOLATION) {
1742 ERROR("Can't open \"%ls\":\n"
1743 " File is in use by another process! "
1744 "Consider using snapshot (VSS) mode.",
1745 printable_path(ctx));
1746 ret = WIMLIB_ERR_OPEN;
1749 winnt_error(status, L"\"%ls\": Can't open file",
1750 printable_path(ctx));
1751 if (status == STATUS_FVE_LOCKED_VOLUME)
1752 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1754 ret = WIMLIB_ERR_OPEN;
1758 /* Get information about the file. */
1759 status = get_file_info(h, &file_info);
1760 if (!NT_SUCCESS(status)) {
1761 winnt_error(status, L"\"%ls\": Can't get file information",
1762 printable_path(ctx));
1763 ret = WIMLIB_ERR_STAT;
1767 /* Create a WIM dentry with an associated inode, which may be shared.
1769 * However, we need to explicitly check for directories and files with
1770 * only 1 link and refuse to hard link them. This is because Windows
1771 * has a bug where it can return duplicate File IDs for files and
1772 * directories on the FAT filesystem.
1774 * Since we don't follow mount points on Windows, we don't need to query
1775 * the volume ID per-file. Just once, for the root, is enough. But we
1776 * can't simply pass 0, because then there could be inode collisions
1777 * among multiple calls to win32_build_dentry_tree() that are scanning
1778 * files on different volumes. */
1779 ret = inode_table_new_dentry(ctx->params->inode_table,
1782 ctx->params->capture_root_dev,
1783 (file_info.num_links <= 1),
1788 /* Get the short (DOS) name of the file. */
1789 status = winnt_get_short_name(h, root);
1791 /* If we can't read the short filename for any reason other than
1792 * out-of-memory, just ignore the error and assume the file has no short
1793 * name. This shouldn't be an issue, since the short names are
1794 * essentially obsolete anyway. */
1795 if (unlikely(status == STATUS_NO_MEMORY)) {
1796 ret = WIMLIB_ERR_NOMEM;
1800 inode = root->d_inode;
1802 if (inode->i_nlink > 1) {
1803 /* Shared inode (hard link); skip reading per-inode information.
1808 inode->i_attributes = file_info.attributes;
1809 inode->i_creation_time = file_info.creation_time;
1810 inode->i_last_write_time = file_info.last_write_time;
1811 inode->i_last_access_time = file_info.last_access_time;
1813 /* Get the file's security descriptor, unless we are capturing in
1814 * NO_ACLS mode or the volume does not support security descriptors. */
1815 if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1816 && (ctx->vol_flags & FILE_PERSISTENT_ACLS))
1818 ret = winnt_load_security_descriptor(h, inode, ctx);
1823 /* Get the file's object ID. */
1824 ret = winnt_load_object_id(h, inode, ctx);
1828 /* Get the file's extended attributes. */
1829 if (unlikely(file_info.ea_size != 0)) {
1830 ret = winnt_load_xattrs(h, inode, ctx, file_info.ea_size);
1835 /* If this is a reparse point, load the reparse data. */
1836 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1837 ret = winnt_load_reparse_data(h, inode, ctx);
1842 sort_key = get_sort_key(h);
1844 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1845 /* Load information about the raw encrypted data. This is
1846 * needed for any directory or non-directory that has
1847 * FILE_ATTRIBUTE_ENCRYPTED set.
1849 * Note: since OpenEncryptedFileRaw() fails with
1850 * ERROR_SHARING_VIOLATION if there are any open handles to the
1851 * file, we have to close the file and re-open it later if
1855 ret = winnt_scan_efsrpc_raw_data(inode, ctx);
1860 * Load information about data streams (unnamed and named).
1862 * Skip this step for encrypted files, since the data from
1863 * ReadEncryptedFileRaw() already contains all data streams (and
1864 * they do in fact all get restored by WriteEncryptedFileRaw().)
1866 * Note: WIMGAPI (as of Windows 8.1) gets wrong and stores both
1867 * the EFSRPC data and the named data stream(s)...!
1869 ret = winnt_scan_data_streams(h,
1871 file_info.end_of_file,
1877 if (unlikely(should_try_to_use_wimboot_hash(inode, ctx))) {
1878 ret = try_to_use_wimboot_hash(h, inode, ctx);
1883 set_sort_key(inode, sort_key);
1885 if (inode_is_directory(inode)) {
1887 /* Directory: recurse to children. */
1889 /* Re-open the directory with FILE_LIST_DIRECTORY access. */
1894 status = winnt_openat(cur_dir, relative_path,
1895 relative_path_nchars, FILE_LIST_DIRECTORY,
1897 if (!NT_SUCCESS(status)) {
1898 winnt_error(status, L"\"%ls\": Can't open directory",
1899 printable_path(ctx));
1900 ret = WIMLIB_ERR_OPEN;
1903 ret = winnt_recurse_directory(h, root, ctx);
1910 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_OK, inode);
1912 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1916 if (unlikely(ret)) {
1917 free_dentry_tree(root, ctx->params->blob_table);
1919 ret = report_scan_error(ctx->params, ret);
1926 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_ctx *ctx)
1928 if (likely(ctx->num_get_sacl_priv_notheld == 0 &&
1929 ctx->num_get_sd_access_denied == 0))
1932 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1933 if (ctx->num_get_sacl_priv_notheld != 0) {
1934 WARNING("- Could not capture SACL (System Access Control List)\n"
1935 " on %lu files or directories.",
1936 ctx->num_get_sacl_priv_notheld);
1938 if (ctx->num_get_sd_access_denied != 0) {
1939 WARNING("- Could not capture security descriptor at all\n"
1940 " on %lu files or directories.",
1941 ctx->num_get_sd_access_denied);
1943 WARNING("To fully capture all security descriptors, run the program\n"
1944 " with Administrator rights.");
1947 /*----------------------------------------------------------------------------*
1948 * Fast MFT scan implementation *
1949 *----------------------------------------------------------------------------*/
1951 #define ENABLE_FAST_MFT_SCAN 1
1953 #ifdef ENABLE_FAST_MFT_SCAN
1956 u64 StartingCluster;
1961 u64 StartingFileReferenceNumber;
1962 u64 EndingFileReferenceNumber;
1963 } FILE_REFERENCE_RANGE;
1965 /* The FSCTL_QUERY_FILE_LAYOUT ioctl. This ioctl can be used on Windows 8 and
1966 * later to scan the MFT of an NTFS volume. */
1967 #define FSCTL_QUERY_FILE_LAYOUT CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 157, METHOD_NEITHER, FILE_ANY_ACCESS)
1969 /* The input to FSCTL_QUERY_FILE_LAYOUT */
1972 #define QUERY_FILE_LAYOUT_RESTART 0x00000001
1973 #define QUERY_FILE_LAYOUT_INCLUDE_NAMES 0x00000002
1974 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS 0x00000004
1975 #define QUERY_FILE_LAYOUT_INCLUDE_EXTENTS 0x00000008
1976 #define QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO 0x00000010
1977 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED 0x00000020
1979 #define QUERY_FILE_LAYOUT_FILTER_TYPE_NONE 0
1980 #define QUERY_FILE_LAYOUT_FILTER_TYPE_CLUSTERS 1
1981 #define QUERY_FILE_LAYOUT_FILTER_TYPE_FILEID 2
1982 #define QUERY_FILE_LAYOUT_NUM_FILTER_TYPES 3
1986 CLUSTER_RANGE ClusterRanges[1];
1987 FILE_REFERENCE_RANGE FileReferenceRanges[1];
1989 } QUERY_FILE_LAYOUT_INPUT;
1991 /* The header of the buffer returned by FSCTL_QUERY_FILE_LAYOUT */
1994 u32 FirstFileOffset;
1995 #define QUERY_FILE_LAYOUT_SINGLE_INSTANCED 0x00000001
1998 } QUERY_FILE_LAYOUT_OUTPUT;
2000 /* Inode information returned by FSCTL_QUERY_FILE_LAYOUT */
2006 u64 FileReferenceNumber;
2007 u32 FirstNameOffset;
2008 u32 FirstStreamOffset;
2009 u32 ExtraInfoOffset;
2011 } FILE_LAYOUT_ENTRY;
2013 /* Extra inode information returned by FSCTL_QUERY_FILE_LAYOUT */
2025 } FILE_LAYOUT_INFO_ENTRY;
2027 /* Filename (or dentry) information returned by FSCTL_QUERY_FILE_LAYOUT */
2030 #define FILE_LAYOUT_NAME_ENTRY_PRIMARY 0x00000001
2031 #define FILE_LAYOUT_NAME_ENTRY_DOS 0x00000002
2033 u64 ParentFileReferenceNumber;
2036 wchar_t FileName[1];
2037 } FILE_LAYOUT_NAME_ENTRY;
2039 /* Stream information returned by FSCTL_QUERY_FILE_LAYOUT */
2042 u32 NextStreamOffset;
2043 #define STREAM_LAYOUT_ENTRY_IMMOVABLE 0x00000001
2044 #define STREAM_LAYOUT_ENTRY_PINNED 0x00000002
2045 #define STREAM_LAYOUT_ENTRY_RESIDENT 0x00000004
2046 #define STREAM_LAYOUT_ENTRY_NO_CLUSTERS_ALLOCATED 0x00000008
2048 u32 ExtentInformationOffset;
2053 u32 StreamIdentifierLength;
2054 wchar_t StreamIdentifier[1];
2055 } STREAM_LAYOUT_ENTRY;
2059 #define STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS 0x00000001
2060 #define STREAM_EXTENT_ENTRY_ALL_EXTENTS 0x00000002
2063 RETRIEVAL_POINTERS_BUFFER RetrievalPointers;
2064 } ExtentInformation;
2065 } STREAM_EXTENT_ENTRY;
2067 /* Extract the MFT number part of the full inode number */
2068 #define NTFS_MFT_NO(ref) ((ref) & (((u64)1 << 48) - 1))
2070 /* Is the file the root directory of the NTFS volume? The root directory always
2071 * occupies MFT record 5. */
2072 #define NTFS_IS_ROOT_FILE(ino) (NTFS_MFT_NO(ino) == 5)
2074 /* Is the file a special NTFS file, other than the root directory? The special
2075 * files are the first 16 records in the MFT. */
2076 #define NTFS_IS_SPECIAL_FILE(ino) \
2077 (NTFS_MFT_NO(ino) <= 15 && !NTFS_IS_ROOT_FILE(ino))
2079 #define NTFS_SPECIAL_STREAM_OBJECT_ID 0x00000001
2080 #define NTFS_SPECIAL_STREAM_EA 0x00000002
2081 #define NTFS_SPECIAL_STREAM_EA_INFORMATION 0x00000004
2083 /* Intermediate inode structure. This is used to temporarily save information
2084 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_inode'. */
2086 struct avl_tree_node index_node;
2089 u64 last_access_time;
2090 u64 last_write_time;
2096 u32 special_streams;
2097 u32 first_stream_offset;
2098 struct ntfs_dentry *first_child;
2099 wchar_t short_name[13];
2102 /* Intermediate dentry structure. This is used to temporarily save information
2103 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_dentry'. */
2104 struct ntfs_dentry {
2105 u32 offset_from_inode : 31;
2108 /* Note: build_children_lists() replaces 'parent_ino' with
2111 struct ntfs_dentry *next_child;
2116 /* Intermediate stream structure. This is used to temporarily save information
2117 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct
2118 * wim_inode_stream'. */
2119 struct ntfs_stream {
2124 /* Map of all known NTFS inodes, keyed by inode number */
2125 struct ntfs_inode_map {
2126 struct avl_tree_node *root;
2129 #define NTFS_INODE(node) \
2130 avl_tree_entry((node), struct ntfs_inode, index_node)
2132 #define SKIP_ALIGNED(p, size) ((void *)(p) + ALIGN((size), 8))
2134 /* Get a pointer to the first dentry of the inode. */
2135 #define FIRST_DENTRY(ni) SKIP_ALIGNED((ni), sizeof(struct ntfs_inode))
2137 /* Get a pointer to the first stream of the inode. */
2138 #define FIRST_STREAM(ni) ((const void *)ni + ni->first_stream_offset)
2140 /* Advance to the next dentry of the inode. */
2141 #define NEXT_DENTRY(nd) SKIP_ALIGNED((nd), sizeof(struct ntfs_dentry) + \
2142 (wcslen((nd)->name) + 1) * sizeof(wchar_t))
2144 /* Advance to the next stream of the inode. */
2145 #define NEXT_STREAM(ns) SKIP_ALIGNED((ns), sizeof(struct ntfs_stream) + \
2146 (wcslen((ns)->name) + 1) * sizeof(wchar_t))
2149 _avl_cmp_ntfs_inodes(const struct avl_tree_node *node1,
2150 const struct avl_tree_node *node2)
2152 return cmp_u64(NTFS_INODE(node1)->ino, NTFS_INODE(node2)->ino);
2155 /* Adds an NTFS inode to the map. */
2157 ntfs_inode_map_add_inode(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2159 if (avl_tree_insert(&map->root, &ni->index_node, _avl_cmp_ntfs_inodes)) {
2160 WARNING("Inode 0x%016"PRIx64" is a duplicate!", ni->ino);
2165 /* Find an ntfs_inode in the map by inode number. Returns NULL if not found. */
2166 static struct ntfs_inode *
2167 ntfs_inode_map_lookup(struct ntfs_inode_map *map, u64 ino)
2169 struct ntfs_inode tmp;
2170 struct avl_tree_node *res;
2173 res = avl_tree_lookup_node(map->root, &tmp.index_node, _avl_cmp_ntfs_inodes);
2176 return NTFS_INODE(res);
2179 /* Remove an ntfs_inode from the map and free it. */
2181 ntfs_inode_map_remove(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2183 avl_tree_remove(&map->root, &ni->index_node);
2187 /* Free all ntfs_inodes in the map. */
2189 ntfs_inode_map_destroy(struct ntfs_inode_map *map)
2191 struct ntfs_inode *ni;
2193 avl_tree_for_each_in_postorder(ni, map->root, struct ntfs_inode, index_node)
2198 file_has_streams(const FILE_LAYOUT_ENTRY *file)
2200 return (file->FirstStreamOffset != 0) &&
2201 !(file->FileAttributes & FILE_ATTRIBUTE_ENCRYPTED);
2205 is_valid_name_entry(const FILE_LAYOUT_NAME_ENTRY *name)
2207 return name->FileNameLength > 0 &&
2208 name->FileNameLength % 2 == 0 &&
2209 !wmemchr(name->FileName, L'\0', name->FileNameLength / 2) &&
2210 (!(name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) ||
2211 name->FileNameLength <= 24);
2214 /* Validate the FILE_LAYOUT_NAME_ENTRYs of the specified file and compute the
2215 * total length in bytes of the ntfs_dentry structures needed to hold the name
2218 validate_names_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2219 size_t *total_length_ret)
2221 const FILE_LAYOUT_NAME_ENTRY *name =
2222 (const void *)file + file->FirstNameOffset;
2224 size_t num_long_names = 0;
2227 if (unlikely(!is_valid_name_entry(name))) {
2228 ERROR("Invalid FILE_LAYOUT_NAME_ENTRY! "
2229 "FileReferenceNumber=0x%016"PRIx64", "
2230 "FileNameLength=%"PRIu32", "
2231 "FileName=%.*ls, Flags=0x%08"PRIx32,
2232 file->FileReferenceNumber,
2233 name->FileNameLength,
2234 (int)(name->FileNameLength / 2),
2235 name->FileName, name->Flags);
2236 return WIMLIB_ERR_UNSUPPORTED;
2238 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2240 total += ALIGN(sizeof(struct ntfs_dentry) +
2241 name->FileNameLength + sizeof(wchar_t),
2244 if (name->NextNameOffset == 0)
2246 name = (const void *)name + name->NextNameOffset;
2249 if (unlikely(num_long_names == 0)) {
2250 ERROR("Inode 0x%016"PRIx64" has no long names!",
2251 file->FileReferenceNumber);
2252 return WIMLIB_ERR_UNSUPPORTED;
2255 *total_length_ret = total;
2260 is_valid_stream_entry(const STREAM_LAYOUT_ENTRY *stream)
2262 return stream->StreamIdentifierLength % 2 == 0 &&
2263 !wmemchr(stream->StreamIdentifier , L'\0',
2264 stream->StreamIdentifierLength / 2);
2267 /* assumes that 'id' is a wide string literal */
2268 #define stream_has_identifier(stream, id) \
2269 ((stream)->StreamIdentifierLength == sizeof(id) - 2 && \
2270 !memcmp((stream)->StreamIdentifier, id, sizeof(id) - 2))
2272 * If the specified STREAM_LAYOUT_ENTRY represents a DATA stream as opposed to
2273 * some other type of NTFS stream such as a STANDARD_INFORMATION stream, return
2274 * true and set *stream_name_ret and *stream_name_nchars_ret to specify just the
2275 * stream name. For example, ":foo:$DATA" would become "foo" with length 3
2276 * characters. Otherwise return false.
2279 use_stream(const FILE_LAYOUT_ENTRY *file, const STREAM_LAYOUT_ENTRY *stream,
2280 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
2282 const wchar_t *stream_name;
2283 size_t stream_name_nchars;
2285 if (stream->StreamIdentifierLength == 0) {
2286 /* The unnamed data stream may be given as an empty string
2287 * rather than as "::$DATA". Handle it both ways. */
2289 stream_name_nchars = 0;
2290 } else if (!get_data_stream_name(stream->StreamIdentifier,
2291 stream->StreamIdentifierLength / 2,
2292 &stream_name, &stream_name_nchars))
2295 /* Skip the unnamed data stream for directories. */
2296 if (stream_name_nchars == 0 &&
2297 (file->FileAttributes & FILE_ATTRIBUTE_DIRECTORY))
2300 *stream_name_ret = stream_name;
2301 *stream_name_nchars_ret = stream_name_nchars;
2305 /* Validate the STREAM_LAYOUT_ENTRYs of the specified file and compute the total
2306 * length in bytes of the ntfs_stream structures needed to hold the stream
2307 * information. In addition, set *special_streams_ret to a bitmask of special
2308 * stream types that were found. */
2310 validate_streams_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2311 size_t *total_length_ret,
2312 u32 *special_streams_ret)
2314 const STREAM_LAYOUT_ENTRY *stream =
2315 (const void *)file + file->FirstStreamOffset;
2317 u32 special_streams = 0;
2320 const wchar_t *name;
2323 if (unlikely(!is_valid_stream_entry(stream))) {
2324 WARNING("Invalid STREAM_LAYOUT_ENTRY! "
2325 "FileReferenceNumber=0x%016"PRIx64", "
2326 "StreamIdentifierLength=%"PRIu32", "
2327 "StreamIdentifier=%.*ls",
2328 file->FileReferenceNumber,
2329 stream->StreamIdentifierLength,
2330 (int)(stream->StreamIdentifierLength / 2),
2331 stream->StreamIdentifier);
2332 return WIMLIB_ERR_UNSUPPORTED;
2335 if (use_stream(file, stream, &name, &name_nchars)) {
2336 total += ALIGN(sizeof(struct ntfs_stream) +
2337 (name_nchars + 1) * sizeof(wchar_t), 8);
2338 } else if (stream_has_identifier(stream, L"::$OBJECT_ID")) {
2339 special_streams |= NTFS_SPECIAL_STREAM_OBJECT_ID;
2340 } else if (stream_has_identifier(stream, L"::$EA")) {
2341 special_streams |= NTFS_SPECIAL_STREAM_EA;
2342 } else if (stream_has_identifier(stream, L"::$EA_INFORMATION")) {
2343 special_streams |= NTFS_SPECIAL_STREAM_EA_INFORMATION;
2345 if (stream->NextStreamOffset == 0)
2347 stream = (const void *)stream + stream->NextStreamOffset;
2350 *total_length_ret = total;
2351 *special_streams_ret = special_streams;
2356 load_name_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2359 const FILE_LAYOUT_NAME_ENTRY *name =
2360 (const void *)file + file->FirstNameOffset;
2362 struct ntfs_dentry *nd = p;
2363 /* Note that a name may be just a short (DOS) name, just a long
2364 * name, or both a short name and a long name. If there is a
2365 * short name, one name should also be marked as "primary" to
2366 * indicate which long name the short name is associated with.
2367 * Also, there should be at most one short name per inode. */
2368 if (name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) {
2369 memcpy(ni->short_name,
2370 name->FileName, name->FileNameLength);
2371 ni->short_name[name->FileNameLength / 2] = L'\0';
2373 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2375 nd->offset_from_inode = (u8 *)nd - (u8 *)ni;
2376 nd->is_primary = ((name->Flags &
2377 FILE_LAYOUT_NAME_ENTRY_PRIMARY) != 0);
2378 nd->parent_ino = name->ParentFileReferenceNumber;
2379 memcpy(nd->name, name->FileName, name->FileNameLength);
2380 nd->name[name->FileNameLength / 2] = L'\0';
2381 p += ALIGN(sizeof(struct ntfs_dentry) +
2382 name->FileNameLength + sizeof(wchar_t), 8);
2384 if (name->NextNameOffset == 0)
2386 name = (const void *)name + name->NextNameOffset;
2392 load_starting_lcn(const STREAM_LAYOUT_ENTRY *stream)
2394 const STREAM_EXTENT_ENTRY *entry;
2396 if (stream->ExtentInformationOffset == 0)
2399 entry = (const void *)stream + stream->ExtentInformationOffset;
2401 if (!(entry->Flags & STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS))
2404 return extract_starting_lcn(&entry->ExtentInformation.RetrievalPointers);
2408 load_stream_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2411 const STREAM_LAYOUT_ENTRY *stream =
2412 (const void *)file + file->FirstStreamOffset;
2413 const u32 first_stream_offset = (const u8 *)p - (const u8 *)ni;
2415 struct ntfs_stream *ns = p;
2416 const wchar_t *name;
2419 if (use_stream(file, stream, &name, &name_nchars)) {
2420 ni->first_stream_offset = first_stream_offset;
2422 if (name_nchars == 0)
2423 ni->starting_lcn = load_starting_lcn(stream);
2424 ns->size = stream->EndOfFile;
2425 wmemcpy(ns->name, name, name_nchars);
2426 ns->name[name_nchars] = L'\0';
2427 p += ALIGN(sizeof(struct ntfs_stream) +
2428 (name_nchars + 1) * sizeof(wchar_t), 8);
2430 if (stream->NextStreamOffset == 0)
2432 stream = (const void *)stream + stream->NextStreamOffset;
2437 /* Process the information for a file given by FSCTL_QUERY_FILE_LAYOUT. */
2439 load_one_file(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode_map *inode_map)
2441 const FILE_LAYOUT_INFO_ENTRY *info =
2442 (const void *)file + file->ExtraInfoOffset;
2444 struct ntfs_inode *ni;
2448 u32 special_streams = 0;
2450 inode_size = ALIGN(sizeof(struct ntfs_inode), 8);
2452 /* The root file should have no names, and all other files should have
2453 * at least one name. But just in case, we ignore the names of the root
2454 * file, and we ignore any non-root file with no names. */
2455 if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber)) {
2456 if (file->FirstNameOffset == 0)
2458 ret = validate_names_and_compute_total_length(file, &n);
2464 if (file_has_streams(file)) {
2465 ret = validate_streams_and_compute_total_length(file, &n,
2472 /* To save memory, we allocate the ntfs_dentry's and ntfs_stream's in
2473 * the same memory block as their ntfs_inode. */
2474 ni = CALLOC(1, inode_size);
2476 return WIMLIB_ERR_NOMEM;
2478 ni->ino = file->FileReferenceNumber;
2479 ni->attributes = info->BasicInformation.FileAttributes;
2480 ni->creation_time = info->BasicInformation.CreationTime;
2481 ni->last_write_time = info->BasicInformation.LastWriteTime;
2482 ni->last_access_time = info->BasicInformation.LastAccessTime;
2483 ni->security_id = info->SecurityId;
2484 ni->special_streams = special_streams;
2486 p = FIRST_DENTRY(ni);
2488 if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber))
2489 p = load_name_information(file, ni, p);
2491 if (file_has_streams(file))
2492 p = load_stream_information(file, ni, p);
2494 wimlib_assert((u8 *)p - (u8 *)ni == inode_size);
2496 ntfs_inode_map_add_inode(inode_map, ni);
2501 * Quickly find all files on an NTFS volume by using FSCTL_QUERY_FILE_LAYOUT to
2502 * scan the MFT. The NTFS volume is specified by the NT namespace path @path.
2503 * For each file, allocate an 'ntfs_inode' structure for each file and add it to
2504 * 'inode_map' keyed by inode number. Include NTFS special files such as
2505 * $Bitmap (they will be removed later).
2508 load_files_from_mft(const wchar_t *path, struct ntfs_inode_map *inode_map)
2511 QUERY_FILE_LAYOUT_INPUT in = (QUERY_FILE_LAYOUT_INPUT) {
2513 .Flags = QUERY_FILE_LAYOUT_RESTART |
2514 QUERY_FILE_LAYOUT_INCLUDE_NAMES |
2515 QUERY_FILE_LAYOUT_INCLUDE_STREAMS |
2516 QUERY_FILE_LAYOUT_INCLUDE_EXTENTS |
2517 QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO |
2518 QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED,
2519 .FilterType = QUERY_FILE_LAYOUT_FILTER_TYPE_NONE,
2521 size_t outsize = 32768;
2522 QUERY_FILE_LAYOUT_OUTPUT *out = NULL;
2526 status = winnt_open(path, wcslen(path),
2527 FILE_READ_DATA | FILE_READ_ATTRIBUTES, &h);
2528 if (!NT_SUCCESS(status)) {
2529 ret = -1; /* Silently try standard recursive scan instead */
2534 /* Allocate a buffer for the output of the ioctl. */
2535 out = MALLOC(outsize);
2537 ret = WIMLIB_ERR_NOMEM;
2541 /* Execute FSCTL_QUERY_FILE_LAYOUT until it fails. */
2542 while (NT_SUCCESS(status = winnt_fsctl(h,
2543 FSCTL_QUERY_FILE_LAYOUT,
2545 out, outsize, NULL)))
2547 const FILE_LAYOUT_ENTRY *file =
2548 (const void *)out + out->FirstFileOffset;
2550 ret = load_one_file(file, inode_map);
2553 if (file->NextFileOffset == 0)
2555 file = (const void *)file + file->NextFileOffset;
2557 in.Flags &= ~QUERY_FILE_LAYOUT_RESTART;
2560 /* Enlarge the buffer if needed. */
2561 if (status != STATUS_BUFFER_TOO_SMALL)
2567 /* Normally, FSCTL_QUERY_FILE_LAYOUT fails with STATUS_END_OF_FILE after
2568 * all files have been enumerated. */
2569 if (status != STATUS_END_OF_FILE) {
2570 if (status == STATUS_INVALID_DEVICE_REQUEST /* old OS */ ||
2571 status == STATUS_INVALID_PARAMETER /* not root directory */ ) {
2572 /* Silently try standard recursive scan instead */
2576 L"Error enumerating files on volume \"%ls\"",
2578 /* Try standard recursive scan instead */
2579 ret = WIMLIB_ERR_UNSUPPORTED;
2590 /* Build the list of child dentries for each inode in @map. This is done by
2591 * iterating through each name of each inode and adding it to its parent's
2592 * children list. Note that every name should have a parent, i.e. should belong
2593 * to some directory. The root directory does not have any names. */
2595 build_children_lists(struct ntfs_inode_map *map, struct ntfs_inode **root_ret)
2597 struct ntfs_inode *ni;
2599 avl_tree_for_each_in_order(ni, map->root, struct ntfs_inode, index_node)
2601 struct ntfs_dentry *nd;
2604 if (NTFS_IS_ROOT_FILE(ni->ino)) {
2609 n = ni->num_aliases;
2610 nd = FIRST_DENTRY(ni);
2612 struct ntfs_inode *parent;
2614 parent = ntfs_inode_map_lookup(map, nd->parent_ino);
2615 if (unlikely(!parent)) {
2616 ERROR("Parent inode 0x%016"PRIx64" of"
2617 "directory entry \"%ls\" (inode "
2618 "0x%016"PRIx64") was missing from the "
2620 nd->parent_ino, nd->name, ni->ino);
2621 return WIMLIB_ERR_UNSUPPORTED;
2623 nd->next_child = parent->first_child;
2624 parent->first_child = nd;
2627 nd = NEXT_DENTRY(nd);
2633 struct security_map_node {
2634 struct avl_tree_node index_node;
2635 u32 disk_security_id;
2636 u32 wim_security_id;
2639 /* Map from disk security IDs to WIM security IDs */
2640 struct security_map {
2641 struct avl_tree_node *root;
2644 #define SECURITY_MAP_NODE(node) \
2645 avl_tree_entry((node), struct security_map_node, index_node)
2648 _avl_cmp_security_map_nodes(const struct avl_tree_node *node1,
2649 const struct avl_tree_node *node2)
2651 return cmp_u32(SECURITY_MAP_NODE(node1)->disk_security_id,
2652 SECURITY_MAP_NODE(node2)->disk_security_id);
2656 security_map_lookup(struct security_map *map, u32 disk_security_id)
2658 struct security_map_node tmp;
2659 const struct avl_tree_node *res;
2661 if (disk_security_id == 0) /* No on-disk security ID; uncacheable */
2664 tmp.disk_security_id = disk_security_id;
2665 res = avl_tree_lookup_node(map->root, &tmp.index_node,
2666 _avl_cmp_security_map_nodes);
2669 return SECURITY_MAP_NODE(res)->wim_security_id;
2673 security_map_insert(struct security_map *map, u32 disk_security_id,
2674 u32 wim_security_id)
2676 struct security_map_node *node;
2678 if (disk_security_id == 0) /* No on-disk security ID; uncacheable */
2681 node = MALLOC(sizeof(*node));
2683 return WIMLIB_ERR_NOMEM;
2685 node->disk_security_id = disk_security_id;
2686 node->wim_security_id = wim_security_id;
2687 avl_tree_insert(&map->root, &node->index_node,
2688 _avl_cmp_security_map_nodes);
2693 security_map_destroy(struct security_map *map)
2695 struct security_map_node *node;
2697 avl_tree_for_each_in_postorder(node, map->root,
2698 struct security_map_node, index_node)
2703 * Turn our temporary NTFS structures into the final WIM structures:
2705 * ntfs_inode => wim_inode
2706 * ntfs_dentry => wim_dentry
2707 * ntfs_stream => wim_inode_stream
2709 * This also handles things such as exclusions and issuing progress messages.
2710 * It's similar to winnt_build_dentry_tree_recursive(), but this is much faster
2711 * because almost all information we need is already loaded in memory in the
2712 * ntfs_* structures. However, in some cases we still fall back to
2713 * winnt_build_dentry_tree_recursive() and/or opening the file.
2716 generate_wim_structures_recursive(struct wim_dentry **root_ret,
2717 const wchar_t *filename, bool is_primary_name,
2718 struct ntfs_inode *ni,
2719 struct winnt_scan_ctx *ctx,
2720 struct ntfs_inode_map *inode_map,
2721 struct security_map *security_map)
2724 struct wim_dentry *root = NULL;
2725 struct wim_inode *inode = NULL;
2726 const struct ntfs_stream *ns;
2728 /* Completely ignore NTFS special files. */
2729 if (NTFS_IS_SPECIAL_FILE(ni->ino))
2732 /* Fall back to a recursive scan for unhandled cases. Reparse points,
2733 * in particular, can't be properly handled here because a commonly used
2734 * filter driver (WOF) hides reparse points from regular filesystem APIs
2735 * but not from FSCTL_QUERY_FILE_LAYOUT. */
2736 if (ni->attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
2737 FILE_ATTRIBUTE_ENCRYPTED) ||
2738 ni->special_streams != 0)
2740 ret = winnt_build_dentry_tree_recursive(&root,
2742 ctx->params->cur_path,
2743 ctx->params->cur_path_nchars,
2749 /* Test for exclusion based on path. */
2750 ret = try_exclude(ctx->params);
2751 if (unlikely(ret < 0)) /* Excluded? */
2753 if (unlikely(ret > 0)) /* Error? */
2756 /* Create the WIM dentry and possibly a new WIM inode */
2757 ret = inode_table_new_dentry(ctx->params->inode_table, filename,
2758 ni->ino, ctx->params->capture_root_dev,
2763 inode = root->d_inode;
2765 /* Set the short name if needed. */
2766 if (is_primary_name && *ni->short_name) {
2767 size_t nbytes = wcslen(ni->short_name) * sizeof(wchar_t);
2768 root->d_short_name = memdup(ni->short_name,
2769 nbytes + sizeof(wchar_t));
2770 if (!root->d_short_name) {
2771 ret = WIMLIB_ERR_NOMEM;
2774 root->d_short_name_nbytes = nbytes;
2777 if (inode->i_nlink > 1) { /* Already seen this inode? */
2782 /* The file attributes and timestamps were cached from the MFT. */
2783 inode->i_attributes = ni->attributes;
2784 inode->i_creation_time = ni->creation_time;
2785 inode->i_last_write_time = ni->last_write_time;
2786 inode->i_last_access_time = ni->last_access_time;
2788 /* Set the security descriptor if needed. */
2789 if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)) {
2790 /* Look up the WIM security ID that corresponds to the on-disk
2792 s32 wim_security_id =
2793 security_map_lookup(security_map, ni->security_id);
2794 if (likely(wim_security_id >= 0)) {
2795 /* The mapping for this security ID is already cached.*/
2796 inode->i_security_id = wim_security_id;
2801 /* Create a mapping for this security ID and insert it
2802 * into the security map. */
2804 status = winnt_open(ctx->params->cur_path,
2805 ctx->params->cur_path_nchars,
2807 ACCESS_SYSTEM_SECURITY, &h);
2808 if (!NT_SUCCESS(status)) {
2809 winnt_error(status, L"Can't open \"%ls\" to "
2810 "read security descriptor",
2811 printable_path(ctx));
2812 ret = WIMLIB_ERR_OPEN;
2815 ret = winnt_load_security_descriptor(h, inode, ctx);
2820 ret = security_map_insert(security_map, ni->security_id,
2821 inode->i_security_id);
2827 /* Add data streams based on the cached information from the MFT. */
2828 ns = FIRST_STREAM(ni);
2829 for (u32 i = 0; i < ni->num_streams; i++) {
2830 struct windows_file *windows_file;
2832 /* Reference the stream by path if it's a named data stream, or
2833 * if the volume doesn't support "open by file ID", or if the
2834 * application hasn't explicitly opted in to "open by file ID".
2835 * Otherwise, only save the inode number (file ID). */
2837 !(ctx->vol_flags & FILE_SUPPORTS_OPEN_BY_FILE_ID) ||
2838 !(ctx->params->add_flags & WIMLIB_ADD_FLAG_FILE_PATHS_UNNEEDED))
2840 windows_file = alloc_windows_file(ctx->params->cur_path,
2841 ctx->params->cur_path_nchars,
2847 windows_file = alloc_windows_file_for_file_id(ni->ino,
2848 ctx->params->cur_path,
2849 ctx->params->root_path_nchars,
2853 ret = add_stream(inode, windows_file, ns->size,
2854 STREAM_TYPE_DATA, ns->name,
2855 ctx->params->unhashed_blobs);
2858 ns = NEXT_STREAM(ns);
2861 set_sort_key(inode, ni->starting_lcn);
2863 /* If processing a directory, then recurse to its children. In this
2864 * version there is no need to go to disk, as we already have the list
2865 * of children cached from the MFT. */
2866 if (inode_is_directory(inode)) {
2867 const struct ntfs_dentry *nd = ni->first_child;
2869 while (nd != NULL) {
2870 size_t orig_path_nchars;
2871 struct wim_dentry *child;
2872 const struct ntfs_dentry *next = nd->next_child;
2874 ret = WIMLIB_ERR_NOMEM;
2875 if (!pathbuf_append_name(ctx->params, nd->name,
2880 ret = generate_wim_structures_recursive(
2884 (void *)nd - nd->offset_from_inode,
2889 pathbuf_truncate(ctx->params, orig_path_nchars);
2894 attach_scanned_tree(root, child, ctx->params->blob_table);
2901 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_OK, inode);
2903 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
2905 if (--ni->num_aliases == 0) {
2906 /* Memory usage optimization: when we don't need the ntfs_inode
2907 * (and its names and streams) anymore, free it. */
2908 ntfs_inode_map_remove(inode_map, ni);
2910 if (unlikely(ret)) {
2911 free_dentry_tree(root, ctx->params->blob_table);
2919 winnt_build_dentry_tree_fast(struct wim_dentry **root_ret,
2920 struct winnt_scan_ctx *ctx)
2922 struct ntfs_inode_map inode_map = { .root = NULL };
2923 struct security_map security_map = { .root = NULL };
2924 struct ntfs_inode *root = NULL;
2925 wchar_t *path = ctx->params->cur_path;
2926 size_t path_nchars = ctx->params->cur_path_nchars;
2930 adjust_path = (path[path_nchars - 1] == L'\\');
2932 path[path_nchars - 1] = L'\0';
2934 ret = load_files_from_mft(path, &inode_map);
2937 path[path_nchars - 1] = L'\\';
2942 ret = build_children_lists(&inode_map, &root);
2947 ERROR("The MFT listing for volume \"%ls\" did not include a "
2948 "root directory!", path);
2949 ret = WIMLIB_ERR_UNSUPPORTED;
2953 root->num_aliases = 1;
2955 ret = generate_wim_structures_recursive(root_ret, L"", false, root, ctx,
2956 &inode_map, &security_map);
2958 ntfs_inode_map_destroy(&inode_map);
2959 security_map_destroy(&security_map);
2963 #endif /* ENABLE_FAST_MFT_SCAN */
2965 /*----------------------------------------------------------------------------*
2966 * Entry point for directory tree scans on Windows *
2967 *----------------------------------------------------------------------------*/
2970 win32_build_dentry_tree(struct wim_dentry **root_ret,
2971 const wchar_t *root_disk_path,
2972 struct scan_params *params)
2974 struct winnt_scan_ctx ctx = { .params = params };
2975 UNICODE_STRING ntpath;
2980 if (params->add_flags & WIMLIB_ADD_FLAG_SNAPSHOT)
2981 ret = vss_create_snapshot(root_disk_path, &ntpath, &ctx.snapshot);
2983 ret = win32_path_to_nt_path(root_disk_path, &ntpath);
2988 if (ntpath.Length < 4 * sizeof(wchar_t) ||
2989 wmemcmp(ntpath.Buffer, L"\\??\\", 4))
2991 ERROR("\"%ls\": unrecognized path format", root_disk_path);
2992 ret = WIMLIB_ERR_INVALID_PARAM;
2994 ret = pathbuf_init(params, ntpath.Buffer);
2996 HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
3000 status = winnt_open(params->cur_path, params->cur_path_nchars,
3001 FILE_READ_ATTRIBUTES, &h);
3002 if (!NT_SUCCESS(status)) {
3003 winnt_error(status, L"Can't open \"%ls\"", root_disk_path);
3004 if (status == STATUS_FVE_LOCKED_VOLUME)
3005 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
3007 ret = WIMLIB_ERR_OPEN;
3011 get_volume_information(h, &ctx);
3015 #ifdef ENABLE_FAST_MFT_SCAN
3016 if (ctx.is_ntfs && !_wgetenv(L"WIMLIB_DISABLE_QUERY_FILE_LAYOUT")) {
3017 ret = winnt_build_dentry_tree_fast(root_ret, &ctx);
3018 if (ret >= 0 && ret != WIMLIB_ERR_UNSUPPORTED)
3021 WARNING("A problem occurred during the fast MFT scan.\n"
3022 " Falling back to the standard "
3023 "recursive directory tree scan.");
3027 ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
3029 params->cur_path_nchars,
3032 vss_put_snapshot(ctx.snapshot);
3034 winnt_do_scan_warnings(root_disk_path, &ctx);
3038 #endif /* __WIN32__ */