2 * win32_capture.c - Windows-specific code for capturing files into a WIM image.
4 * This now uses the native Windows NT API a lot and not just Win32.
8 * Copyright (C) 2013-2018 Eric Biggers
10 * This file is free software; you can redistribute it and/or modify it under
11 * the terms of the GNU Lesser General Public License as published by the Free
12 * Software Foundation; either version 3 of the License, or (at your option) any
15 * This file is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this file; if not, see http://www.gnu.org/licenses/.
30 #include "wimlib/win32_common.h"
32 #include "wimlib/assert.h"
33 #include "wimlib/blob_table.h"
34 #include "wimlib/dentry.h"
35 #include "wimlib/encoding.h"
36 #include "wimlib/endianness.h"
37 #include "wimlib/error.h"
38 #include "wimlib/object_id.h"
39 #include "wimlib/paths.h"
40 #include "wimlib/reparse.h"
41 #include "wimlib/scan.h"
42 #include "wimlib/win32_vss.h"
43 #include "wimlib/wof.h"
44 #include "wimlib/xattr.h"
46 struct winnt_scan_ctx {
47 struct scan_params *params;
50 unsigned long num_get_sd_access_denied;
51 unsigned long num_get_sacl_priv_notheld;
53 /* True if WOF is definitely not attached to the volume being scanned;
54 * false if it may be */
55 bool wof_not_attached;
57 /* A reference to the VSS snapshot being used, or NULL if none */
58 struct vss_snapshot *snapshot;
61 static inline const wchar_t *
62 printable_path(const struct winnt_scan_ctx *ctx)
64 /* Skip over \\?\ or \??\ */
65 return ctx->params->cur_path + 4;
68 /* Description of where data is located on a Windows filesystem */
71 /* Is the data the raw encrypted data of an EFS-encrypted file? */
74 /* Is this file "open by file ID" rather than the regular "open by
75 * path"? "Open by file ID" uses resources more efficiently. */
78 /* The file's LCN (logical cluster number) for sorting, or 0 if unknown.
82 /* Length of the path in bytes, excluding the null terminator if
86 /* A reference to the VSS snapshot containing the file, or NULL if none.
88 struct vss_snapshot *snapshot;
90 /* The path to the file. If 'is_encrypted=0' this is an NT namespace
91 * path; if 'is_encrypted=1' this is a Win32 namespace path. If
92 * 'is_file_id=0', then the path is null-terminated. If 'is_file_id=1'
93 * (only allowed with 'is_encrypted=0') the path ends with a binary file
94 * ID and may not be null-terminated. */
98 /* Allocate a structure to describe the location of a data stream by path. */
99 static struct windows_file *
100 alloc_windows_file(const wchar_t *path, size_t path_nchars,
101 const wchar_t *stream_name, size_t stream_name_nchars,
102 struct vss_snapshot *snapshot, bool is_encrypted)
104 size_t full_path_nbytes;
105 struct windows_file *file;
108 full_path_nbytes = path_nchars * sizeof(wchar_t);
109 if (stream_name_nchars)
110 full_path_nbytes += (1 + stream_name_nchars) * sizeof(wchar_t);
112 file = MALLOC(sizeof(struct windows_file) + full_path_nbytes +
117 file->is_encrypted = is_encrypted;
118 file->is_file_id = 0;
120 file->path_nbytes = full_path_nbytes;
121 file->snapshot = vss_get_snapshot(snapshot);
122 p = wmempcpy(file->path, path, path_nchars);
123 if (stream_name_nchars) {
124 /* Named data stream */
126 p = wmempcpy(p, stream_name, stream_name_nchars);
132 /* Allocate a structure to describe the location of a file by ID. */
133 static struct windows_file *
134 alloc_windows_file_for_file_id(u64 file_id, const wchar_t *root_path,
135 size_t root_path_nchars,
136 struct vss_snapshot *snapshot)
138 size_t full_path_nbytes;
139 struct windows_file *file;
142 full_path_nbytes = (root_path_nchars * sizeof(wchar_t)) +
144 file = MALLOC(sizeof(struct windows_file) + full_path_nbytes +
149 file->is_encrypted = 0;
150 file->is_file_id = 1;
152 file->path_nbytes = full_path_nbytes;
153 file->snapshot = vss_get_snapshot(snapshot);
154 p = wmempcpy(file->path, root_path, root_path_nchars);
155 p = mempcpy(p, &file_id, sizeof(file_id));
160 /* Add a stream, located on a Windows filesystem, to the specified WIM inode. */
162 add_stream(struct wim_inode *inode, struct windows_file *windows_file,
163 u64 stream_size, int stream_type, const utf16lechar *stream_name,
164 struct list_head *unhashed_blobs)
166 struct blob_descriptor *blob = NULL;
167 struct wim_inode_stream *strm;
173 /* If the stream is nonempty, create a blob descriptor for it. */
175 blob = new_blob_descriptor();
178 blob->windows_file = windows_file;
179 blob->blob_location = BLOB_IN_WINDOWS_FILE;
180 blob->file_inode = inode;
181 blob->size = stream_size;
185 strm = inode_add_stream(inode, stream_type, stream_name, blob);
189 prepare_unhashed_blob(blob, inode, strm->stream_id, unhashed_blobs);
193 free_windows_file(windows_file);
197 free_blob_descriptor(blob);
198 ret = WIMLIB_ERR_NOMEM;
202 struct windows_file *
203 clone_windows_file(const struct windows_file *file)
205 struct windows_file *new;
207 new = memdup(file, sizeof(*file) + file->path_nbytes + sizeof(wchar_t));
209 vss_get_snapshot(new->snapshot);
214 free_windows_file(struct windows_file *file)
216 vss_put_snapshot(file->snapshot);
221 cmp_windows_files(const struct windows_file *file1,
222 const struct windows_file *file2)
224 /* Compare by starting LCN (logical cluster number) */
225 int v = cmp_u64(file1->sort_key, file2->sort_key);
229 /* Fall back to comparing files by path (arbitrary heuristic). */
230 v = memcmp(file1->path, file2->path,
231 min(file1->path_nbytes, file2->path_nbytes));
235 return cmp_u32(file1->path_nbytes, file2->path_nbytes);
239 get_windows_file_path(const struct windows_file *file)
245 * Open the file named by the NT namespace path @path of length @path_nchars
246 * characters. If @cur_dir is not NULL then the path is given relative to
247 * @cur_dir; otherwise the path is absolute. @perms is the access mask of
248 * permissions to request on the handle. SYNCHRONIZE permision is always added.
251 winnt_openat(HANDLE cur_dir, const wchar_t *path, size_t path_nchars,
252 ACCESS_MASK perms, HANDLE *h_ret)
254 UNICODE_STRING name = {
255 .Length = path_nchars * sizeof(wchar_t),
256 .MaximumLength = path_nchars * sizeof(wchar_t),
257 .Buffer = (wchar_t *)path,
259 OBJECT_ATTRIBUTES attr = {
260 .Length = sizeof(attr),
261 .RootDirectory = cur_dir,
264 IO_STATUS_BLOCK iosb;
266 ULONG options = FILE_OPEN_REPARSE_POINT | FILE_OPEN_FOR_BACKUP_INTENT;
268 perms |= SYNCHRONIZE;
269 if (perms & (FILE_READ_DATA | FILE_LIST_DIRECTORY)) {
270 options |= FILE_SYNCHRONOUS_IO_NONALERT;
271 options |= FILE_SEQUENTIAL_ONLY;
274 status = NtOpenFile(h_ret, perms, &attr, &iosb,
275 FILE_SHARE_VALID_FLAGS, options);
276 if (!NT_SUCCESS(status)) {
277 /* Try requesting fewer permissions */
278 if (status == STATUS_ACCESS_DENIED ||
279 status == STATUS_PRIVILEGE_NOT_HELD) {
280 if (perms & ACCESS_SYSTEM_SECURITY) {
281 perms &= ~ACCESS_SYSTEM_SECURITY;
284 if (perms & READ_CONTROL) {
285 perms &= ~READ_CONTROL;
294 winnt_open(const wchar_t *path, size_t path_nchars, ACCESS_MASK perms,
297 return winnt_openat(NULL, path, path_nchars, perms, h_ret);
300 static const wchar_t *
301 windows_file_to_string(const struct windows_file *file, u8 *buf, size_t bufsize)
303 if (file->is_file_id) {
306 (u8 *)file->path + file->path_nbytes - sizeof(file_id),
308 swprintf((wchar_t *)buf, L"NTFS inode 0x%016"PRIx64, file_id);
309 } else if (file->path_nbytes + 3 * sizeof(wchar_t) <= bufsize) {
310 swprintf((wchar_t *)buf, L"\"%ls\"", file->path);
312 return L"(name too long)";
314 return (wchar_t *)buf;
318 read_winnt_stream_prefix(const struct windows_file *file,
319 u64 size, const struct consume_chunk_callback *cb)
321 IO_STATUS_BLOCK iosb;
322 UNICODE_STRING name = {
323 .Buffer = (wchar_t *)file->path,
324 .Length = file->path_nbytes,
325 .MaximumLength = file->path_nbytes,
327 OBJECT_ATTRIBUTES attr = {
328 .Length = sizeof(attr),
333 u8 buf[BUFFER_SIZE] _aligned_attribute(8);
337 status = NtOpenFile(&h, FILE_READ_DATA | SYNCHRONIZE,
339 FILE_SHARE_VALID_FLAGS,
340 FILE_OPEN_REPARSE_POINT |
341 FILE_OPEN_FOR_BACKUP_INTENT |
342 FILE_SYNCHRONOUS_IO_NONALERT |
343 FILE_SEQUENTIAL_ONLY |
344 (file->is_file_id ? FILE_OPEN_BY_FILE_ID : 0));
345 if (unlikely(!NT_SUCCESS(status))) {
346 if (status == STATUS_SHARING_VIOLATION) {
347 ERROR("Can't open %ls for reading:\n"
348 " File is in use by another process! "
349 "Consider using snapshot (VSS) mode.",
350 windows_file_to_string(file, buf, sizeof(buf)));
352 winnt_error(status, L"Can't open %ls for reading",
353 windows_file_to_string(file, buf, sizeof(buf)));
355 return WIMLIB_ERR_OPEN;
359 bytes_remaining = size;
360 while (bytes_remaining) {
361 IO_STATUS_BLOCK iosb;
364 const unsigned max_tries = 5;
365 unsigned tries_remaining = max_tries;
367 count = min(sizeof(buf), bytes_remaining);
370 status = NtReadFile(h, NULL, NULL, NULL,
371 &iosb, buf, count, NULL, NULL);
372 if (unlikely(!NT_SUCCESS(status))) {
373 if (status == STATUS_END_OF_FILE) {
374 ERROR("%ls: File was concurrently truncated",
375 windows_file_to_string(file, buf, sizeof(buf)));
376 ret = WIMLIB_ERR_CONCURRENT_MODIFICATION_DETECTED;
378 winnt_warning(status, L"Error reading data from %ls",
379 windows_file_to_string(file, buf, sizeof(buf)));
381 /* Currently these retries are purely a guess;
382 * there is no reproducible problem that they solve. */
383 if (--tries_remaining) {
385 if (status == STATUS_INSUFFICIENT_RESOURCES ||
386 status == STATUS_NO_MEMORY) {
389 WARNING("Retrying after %dms...", delay);
393 ERROR("Too many retries; returning failure");
394 ret = WIMLIB_ERR_READ;
397 } else if (unlikely(tries_remaining != max_tries)) {
398 WARNING("A read request had to be retried multiple times "
399 "before it succeeded!");
402 bytes_read = iosb.Information;
404 bytes_remaining -= bytes_read;
405 ret = consume_chunk(cb, buf, bytes_read);
413 struct win32_encrypted_read_ctx {
414 const struct consume_chunk_callback *cb;
420 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
422 struct win32_encrypted_read_ctx *ctx = _ctx;
424 size_t bytes_to_consume = min(len, ctx->bytes_remaining);
426 if (bytes_to_consume == 0)
427 return ERROR_SUCCESS;
429 ret = consume_chunk(ctx->cb, data, bytes_to_consume);
431 ctx->wimlib_err_code = ret;
432 /* It doesn't matter what error code is returned here, as long
433 * as it isn't ERROR_SUCCESS. */
434 return ERROR_READ_FAULT;
436 ctx->bytes_remaining -= bytes_to_consume;
437 return ERROR_SUCCESS;
441 read_win32_encrypted_file_prefix(const wchar_t *path, bool is_dir, u64 size,
442 const struct consume_chunk_callback *cb)
444 struct win32_encrypted_read_ctx export_ctx;
451 flags |= CREATE_FOR_DIR;
454 export_ctx.wimlib_err_code = 0;
455 export_ctx.bytes_remaining = size;
457 err = OpenEncryptedFileRaw(path, flags, &file_ctx);
458 if (err != ERROR_SUCCESS) {
460 L"Failed to open encrypted file \"%ls\" for raw read",
462 return WIMLIB_ERR_OPEN;
464 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
465 &export_ctx, file_ctx);
466 if (err != ERROR_SUCCESS) {
467 ret = export_ctx.wimlib_err_code;
470 L"Failed to read encrypted file \"%ls\"",
472 ret = WIMLIB_ERR_READ;
474 } else if (export_ctx.bytes_remaining != 0) {
475 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
476 "encrypted file \"%ls\"",
477 size - export_ctx.bytes_remaining, size,
479 ret = WIMLIB_ERR_READ;
483 CloseEncryptedFileRaw(file_ctx);
487 /* Read the first @size bytes from the file, or named data stream of a file,
488 * described by @blob. */
490 read_windows_file_prefix(const struct blob_descriptor *blob, u64 size,
491 const struct consume_chunk_callback *cb)
493 const struct windows_file *file = blob->windows_file;
495 if (unlikely(file->is_encrypted)) {
496 bool is_dir = (blob->file_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY);
497 return read_win32_encrypted_file_prefix(file->path, is_dir, size, cb);
500 return read_winnt_stream_prefix(file, size, cb);
504 * Load the short name of a file into a WIM dentry.
506 static noinline_for_stack NTSTATUS
507 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
509 /* It's not any harder to just make the NtQueryInformationFile() system
510 * call ourselves, and it saves a dumb call to FindFirstFile() which of
511 * course has to create its own handle. */
513 IO_STATUS_BLOCK iosb;
514 u8 buf[128] _aligned_attribute(8);
515 const FILE_NAME_INFORMATION *info;
517 status = NtQueryInformationFile(h, &iosb, buf, sizeof(buf),
518 FileAlternateNameInformation);
519 info = (const FILE_NAME_INFORMATION *)buf;
520 if (NT_SUCCESS(status) && info->FileNameLength != 0) {
521 dentry->d_short_name = utf16le_dupz(info->FileName,
522 info->FileNameLength);
523 if (!dentry->d_short_name)
524 return STATUS_NO_MEMORY;
525 dentry->d_short_name_nbytes = info->FileNameLength;
531 * Load the security descriptor of a file into the corresponding inode and the
532 * WIM image's security descriptor set.
534 static noinline_for_stack int
535 winnt_load_security_descriptor(HANDLE h, struct wim_inode *inode,
536 struct winnt_scan_ctx *ctx)
538 SECURITY_INFORMATION requestedInformation;
539 u8 _buf[4096] _aligned_attribute(8);
546 * LABEL_SECURITY_INFORMATION is needed on Windows Vista and 7 because
547 * Microsoft decided to add mandatory integrity labels to the SACL but
548 * not have them returned by SACL_SECURITY_INFORMATION.
550 * BACKUP_SECURITY_INFORMATION is needed on Windows 8 because Microsoft
551 * decided to add even more stuff to the SACL and still not have it
552 * returned by SACL_SECURITY_INFORMATION; but they did remember that
553 * backup applications exist and simply want to read the stupid thing
554 * once and for all, so they added a flag to read the entire security
557 * Older versions of Windows tolerate these new flags being passed in.
559 requestedInformation = OWNER_SECURITY_INFORMATION |
560 GROUP_SECURITY_INFORMATION |
561 DACL_SECURITY_INFORMATION |
562 SACL_SECURITY_INFORMATION |
563 LABEL_SECURITY_INFORMATION |
564 BACKUP_SECURITY_INFORMATION;
567 bufsize = sizeof(_buf);
570 * We need the file's security descriptor in
571 * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
572 * opened with as many relevant permissions as possible. At this point,
573 * on Windows there are a number of options for reading a file's
574 * security descriptor:
576 * GetFileSecurity(): This takes in a path and returns the
577 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle,
578 * not ours, and the handle created internally doesn't specify
579 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied
580 * errors on some files and directories, even when running as the
583 * GetSecurityInfo(): This takes in a handle and returns the security
584 * descriptor split into a bunch of different parts. This should work,
585 * but it's dumb because we have to put the security descriptor back
588 * BackupRead(): This can read the security descriptor, but this is a
589 * difficult-to-use API, probably only works as the Administrator, and
590 * the format of the returned data is not well documented.
592 * NtQuerySecurityObject(): This is exactly what we need, as it takes
593 * in a handle and returns the security descriptor in
594 * SECURITY_DESCRIPTOR_RELATIVE format. Only problem is that it's a
595 * ntdll function and therefore not officially part of the Win32 API.
598 while (!NT_SUCCESS(status = NtQuerySecurityObject(h,
599 requestedInformation,
600 (PSECURITY_DESCRIPTOR)buf,
605 case STATUS_BUFFER_TOO_SMALL:
606 wimlib_assert(buf == _buf);
607 buf = MALLOC(len_needed);
609 status = STATUS_NO_MEMORY;
612 bufsize = len_needed;
614 case STATUS_PRIVILEGE_NOT_HELD:
615 case STATUS_ACCESS_DENIED:
616 if (ctx->params->add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
618 /* Permission denied in STRICT_ACLS mode, or
622 if (requestedInformation & SACL_SECURITY_INFORMATION) {
623 /* Try again without the SACL. */
624 ctx->num_get_sacl_priv_notheld++;
625 requestedInformation &= ~(SACL_SECURITY_INFORMATION |
626 LABEL_SECURITY_INFORMATION |
627 BACKUP_SECURITY_INFORMATION);
630 /* Fake success (useful when capturing as
631 * non-Administrator). */
632 ctx->num_get_sd_access_denied++;
633 status = STATUS_SUCCESS;
638 /* We can get a length of 0 with Samba. Assume that means "no security
643 /* Add the security descriptor to the WIM image, and save its ID in
644 * the file's inode. */
645 inode->i_security_id = sd_set_add_sd(ctx->params->sd_set, buf, len_needed);
646 if (unlikely(inode->i_security_id < 0))
647 status = STATUS_NO_MEMORY;
649 if (unlikely(buf != _buf))
651 if (!NT_SUCCESS(status)) {
652 winnt_error(status, L"\"%ls\": Can't read security descriptor",
653 printable_path(ctx));
654 return WIMLIB_ERR_STAT;
659 /* Load a file's object ID into the corresponding WIM inode. */
660 static noinline_for_stack int
661 winnt_load_object_id(HANDLE h, struct wim_inode *inode,
662 struct winnt_scan_ctx *ctx)
664 FILE_OBJECTID_BUFFER buffer;
668 if (!(ctx->vol_flags & FILE_SUPPORTS_OBJECT_IDS))
671 status = winnt_fsctl(h, FSCTL_GET_OBJECT_ID, NULL, 0,
672 &buffer, sizeof(buffer), &len);
674 if (status == STATUS_OBJECTID_NOT_FOUND) /* No object ID */
677 if (status == STATUS_INVALID_DEVICE_REQUEST ||
678 status == STATUS_NOT_SUPPORTED /* Samba volume, WinXP */) {
679 /* The filesystem claimed to support object IDs, but we can't
680 * actually read them. This happens with Samba. */
681 ctx->vol_flags &= ~FILE_SUPPORTS_OBJECT_IDS;
685 if (!NT_SUCCESS(status)) {
686 winnt_error(status, L"\"%ls\": Can't read object ID",
687 printable_path(ctx));
688 return WIMLIB_ERR_STAT;
691 if (len == 0) /* No object ID (for directories) */
694 if (!inode_set_object_id(inode, &buffer, len))
695 return WIMLIB_ERR_NOMEM;
700 /* Load a file's extended attributes into the corresponding WIM inode. */
701 static noinline_for_stack int
702 winnt_load_xattrs(HANDLE h, struct wim_inode *inode,
703 struct winnt_scan_ctx *ctx, u32 ea_size)
705 IO_STATUS_BLOCK iosb;
707 u8 _buf[1024] _aligned_attribute(4);
709 const FILE_FULL_EA_INFORMATION *ea;
710 struct wim_xattr_entry *entry;
715 * EaSize from FILE_EA_INFORMATION is apparently supposed to give the
716 * size of the buffer required for NtQueryEaFile(), but it doesn't
717 * actually work correctly; it can be off by about 4 bytes per xattr.
719 * So just start out by doubling the advertised size, and also handle
720 * STATUS_BUFFER_OVERFLOW just in case.
723 if (unlikely(ea_size * 2 < ea_size))
724 ea_size = UINT32_MAX;
727 if (unlikely(ea_size > sizeof(_buf))) {
728 buf = MALLOC(ea_size);
730 if (ea_size >= (1 << 20)) {
731 WARNING("\"%ls\": EaSize was extremely large (%u)",
732 printable_path(ctx), ea_size);
734 return WIMLIB_ERR_NOMEM;
738 status = NtQueryEaFile(h, &iosb, buf, ea_size,
739 FALSE, NULL, 0, NULL, TRUE);
741 if (unlikely(!NT_SUCCESS(status))) {
742 if (status == STATUS_BUFFER_OVERFLOW) {
749 if (status == STATUS_NO_EAS_ON_FILE) {
751 * FILE_EA_INFORMATION.EaSize was nonzero so this
752 * shouldn't happen, but just in case...
757 winnt_error(status, L"\"%ls\": Can't read extended attributes",
758 printable_path(ctx));
759 ret = WIMLIB_ERR_STAT;
763 ea = (const FILE_FULL_EA_INFORMATION *)buf;
764 entry = (struct wim_xattr_entry *)buf;
767 * wim_xattr_entry is not larger than FILE_FULL_EA_INFORMATION,
768 * so we can reuse the same buffer by overwriting the
769 * FILE_FULL_EA_INFORMATION with the wim_xattr_entry in-place.
771 FILE_FULL_EA_INFORMATION _ea;
773 STATIC_ASSERT(offsetof(struct wim_xattr_entry, name) <=
774 offsetof(FILE_FULL_EA_INFORMATION, EaName));
775 wimlib_assert((u8 *)entry <= (const u8 *)ea);
777 memcpy(&_ea, ea, sizeof(_ea));
779 entry->value_len = cpu_to_le16(_ea.EaValueLength);
780 entry->name_len = _ea.EaNameLength;
781 entry->flags = _ea.Flags;
782 memmove(entry->name, ea->EaName, _ea.EaNameLength);
783 entry->name[_ea.EaNameLength] = '\0';
784 memmove(&entry->name[_ea.EaNameLength + 1],
785 &ea->EaName[_ea.EaNameLength + 1], _ea.EaValueLength);
786 entry = (struct wim_xattr_entry *)
787 &entry->name[_ea.EaNameLength + 1 + _ea.EaValueLength];
788 if (_ea.NextEntryOffset == 0)
790 ea = (const FILE_FULL_EA_INFORMATION *)
791 ((const u8 *)ea + _ea.NextEntryOffset);
793 wimlib_assert((u8 *)entry - buf <= ea_size);
795 ret = WIMLIB_ERR_NOMEM;
796 if (!inode_set_xattrs(inode, buf, (u8 *)entry - buf))
800 if (unlikely(buf != _buf))
806 winnt_build_dentry_tree(struct wim_dentry **root_ret,
808 const wchar_t *relative_path,
809 size_t relative_path_nchars,
810 const wchar_t *filename,
811 struct winnt_scan_ctx *ctx,
815 winnt_recurse_directory(HANDLE h,
816 struct wim_dentry *parent,
817 struct winnt_scan_ctx *ctx)
820 const size_t bufsize = 8192;
821 IO_STATUS_BLOCK iosb;
825 buf = MALLOC(bufsize);
827 return WIMLIB_ERR_NOMEM;
829 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
830 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
832 while (NT_SUCCESS(status = NtQueryDirectoryFile(h, NULL, NULL, NULL,
834 FileNamesInformation,
835 FALSE, NULL, FALSE)))
837 const FILE_NAMES_INFORMATION *info = buf;
839 if (!should_ignore_filename(info->FileName,
840 info->FileNameLength / 2))
842 struct wim_dentry *child;
843 size_t orig_path_nchars;
844 const wchar_t *filename;
846 ret = WIMLIB_ERR_NOMEM;
847 filename = pathbuf_append_name(ctx->params,
849 info->FileNameLength / 2,
854 ret = winnt_build_dentry_tree(
858 info->FileNameLength / 2,
863 pathbuf_truncate(ctx->params, orig_path_nchars);
867 attach_scanned_tree(parent, child,
868 ctx->params->blob_table);
870 if (info->NextEntryOffset == 0)
872 info = (const FILE_NAMES_INFORMATION *)
873 ((const u8 *)info + info->NextEntryOffset);
877 if (unlikely(status != STATUS_NO_MORE_FILES)) {
878 winnt_error(status, L"\"%ls\": Can't read directory",
879 printable_path(ctx));
880 ret = WIMLIB_ERR_READ;
887 /* Reparse point fixup status code */
888 #define RP_FIXED (-1)
891 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
894 IO_STATUS_BLOCK iosb;
895 FILE_INTERNAL_INFORMATION int_info;
896 FILE_FS_VOLUME_INFORMATION vol_info;
898 status = NtQueryInformationFile(h, &iosb, &int_info, sizeof(int_info),
899 FileInternalInformation);
900 if (!NT_SUCCESS(status))
903 if (int_info.IndexNumber.QuadPart != ino)
906 status = NtQueryVolumeInformationFile(h, &iosb,
907 &vol_info, sizeof(vol_info),
908 FileFsVolumeInformation);
909 if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
912 if (iosb.Information <
913 offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
914 sizeof(vol_info.VolumeSerialNumber))
917 return (vol_info.VolumeSerialNumber == dev);
921 * This is the Windows equivalent of unix_relativize_link_target(); see there
922 * for general details. This version works with an "absolute" Windows link
923 * target, specified from the root of the Windows kernel object namespace. Note
924 * that we have to open directories with a trailing slash when present because
925 * \??\E: opens the E: device itself and not the filesystem root directory.
927 static const wchar_t *
928 winnt_relativize_link_target(const wchar_t *target, size_t target_nbytes,
932 OBJECT_ATTRIBUTES attr;
933 IO_STATUS_BLOCK iosb;
935 const wchar_t *target_end;
938 target_end = target + (target_nbytes / sizeof(wchar_t));
941 if (target_end == target)
944 /* No leading slash??? */
945 if (target[0] != L'\\')
949 if ((target_end - target) >= 2 &&
950 target[0] == L'\\' && target[1] == L'\\')
953 attr.Length = sizeof(attr);
954 attr.RootDirectory = NULL;
955 attr.ObjectName = &name;
957 attr.SecurityDescriptor = NULL;
958 attr.SecurityQualityOfService = NULL;
960 name.Buffer = (wchar_t *)target;
965 const wchar_t *orig_p = p;
967 /* Skip non-backslashes */
968 while (p != target_end && *p != L'\\')
971 /* Skip backslashes */
972 while (p != target_end && *p == L'\\')
975 /* Append path component */
976 name.Length += (p - orig_p) * sizeof(wchar_t);
977 name.MaximumLength = name.Length;
979 /* Try opening the file */
980 status = NtOpenFile(&h,
981 FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
984 FILE_SHARE_VALID_FLAGS,
985 FILE_OPEN_FOR_BACKUP_INTENT);
987 if (NT_SUCCESS(status)) {
988 /* Reset root directory */
989 if (attr.RootDirectory)
990 NtClose(attr.RootDirectory);
991 attr.RootDirectory = h;
992 name.Buffer = (wchar_t *)p;
995 if (file_has_ino_and_dev(h, ino, dev))
996 goto out_close_root_dir;
998 } while (p != target_end);
1003 if (attr.RootDirectory)
1004 NtClose(attr.RootDirectory);
1005 while (p > target && *(p - 1) == L'\\')
1011 winnt_rpfix_progress(struct scan_params *params,
1012 const struct link_reparse_point *link, int scan_status)
1014 size_t print_name_nchars = link->print_name_nbytes / sizeof(wchar_t);
1015 wchar_t print_name0[print_name_nchars + 1];
1017 wmemcpy(print_name0, link->print_name, print_name_nchars);
1018 print_name0[print_name_nchars] = L'\0';
1020 params->progress.scan.symlink_target = print_name0;
1021 return do_scan_progress(params, scan_status, NULL);
1025 winnt_try_rpfix(struct reparse_buffer_disk *rpbuf, u16 *rpbuflen_p,
1026 struct scan_params *params)
1028 struct link_reparse_point link;
1029 const wchar_t *rel_target;
1032 if (parse_link_reparse_point(rpbuf, *rpbuflen_p, &link)) {
1033 /* Couldn't understand the reparse data; don't do the fixup. */
1038 * Don't do reparse point fixups on relative symbolic links.
1040 * On Windows, a relative symbolic link is supposed to be identifiable
1041 * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
1042 * SYMBOLIC_LINK_RELATIVE. We will use this information, although this
1043 * may not always do what the user expects, since drive-relative
1044 * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
1045 * set, in addition to truly relative symbolic links such as "Users" or
1046 * "Users\Public". However, WIMGAPI (as of Windows 8.1) has this same
1049 * Otherwise, as far as I can tell, the targets of symbolic links that
1050 * are NOT relative, as well as junctions (note: a mountpoint is the
1051 * sames thing as a junction), must be NT namespace paths, for example:
1053 * - \??\e:\Users\Public
1054 * - \DosDevices\e:\Users\Public
1055 * - \Device\HardDiskVolume4\Users\Public
1056 * - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
1057 * - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
1059 if (link_is_relative_symlink(&link))
1062 rel_target = winnt_relativize_link_target(link.substitute_name,
1063 link.substitute_name_nbytes,
1064 params->capture_root_ino,
1065 params->capture_root_dev);
1067 if (rel_target == link.substitute_name) {
1068 /* Target points outside of the tree being captured or had an
1069 * unrecognized path format. Don't adjust it. */
1070 return winnt_rpfix_progress(params, &link,
1071 WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK);
1074 /* We have an absolute target pointing within the directory being
1075 * captured. @rel_target is the suffix of the link target that is the
1076 * part relative to the directory being captured.
1078 * We will cut off the prefix before this part (which is the path to the
1079 * directory being captured) and add a dummy prefix. Since the process
1080 * will need to be reversed when applying the image, it doesn't matter
1081 * what exactly the prefix is, as long as it looks like an absolute
1084 static const wchar_t prefix[6] = L"\\??\\X:";
1085 static const size_t num_unprintable_chars = 4;
1087 size_t rel_target_nbytes =
1088 link.substitute_name_nbytes - ((const u8 *)rel_target -
1089 (const u8 *)link.substitute_name);
1091 wchar_t tmp[(sizeof(prefix) + rel_target_nbytes) / sizeof(wchar_t)];
1093 memcpy(tmp, prefix, sizeof(prefix));
1094 memcpy(tmp + ARRAY_LEN(prefix), rel_target, rel_target_nbytes);
1096 link.substitute_name = tmp;
1097 link.substitute_name_nbytes = sizeof(tmp);
1099 link.print_name = link.substitute_name + num_unprintable_chars;
1100 link.print_name_nbytes = link.substitute_name_nbytes -
1101 (num_unprintable_chars * sizeof(wchar_t));
1103 if (make_link_reparse_point(&link, rpbuf, rpbuflen_p))
1106 ret = winnt_rpfix_progress(params, &link,
1107 WIMLIB_SCAN_DENTRY_FIXED_SYMLINK);
1113 /* Load the reparse data of a file into the corresponding WIM inode. If the
1114 * reparse point is a symbolic link or junction with an absolute target and
1115 * RPFIX mode is enabled, then also rewrite its target to be relative to the
1117 static noinline_for_stack int
1118 winnt_load_reparse_data(HANDLE h, struct wim_inode *inode,
1119 struct winnt_scan_ctx *ctx)
1121 struct reparse_buffer_disk rpbuf;
1127 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1128 /* See comment above assign_stream_types_encrypted() */
1129 WARNING("Ignoring reparse data of encrypted file \"%ls\"",
1130 printable_path(ctx));
1134 status = winnt_fsctl(h, FSCTL_GET_REPARSE_POINT,
1135 NULL, 0, &rpbuf, sizeof(rpbuf), &len);
1136 if (!NT_SUCCESS(status)) {
1137 winnt_error(status, L"\"%ls\": Can't get reparse point",
1138 printable_path(ctx));
1139 return WIMLIB_ERR_READLINK;
1144 if (unlikely(rpbuflen < REPARSE_DATA_OFFSET)) {
1145 ERROR("\"%ls\": reparse point buffer is too short",
1146 printable_path(ctx));
1147 return WIMLIB_ERR_INVALID_REPARSE_DATA;
1150 if (le32_to_cpu(rpbuf.rptag) == WIM_IO_REPARSE_TAG_DEDUP) {
1152 * Windows treats Data Deduplication reparse points specially.
1153 * Reads from the unnamed data stream actually return the
1154 * redirected file contents, even with FILE_OPEN_REPARSE_POINT.
1155 * Deduplicated files also cannot be properly restored without
1156 * also restoring the "System Volume Information" directory,
1157 * which wimlib excludes by default. Therefore, the logical
1158 * behavior for us seems to be to ignore the reparse point and
1159 * treat the file as a normal file.
1161 inode->i_attributes &= ~FILE_ATTRIBUTE_REPARSE_POINT;
1165 if (ctx->params->add_flags & WIMLIB_ADD_FLAG_RPFIX) {
1166 ret = winnt_try_rpfix(&rpbuf, &rpbuflen, ctx->params);
1167 if (ret == RP_FIXED)
1168 inode->i_rp_flags &= ~WIM_RP_FLAG_NOT_FIXED;
1173 inode->i_reparse_tag = le32_to_cpu(rpbuf.rptag);
1174 inode->i_rp_reserved = le16_to_cpu(rpbuf.rpreserved);
1176 if (!inode_add_stream_with_data(inode,
1177 STREAM_TYPE_REPARSE_POINT,
1180 rpbuflen - REPARSE_DATA_OFFSET,
1181 ctx->params->blob_table))
1182 return WIMLIB_ERR_NOMEM;
1188 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
1191 *(u64*)_size_ret += len;
1192 return ERROR_SUCCESS;
1196 win32_get_encrypted_file_size(const wchar_t *path, bool is_dir, u64 *size_ret)
1204 flags |= CREATE_FOR_DIR;
1206 err = OpenEncryptedFileRaw(path, flags, &file_ctx);
1207 if (err != ERROR_SUCCESS) {
1209 L"Failed to open encrypted file \"%ls\" for raw read",
1211 return WIMLIB_ERR_OPEN;
1214 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
1215 size_ret, file_ctx);
1216 if (err != ERROR_SUCCESS) {
1218 L"Failed to read raw encrypted data from \"%ls\"",
1220 ret = WIMLIB_ERR_READ;
1224 CloseEncryptedFileRaw(file_ctx);
1229 winnt_scan_efsrpc_raw_data(struct wim_inode *inode,
1230 struct winnt_scan_ctx *ctx)
1232 wchar_t *path = ctx->params->cur_path;
1233 size_t path_nchars = ctx->params->cur_path_nchars;
1234 const bool is_dir = (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY);
1235 struct windows_file *windows_file;
1239 /* OpenEncryptedFileRaw() expects a Win32 name. */
1240 wimlib_assert(!wmemcmp(path, L"\\??\\", 4));
1243 ret = win32_get_encrypted_file_size(path, is_dir, &size);
1247 /* Empty EFSRPC data does not make sense */
1248 wimlib_assert(size != 0);
1250 windows_file = alloc_windows_file(path, path_nchars, NULL, 0,
1251 ctx->snapshot, true);
1252 ret = add_stream(inode, windows_file, size, STREAM_TYPE_EFSRPC_RAW_DATA,
1253 NO_STREAM_NAME, ctx->params->unhashed_blobs);
1260 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1261 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
1263 const wchar_t *sep, *type, *end;
1265 /* The stream name should be returned as :NAME:TYPE */
1266 if (raw_stream_name_nchars < 1)
1268 if (raw_stream_name[0] != L':')
1272 raw_stream_name_nchars--;
1274 end = raw_stream_name + raw_stream_name_nchars;
1276 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
1281 if (end - type != 5)
1284 if (wmemcmp(type, L"$DATA", 5))
1287 *stream_name_ret = raw_stream_name;
1288 *stream_name_nchars_ret = sep - raw_stream_name;
1293 winnt_scan_data_stream(wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1294 u64 stream_size, struct wim_inode *inode,
1295 struct winnt_scan_ctx *ctx)
1297 wchar_t *stream_name;
1298 size_t stream_name_nchars;
1299 struct windows_file *windows_file;
1301 /* Given the raw stream name (which is something like
1302 * :streamname:$DATA), extract just the stream name part (streamname).
1303 * Ignore any non-$DATA streams. */
1304 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
1305 (const wchar_t **)&stream_name,
1306 &stream_name_nchars))
1309 stream_name[stream_name_nchars] = L'\0';
1311 windows_file = alloc_windows_file(ctx->params->cur_path,
1312 ctx->params->cur_path_nchars,
1313 stream_name, stream_name_nchars,
1314 ctx->snapshot, false);
1315 return add_stream(inode, windows_file, stream_size, STREAM_TYPE_DATA,
1316 stream_name, ctx->params->unhashed_blobs);
1320 * Load information about the data streams of an open file into a WIM inode.
1322 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
1323 * and FindNextStream(). This is done for two reasons:
1325 * - FindFirstStream() opens its own handle to the file or directory and
1326 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
1327 * causing access denied errors on certain files (even when running as the
1329 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
1330 * and later, whereas the stream support in NtQueryInformationFile() was
1331 * already present in Windows XP.
1333 static noinline_for_stack int
1334 winnt_scan_data_streams(HANDLE h, struct wim_inode *inode, u64 file_size,
1335 struct winnt_scan_ctx *ctx)
1338 u8 _buf[4096] _aligned_attribute(8);
1341 IO_STATUS_BLOCK iosb;
1343 FILE_STREAM_INFORMATION *info;
1346 bufsize = sizeof(_buf);
1348 if (!(ctx->vol_flags & FILE_NAMED_STREAMS))
1351 /* Get a buffer containing the stream information. */
1352 while (!NT_SUCCESS(status = NtQueryInformationFile(h,
1356 FileStreamInformation)))
1360 case STATUS_BUFFER_OVERFLOW:
1366 newbuf = MALLOC(bufsize);
1368 newbuf = REALLOC(buf, bufsize);
1370 ret = WIMLIB_ERR_NOMEM;
1376 case STATUS_NOT_IMPLEMENTED:
1377 case STATUS_NOT_SUPPORTED:
1378 case STATUS_INVALID_INFO_CLASS:
1382 L"\"%ls\": Failed to query stream information",
1383 printable_path(ctx));
1384 ret = WIMLIB_ERR_READ;
1389 if (iosb.Information == 0) {
1390 /* No stream information. */
1395 /* Parse one or more stream information structures. */
1396 info = (FILE_STREAM_INFORMATION *)buf;
1398 /* Load the stream information. */
1399 ret = winnt_scan_data_stream(info->StreamName,
1400 info->StreamNameLength / 2,
1401 info->StreamSize.QuadPart,
1406 if (info->NextEntryOffset == 0) {
1407 /* No more stream information. */
1410 /* Advance to next stream information. */
1411 info = (FILE_STREAM_INFORMATION *)
1412 ((u8 *)info + info->NextEntryOffset);
1418 /* The volume does not support named streams. Only capture the unnamed
1420 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1421 FILE_ATTRIBUTE_REPARSE_POINT))
1428 wchar_t stream_name[] = L"::$DATA";
1429 ret = winnt_scan_data_stream(stream_name, 7, file_size,
1433 /* Free buffer if allocated on heap. */
1434 if (unlikely(buf != _buf))
1440 extract_starting_lcn(const RETRIEVAL_POINTERS_BUFFER *extents)
1442 if (extents->ExtentCount < 1)
1445 return extents->Extents[0].Lcn.QuadPart;
1448 static noinline_for_stack u64
1449 get_sort_key(HANDLE h)
1451 STARTING_VCN_INPUT_BUFFER in = { .StartingVcn.QuadPart = 0 };
1452 RETRIEVAL_POINTERS_BUFFER out;
1454 if (!NT_SUCCESS(winnt_fsctl(h, FSCTL_GET_RETRIEVAL_POINTERS,
1455 &in, sizeof(in), &out, sizeof(out), NULL)))
1458 return extract_starting_lcn(&out);
1462 set_sort_key(struct wim_inode *inode, u64 sort_key)
1464 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1465 struct wim_inode_stream *strm = &inode->i_streams[i];
1466 struct blob_descriptor *blob = stream_blob_resolved(strm);
1467 if (blob && blob->blob_location == BLOB_IN_WINDOWS_FILE)
1468 blob->windows_file->sort_key = sort_key;
1473 should_try_to_use_wimboot_hash(const struct wim_inode *inode,
1474 const struct winnt_scan_ctx *ctx)
1476 /* Directories and encrypted files aren't valid for external backing. */
1477 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1478 FILE_ATTRIBUTE_ENCRYPTED))
1481 /* If the file is a reparse point, then try the hash fixup if it's a WOF
1482 * reparse point and we're in WIMBOOT mode. Otherwise, try the hash
1483 * fixup if WOF may be attached. */
1484 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1485 return (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_WOF) &&
1486 (ctx->params->add_flags & WIMLIB_ADD_FLAG_WIMBOOT);
1487 return !ctx->wof_not_attached;
1491 * This function implements an optimization for capturing files from a
1492 * filesystem with a backing WIM(s). If a file is WIM-backed, then we can
1493 * retrieve the SHA-1 message digest of its original contents from its reparse
1494 * point. This may eliminate the need to read the file's data and/or allow the
1495 * file's data to be immediately deduplicated with existing data in the WIM.
1497 * If WOF is attached, then this function is merely an optimization, but
1498 * potentially a very effective one. If WOF is detached, then this function
1499 * really causes WIM-backed files to be, effectively, automatically
1500 * "dereferenced" when possible; the unnamed data stream is updated to reference
1501 * the original contents and the reparse point is removed.
1503 * This function returns 0 if the fixup succeeded or was intentionally not
1504 * executed. Otherwise it returns an error code.
1506 static noinline_for_stack int
1507 try_to_use_wimboot_hash(HANDLE h, struct wim_inode *inode,
1508 struct winnt_scan_ctx *ctx)
1510 struct blob_table *blob_table = ctx->params->blob_table;
1511 struct wim_inode_stream *reparse_strm = NULL;
1512 struct wim_inode_stream *strm;
1513 struct blob_descriptor *blob;
1514 u8 hash[SHA1_HASH_SIZE];
1517 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1518 struct reparse_buffer_disk rpbuf;
1520 struct wof_external_info wof_info;
1521 struct wim_provider_rpdata wim_info;
1522 } *rpdata = (void *)rpbuf.rpdata;
1523 struct blob_descriptor *reparse_blob;
1525 /* The file has a WOF reparse point, so WOF must be detached.
1526 * We can read the reparse point directly. */
1527 ctx->wof_not_attached = true;
1528 reparse_strm = inode_get_unnamed_stream(inode, STREAM_TYPE_REPARSE_POINT);
1529 reparse_blob = stream_blob_resolved(reparse_strm);
1531 if (!reparse_blob || reparse_blob->size < sizeof(*rpdata))
1532 return 0; /* Not a WIM-backed file */
1534 ret = read_blob_into_buf(reparse_blob, rpdata);
1538 if (rpdata->wof_info.version != WOF_CURRENT_VERSION ||
1539 rpdata->wof_info.provider != WOF_PROVIDER_WIM ||
1540 rpdata->wim_info.version != 2)
1541 return 0; /* Not a WIM-backed file */
1543 /* Okay, this is a WIM backed file. Get its SHA-1 hash. */
1544 copy_hash(hash, rpdata->wim_info.unnamed_data_stream_hash);
1547 struct wof_external_info wof_info;
1548 struct wim_provider_external_info wim_info;
1552 /* WOF may be attached. Try reading this file's external
1554 status = winnt_fsctl(h, FSCTL_GET_EXTERNAL_BACKING,
1555 NULL, 0, &out, sizeof(out), NULL);
1557 /* Is WOF not attached? */
1558 if (status == STATUS_INVALID_DEVICE_REQUEST ||
1559 status == STATUS_NOT_SUPPORTED) {
1560 ctx->wof_not_attached = true;
1564 /* Is this file not externally backed? */
1565 if (status == STATUS_OBJECT_NOT_EXTERNALLY_BACKED)
1568 /* Does this file have an unknown type of external backing that
1569 * needed a larger information buffer? */
1570 if (status == STATUS_BUFFER_TOO_SMALL)
1573 /* Was there some other failure? */
1574 if (status != STATUS_SUCCESS) {
1576 L"\"%ls\": FSCTL_GET_EXTERNAL_BACKING failed",
1577 printable_path(ctx));
1578 return WIMLIB_ERR_STAT;
1581 /* Is this file backed by a WIM? */
1582 if (out.wof_info.version != WOF_CURRENT_VERSION ||
1583 out.wof_info.provider != WOF_PROVIDER_WIM ||
1584 out.wim_info.version != WIM_PROVIDER_CURRENT_VERSION)
1587 /* Okay, this is a WIM backed file. Get its SHA-1 hash. */
1588 copy_hash(hash, out.wim_info.unnamed_data_stream_hash);
1591 /* If the file's unnamed data stream is nonempty, then fill in its hash
1592 * and deduplicate it if possible.
1594 * With WOF detached, we require that the blob *must* de-duplicable for
1595 * any action can be taken, since without WOF we can't fall back to
1596 * getting the "dereferenced" data by reading the stream (the real
1597 * stream is sparse and contains all zeroes). */
1598 strm = inode_get_unnamed_data_stream(inode);
1599 if (strm && (blob = stream_blob_resolved(strm))) {
1600 struct blob_descriptor **back_ptr;
1602 if (reparse_strm && !lookup_blob(blob_table, hash))
1604 back_ptr = retrieve_pointer_to_unhashed_blob(blob);
1605 copy_hash(blob->hash, hash);
1606 if (after_blob_hashed(blob, back_ptr, blob_table) != blob)
1607 free_blob_descriptor(blob);
1610 /* Remove the reparse point, if present. */
1612 inode_remove_stream(inode, reparse_strm, blob_table);
1613 inode->i_attributes &= ~(FILE_ATTRIBUTE_REPARSE_POINT |
1614 FILE_ATTRIBUTE_SPARSE_FILE);
1615 if (inode->i_attributes == 0)
1616 inode->i_attributes = FILE_ATTRIBUTE_NORMAL;
1626 u64 last_write_time;
1627 u64 last_access_time;
1633 static noinline_for_stack NTSTATUS
1634 get_file_info(HANDLE h, struct file_info *info)
1636 IO_STATUS_BLOCK iosb;
1638 FILE_ALL_INFORMATION all_info;
1640 status = NtQueryInformationFile(h, &iosb, &all_info, sizeof(all_info),
1641 FileAllInformation);
1643 if (unlikely(!NT_SUCCESS(status) && status != STATUS_BUFFER_OVERFLOW))
1646 info->attributes = all_info.BasicInformation.FileAttributes;
1647 info->num_links = all_info.StandardInformation.NumberOfLinks;
1648 info->creation_time = all_info.BasicInformation.CreationTime.QuadPart;
1649 info->last_write_time = all_info.BasicInformation.LastWriteTime.QuadPart;
1650 info->last_access_time = all_info.BasicInformation.LastAccessTime.QuadPart;
1651 info->ino = all_info.InternalInformation.IndexNumber.QuadPart;
1652 info->end_of_file = all_info.StandardInformation.EndOfFile.QuadPart;
1653 info->ea_size = all_info.EaInformation.EaSize;
1654 return STATUS_SUCCESS;
1658 get_volume_information(HANDLE h, struct winnt_scan_ctx *ctx)
1660 u8 _attr_info[sizeof(FILE_FS_ATTRIBUTE_INFORMATION) + 128] _aligned_attribute(8);
1661 FILE_FS_ATTRIBUTE_INFORMATION *attr_info = (void *)_attr_info;
1662 FILE_FS_VOLUME_INFORMATION vol_info;
1663 struct file_info file_info;
1664 IO_STATUS_BLOCK iosb;
1667 /* Get volume flags */
1668 status = NtQueryVolumeInformationFile(h, &iosb, attr_info,
1670 FileFsAttributeInformation);
1671 if (NT_SUCCESS(status)) {
1672 ctx->vol_flags = attr_info->FileSystemAttributes;
1673 ctx->is_ntfs = (attr_info->FileSystemNameLength == 4 * sizeof(wchar_t)) &&
1674 !wmemcmp(attr_info->FileSystemName, L"NTFS", 4);
1676 winnt_warning(status, L"\"%ls\": Can't get volume attributes",
1677 printable_path(ctx));
1680 /* Get volume ID. */
1681 status = NtQueryVolumeInformationFile(h, &iosb, &vol_info,
1683 FileFsVolumeInformation);
1684 if ((NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW) &&
1685 (iosb.Information >= offsetof(FILE_FS_VOLUME_INFORMATION,
1686 VolumeSerialNumber) +
1687 sizeof(vol_info.VolumeSerialNumber)))
1689 ctx->params->capture_root_dev = vol_info.VolumeSerialNumber;
1691 winnt_warning(status, L"\"%ls\": Can't get volume ID",
1692 printable_path(ctx));
1695 /* Get inode number. */
1696 status = get_file_info(h, &file_info);
1697 if (NT_SUCCESS(status)) {
1698 ctx->params->capture_root_ino = file_info.ino;
1700 winnt_warning(status, L"\"%ls\": Can't get file information",
1701 printable_path(ctx));
1706 winnt_build_dentry_tree(struct wim_dentry **root_ret,
1708 const wchar_t *relative_path,
1709 size_t relative_path_nchars,
1710 const wchar_t *filename,
1711 struct winnt_scan_ctx *ctx,
1714 struct wim_dentry *root = NULL;
1715 struct wim_inode *inode = NULL;
1719 struct file_info file_info;
1722 ret = try_exclude(ctx->params);
1723 if (unlikely(ret < 0)) /* Excluded? */
1725 if (unlikely(ret > 0)) /* Error? */
1728 /* Open the file with permission to read metadata. Although we will
1729 * later need a handle with FILE_LIST_DIRECTORY permission (or,
1730 * equivalently, FILE_READ_DATA; they're the same numeric value) if the
1731 * file is a directory, it can significantly slow things down to request
1732 * this permission on all nondirectories. Perhaps it causes Windows to
1733 * start prefetching the file contents... */
1734 status = winnt_openat(cur_dir, relative_path, relative_path_nchars,
1735 FILE_READ_ATTRIBUTES | FILE_READ_EA |
1736 READ_CONTROL | ACCESS_SYSTEM_SECURITY,
1738 if (unlikely(!NT_SUCCESS(status))) {
1739 if (status == STATUS_DELETE_PENDING) {
1740 WARNING("\"%ls\": Deletion pending; skipping file",
1741 printable_path(ctx));
1745 if (status == STATUS_SHARING_VIOLATION) {
1746 ERROR("Can't open \"%ls\":\n"
1747 " File is in use by another process! "
1748 "Consider using snapshot (VSS) mode.",
1749 printable_path(ctx));
1750 ret = WIMLIB_ERR_OPEN;
1753 winnt_error(status, L"\"%ls\": Can't open file",
1754 printable_path(ctx));
1755 if (status == STATUS_FVE_LOCKED_VOLUME)
1756 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1758 ret = WIMLIB_ERR_OPEN;
1762 /* Get information about the file. */
1763 status = get_file_info(h, &file_info);
1764 if (!NT_SUCCESS(status)) {
1765 winnt_error(status, L"\"%ls\": Can't get file information",
1766 printable_path(ctx));
1767 ret = WIMLIB_ERR_STAT;
1771 /* Create a WIM dentry with an associated inode, which may be shared.
1773 * However, we need to explicitly check for directories and files with
1774 * only 1 link and refuse to hard link them. This is because Windows
1775 * has a bug where it can return duplicate File IDs for files and
1776 * directories on the FAT filesystem.
1778 * Since we don't follow mount points on Windows, we don't need to query
1779 * the volume ID per-file. Just once, for the root, is enough. But we
1780 * can't simply pass 0, because then there could be inode collisions
1781 * among multiple calls to win32_build_dentry_tree() that are scanning
1782 * files on different volumes. */
1783 ret = inode_table_new_dentry(ctx->params->inode_table,
1786 ctx->params->capture_root_dev,
1787 (file_info.num_links <= 1),
1792 /* Get the short (DOS) name of the file. */
1793 status = winnt_get_short_name(h, root);
1795 /* If we can't read the short filename for any reason other than
1796 * out-of-memory, just ignore the error and assume the file has no short
1797 * name. This shouldn't be an issue, since the short names are
1798 * essentially obsolete anyway. */
1799 if (unlikely(status == STATUS_NO_MEMORY)) {
1800 ret = WIMLIB_ERR_NOMEM;
1804 inode = root->d_inode;
1806 if (inode->i_nlink > 1) {
1807 /* Shared inode (hard link); skip reading per-inode information.
1812 inode->i_attributes = file_info.attributes;
1813 inode->i_creation_time = file_info.creation_time;
1814 inode->i_last_write_time = file_info.last_write_time;
1815 inode->i_last_access_time = file_info.last_access_time;
1817 /* Get the file's security descriptor, unless we are capturing in
1818 * NO_ACLS mode or the volume does not support security descriptors. */
1819 if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1820 && (ctx->vol_flags & FILE_PERSISTENT_ACLS))
1822 ret = winnt_load_security_descriptor(h, inode, ctx);
1827 /* Get the file's object ID. */
1828 ret = winnt_load_object_id(h, inode, ctx);
1832 /* Get the file's extended attributes. */
1833 if (unlikely(file_info.ea_size != 0)) {
1834 ret = winnt_load_xattrs(h, inode, ctx, file_info.ea_size);
1839 /* If this is a reparse point, load the reparse data. */
1840 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1841 ret = winnt_load_reparse_data(h, inode, ctx);
1846 sort_key = get_sort_key(h);
1848 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1849 /* Load information about the raw encrypted data. This is
1850 * needed for any directory or non-directory that has
1851 * FILE_ATTRIBUTE_ENCRYPTED set.
1853 * Note: since OpenEncryptedFileRaw() fails with
1854 * ERROR_SHARING_VIOLATION if there are any open handles to the
1855 * file, we have to close the file and re-open it later if
1859 ret = winnt_scan_efsrpc_raw_data(inode, ctx);
1864 * Load information about data streams (unnamed and named).
1866 * Skip this step for encrypted files, since the data from
1867 * ReadEncryptedFileRaw() already contains all data streams (and
1868 * they do in fact all get restored by WriteEncryptedFileRaw().)
1870 * Note: WIMGAPI (as of Windows 8.1) gets wrong and stores both
1871 * the EFSRPC data and the named data stream(s)...!
1873 ret = winnt_scan_data_streams(h,
1875 file_info.end_of_file,
1881 if (unlikely(should_try_to_use_wimboot_hash(inode, ctx))) {
1882 ret = try_to_use_wimboot_hash(h, inode, ctx);
1887 set_sort_key(inode, sort_key);
1889 if (inode_is_directory(inode) && recursive) {
1891 /* Directory: recurse to children. */
1893 /* Re-open the directory with FILE_LIST_DIRECTORY access. */
1898 status = winnt_openat(cur_dir, relative_path,
1899 relative_path_nchars, FILE_LIST_DIRECTORY,
1901 if (!NT_SUCCESS(status)) {
1902 winnt_error(status, L"\"%ls\": Can't open directory",
1903 printable_path(ctx));
1904 ret = WIMLIB_ERR_OPEN;
1907 ret = winnt_recurse_directory(h, root, ctx);
1914 if (recursive) { /* if !recursive, caller handles progress */
1916 ret = do_scan_progress(ctx->params,
1917 WIMLIB_SCAN_DENTRY_OK, inode);
1919 ret = do_scan_progress(ctx->params,
1920 WIMLIB_SCAN_DENTRY_EXCLUDED,
1926 if (unlikely(ret)) {
1927 free_dentry_tree(root, ctx->params->blob_table);
1929 ret = report_scan_error(ctx->params, ret);
1936 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_ctx *ctx)
1938 if (likely(ctx->num_get_sacl_priv_notheld == 0 &&
1939 ctx->num_get_sd_access_denied == 0))
1942 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1943 if (ctx->num_get_sacl_priv_notheld != 0) {
1944 WARNING("- Could not capture SACL (System Access Control List)\n"
1945 " on %lu files or directories.",
1946 ctx->num_get_sacl_priv_notheld);
1948 if (ctx->num_get_sd_access_denied != 0) {
1949 WARNING("- Could not capture security descriptor at all\n"
1950 " on %lu files or directories.",
1951 ctx->num_get_sd_access_denied);
1953 WARNING("To fully capture all security descriptors, run the program\n"
1954 " with Administrator rights.");
1957 /*----------------------------------------------------------------------------*
1958 * Fast MFT scan implementation *
1959 *----------------------------------------------------------------------------*/
1961 #define ENABLE_FAST_MFT_SCAN 1
1963 #ifdef ENABLE_FAST_MFT_SCAN
1966 u64 StartingCluster;
1971 u64 StartingFileReferenceNumber;
1972 u64 EndingFileReferenceNumber;
1973 } FILE_REFERENCE_RANGE;
1975 /* The FSCTL_QUERY_FILE_LAYOUT ioctl. This ioctl can be used on Windows 8 and
1976 * later to scan the MFT of an NTFS volume. */
1977 #define FSCTL_QUERY_FILE_LAYOUT CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 157, METHOD_NEITHER, FILE_ANY_ACCESS)
1979 /* The input to FSCTL_QUERY_FILE_LAYOUT */
1982 #define QUERY_FILE_LAYOUT_RESTART 0x00000001
1983 #define QUERY_FILE_LAYOUT_INCLUDE_NAMES 0x00000002
1984 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS 0x00000004
1985 #define QUERY_FILE_LAYOUT_INCLUDE_EXTENTS 0x00000008
1986 #define QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO 0x00000010
1987 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED 0x00000020
1989 #define QUERY_FILE_LAYOUT_FILTER_TYPE_NONE 0
1990 #define QUERY_FILE_LAYOUT_FILTER_TYPE_CLUSTERS 1
1991 #define QUERY_FILE_LAYOUT_FILTER_TYPE_FILEID 2
1992 #define QUERY_FILE_LAYOUT_NUM_FILTER_TYPES 3
1996 CLUSTER_RANGE ClusterRanges[1];
1997 FILE_REFERENCE_RANGE FileReferenceRanges[1];
1999 } QUERY_FILE_LAYOUT_INPUT;
2001 /* The header of the buffer returned by FSCTL_QUERY_FILE_LAYOUT */
2004 u32 FirstFileOffset;
2005 #define QUERY_FILE_LAYOUT_SINGLE_INSTANCED 0x00000001
2008 } QUERY_FILE_LAYOUT_OUTPUT;
2010 /* Inode information returned by FSCTL_QUERY_FILE_LAYOUT */
2016 u64 FileReferenceNumber;
2017 u32 FirstNameOffset;
2018 u32 FirstStreamOffset;
2019 u32 ExtraInfoOffset;
2021 } FILE_LAYOUT_ENTRY;
2023 /* Extra inode information returned by FSCTL_QUERY_FILE_LAYOUT */
2035 } FILE_LAYOUT_INFO_ENTRY;
2037 /* Filename (or dentry) information returned by FSCTL_QUERY_FILE_LAYOUT */
2040 #define FILE_LAYOUT_NAME_ENTRY_PRIMARY 0x00000001
2041 #define FILE_LAYOUT_NAME_ENTRY_DOS 0x00000002
2043 u64 ParentFileReferenceNumber;
2046 wchar_t FileName[1];
2047 } FILE_LAYOUT_NAME_ENTRY;
2049 /* Stream information returned by FSCTL_QUERY_FILE_LAYOUT */
2052 u32 NextStreamOffset;
2053 #define STREAM_LAYOUT_ENTRY_IMMOVABLE 0x00000001
2054 #define STREAM_LAYOUT_ENTRY_PINNED 0x00000002
2055 #define STREAM_LAYOUT_ENTRY_RESIDENT 0x00000004
2056 #define STREAM_LAYOUT_ENTRY_NO_CLUSTERS_ALLOCATED 0x00000008
2058 u32 ExtentInformationOffset;
2063 u32 StreamIdentifierLength;
2064 wchar_t StreamIdentifier[1];
2065 } STREAM_LAYOUT_ENTRY;
2069 #define STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS 0x00000001
2070 #define STREAM_EXTENT_ENTRY_ALL_EXTENTS 0x00000002
2073 RETRIEVAL_POINTERS_BUFFER RetrievalPointers;
2074 } ExtentInformation;
2075 } STREAM_EXTENT_ENTRY;
2077 /* Extract the MFT number part of the full inode number */
2078 #define NTFS_MFT_NO(ref) ((ref) & (((u64)1 << 48) - 1))
2080 /* Is the file the root directory of the NTFS volume? The root directory always
2081 * occupies MFT record 5. */
2082 #define NTFS_IS_ROOT_FILE(ino) (NTFS_MFT_NO(ino) == 5)
2084 /* Is the file a special NTFS file, other than the root directory? The special
2085 * files are the first 16 records in the MFT. */
2086 #define NTFS_IS_SPECIAL_FILE(ino) \
2087 (NTFS_MFT_NO(ino) <= 15 && !NTFS_IS_ROOT_FILE(ino))
2089 #define NTFS_SPECIAL_STREAM_OBJECT_ID 0x00000001
2090 #define NTFS_SPECIAL_STREAM_EA 0x00000002
2091 #define NTFS_SPECIAL_STREAM_EA_INFORMATION 0x00000004
2093 /* Intermediate inode structure. This is used to temporarily save information
2094 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_inode'. */
2096 struct avl_tree_node index_node;
2099 u64 last_access_time;
2100 u64 last_write_time;
2106 u32 special_streams;
2107 u32 first_stream_offset;
2108 struct ntfs_dentry *first_child;
2109 wchar_t short_name[13];
2112 /* Intermediate dentry structure. This is used to temporarily save information
2113 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_dentry'. */
2114 struct ntfs_dentry {
2115 u32 offset_from_inode : 31;
2118 /* Note: build_children_lists() replaces 'parent_ino' with
2121 struct ntfs_dentry *next_child;
2126 /* Intermediate stream structure. This is used to temporarily save information
2127 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct
2128 * wim_inode_stream'. */
2129 struct ntfs_stream {
2134 /* Map of all known NTFS inodes, keyed by inode number */
2135 struct ntfs_inode_map {
2136 struct avl_tree_node *root;
2139 #define NTFS_INODE(node) \
2140 avl_tree_entry((node), struct ntfs_inode, index_node)
2142 #define SKIP_ALIGNED(p, size) ((void *)(p) + ALIGN((size), 8))
2144 /* Get a pointer to the first dentry of the inode. */
2145 #define FIRST_DENTRY(ni) SKIP_ALIGNED((ni), sizeof(struct ntfs_inode))
2147 /* Get a pointer to the first stream of the inode. */
2148 #define FIRST_STREAM(ni) ((const void *)ni + ni->first_stream_offset)
2150 /* Advance to the next dentry of the inode. */
2151 #define NEXT_DENTRY(nd) SKIP_ALIGNED((nd), sizeof(struct ntfs_dentry) + \
2152 (wcslen((nd)->name) + 1) * sizeof(wchar_t))
2154 /* Advance to the next stream of the inode. */
2155 #define NEXT_STREAM(ns) SKIP_ALIGNED((ns), sizeof(struct ntfs_stream) + \
2156 (wcslen((ns)->name) + 1) * sizeof(wchar_t))
2159 _avl_cmp_ntfs_inodes(const struct avl_tree_node *node1,
2160 const struct avl_tree_node *node2)
2162 return cmp_u64(NTFS_INODE(node1)->ino, NTFS_INODE(node2)->ino);
2165 /* Adds an NTFS inode to the map. */
2167 ntfs_inode_map_add_inode(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2169 if (avl_tree_insert(&map->root, &ni->index_node, _avl_cmp_ntfs_inodes)) {
2170 WARNING("Inode 0x%016"PRIx64" is a duplicate!", ni->ino);
2175 /* Find an ntfs_inode in the map by inode number. Returns NULL if not found. */
2176 static struct ntfs_inode *
2177 ntfs_inode_map_lookup(struct ntfs_inode_map *map, u64 ino)
2179 struct ntfs_inode tmp;
2180 struct avl_tree_node *res;
2183 res = avl_tree_lookup_node(map->root, &tmp.index_node, _avl_cmp_ntfs_inodes);
2186 return NTFS_INODE(res);
2189 /* Remove an ntfs_inode from the map and free it. */
2191 ntfs_inode_map_remove(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2193 avl_tree_remove(&map->root, &ni->index_node);
2197 /* Free all ntfs_inodes in the map. */
2199 ntfs_inode_map_destroy(struct ntfs_inode_map *map)
2201 struct ntfs_inode *ni;
2203 avl_tree_for_each_in_postorder(ni, map->root, struct ntfs_inode, index_node)
2208 file_has_streams(const FILE_LAYOUT_ENTRY *file)
2210 return (file->FirstStreamOffset != 0) &&
2211 !(file->FileAttributes & FILE_ATTRIBUTE_ENCRYPTED);
2215 is_valid_name_entry(const FILE_LAYOUT_NAME_ENTRY *name)
2217 return name->FileNameLength > 0 &&
2218 name->FileNameLength % 2 == 0 &&
2219 !wmemchr(name->FileName, L'\0', name->FileNameLength / 2) &&
2220 (!(name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) ||
2221 name->FileNameLength <= 24);
2224 /* Validate the FILE_LAYOUT_NAME_ENTRYs of the specified file and compute the
2225 * total length in bytes of the ntfs_dentry structures needed to hold the name
2228 validate_names_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2229 size_t *total_length_ret)
2231 const FILE_LAYOUT_NAME_ENTRY *name =
2232 (const void *)file + file->FirstNameOffset;
2234 size_t num_long_names = 0;
2237 if (unlikely(!is_valid_name_entry(name))) {
2238 ERROR("Invalid FILE_LAYOUT_NAME_ENTRY! "
2239 "FileReferenceNumber=0x%016"PRIx64", "
2240 "FileNameLength=%"PRIu32", "
2241 "FileName=%.*ls, Flags=0x%08"PRIx32,
2242 file->FileReferenceNumber,
2243 name->FileNameLength,
2244 (int)(name->FileNameLength / 2),
2245 name->FileName, name->Flags);
2246 return WIMLIB_ERR_UNSUPPORTED;
2248 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2250 total += ALIGN(sizeof(struct ntfs_dentry) +
2251 name->FileNameLength + sizeof(wchar_t),
2254 if (name->NextNameOffset == 0)
2256 name = (const void *)name + name->NextNameOffset;
2259 if (unlikely(num_long_names == 0)) {
2260 ERROR("Inode 0x%016"PRIx64" has no long names!",
2261 file->FileReferenceNumber);
2262 return WIMLIB_ERR_UNSUPPORTED;
2265 *total_length_ret = total;
2270 is_valid_stream_entry(const STREAM_LAYOUT_ENTRY *stream)
2272 return stream->StreamIdentifierLength % 2 == 0 &&
2273 !wmemchr(stream->StreamIdentifier , L'\0',
2274 stream->StreamIdentifierLength / 2);
2277 /* assumes that 'id' is a wide string literal */
2278 #define stream_has_identifier(stream, id) \
2279 ((stream)->StreamIdentifierLength == sizeof(id) - 2 && \
2280 !memcmp((stream)->StreamIdentifier, id, sizeof(id) - 2))
2282 * If the specified STREAM_LAYOUT_ENTRY represents a DATA stream as opposed to
2283 * some other type of NTFS stream such as a STANDARD_INFORMATION stream, return
2284 * true and set *stream_name_ret and *stream_name_nchars_ret to specify just the
2285 * stream name. For example, ":foo:$DATA" would become "foo" with length 3
2286 * characters. Otherwise return false.
2289 use_stream(const FILE_LAYOUT_ENTRY *file, const STREAM_LAYOUT_ENTRY *stream,
2290 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
2292 const wchar_t *stream_name;
2293 size_t stream_name_nchars;
2295 if (stream->StreamIdentifierLength == 0) {
2296 /* The unnamed data stream may be given as an empty string
2297 * rather than as "::$DATA". Handle it both ways. */
2299 stream_name_nchars = 0;
2300 } else if (!get_data_stream_name(stream->StreamIdentifier,
2301 stream->StreamIdentifierLength / 2,
2302 &stream_name, &stream_name_nchars))
2305 /* Skip the unnamed data stream for directories. */
2306 if (stream_name_nchars == 0 &&
2307 (file->FileAttributes & FILE_ATTRIBUTE_DIRECTORY))
2310 *stream_name_ret = stream_name;
2311 *stream_name_nchars_ret = stream_name_nchars;
2315 /* Validate the STREAM_LAYOUT_ENTRYs of the specified file and compute the total
2316 * length in bytes of the ntfs_stream structures needed to hold the stream
2317 * information. In addition, set *special_streams_ret to a bitmask of special
2318 * stream types that were found. */
2320 validate_streams_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2321 size_t *total_length_ret,
2322 u32 *special_streams_ret)
2324 const STREAM_LAYOUT_ENTRY *stream =
2325 (const void *)file + file->FirstStreamOffset;
2327 u32 special_streams = 0;
2330 const wchar_t *name;
2333 if (unlikely(!is_valid_stream_entry(stream))) {
2334 WARNING("Invalid STREAM_LAYOUT_ENTRY! "
2335 "FileReferenceNumber=0x%016"PRIx64", "
2336 "StreamIdentifierLength=%"PRIu32", "
2337 "StreamIdentifier=%.*ls",
2338 file->FileReferenceNumber,
2339 stream->StreamIdentifierLength,
2340 (int)(stream->StreamIdentifierLength / 2),
2341 stream->StreamIdentifier);
2342 return WIMLIB_ERR_UNSUPPORTED;
2345 if (use_stream(file, stream, &name, &name_nchars)) {
2346 total += ALIGN(sizeof(struct ntfs_stream) +
2347 (name_nchars + 1) * sizeof(wchar_t), 8);
2348 } else if (stream_has_identifier(stream, L"::$OBJECT_ID")) {
2349 special_streams |= NTFS_SPECIAL_STREAM_OBJECT_ID;
2350 } else if (stream_has_identifier(stream, L"::$EA")) {
2351 special_streams |= NTFS_SPECIAL_STREAM_EA;
2352 } else if (stream_has_identifier(stream, L"::$EA_INFORMATION")) {
2353 special_streams |= NTFS_SPECIAL_STREAM_EA_INFORMATION;
2355 if (stream->NextStreamOffset == 0)
2357 stream = (const void *)stream + stream->NextStreamOffset;
2360 *total_length_ret = total;
2361 *special_streams_ret = special_streams;
2366 load_name_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2369 const FILE_LAYOUT_NAME_ENTRY *name =
2370 (const void *)file + file->FirstNameOffset;
2372 struct ntfs_dentry *nd = p;
2373 /* Note that a name may be just a short (DOS) name, just a long
2374 * name, or both a short name and a long name. If there is a
2375 * short name, one name should also be marked as "primary" to
2376 * indicate which long name the short name is associated with.
2377 * Also, there should be at most one short name per inode. */
2378 if (name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) {
2379 memcpy(ni->short_name,
2380 name->FileName, name->FileNameLength);
2381 ni->short_name[name->FileNameLength / 2] = L'\0';
2383 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2385 nd->offset_from_inode = (u8 *)nd - (u8 *)ni;
2386 nd->is_primary = ((name->Flags &
2387 FILE_LAYOUT_NAME_ENTRY_PRIMARY) != 0);
2388 nd->parent_ino = name->ParentFileReferenceNumber;
2389 memcpy(nd->name, name->FileName, name->FileNameLength);
2390 nd->name[name->FileNameLength / 2] = L'\0';
2391 p += ALIGN(sizeof(struct ntfs_dentry) +
2392 name->FileNameLength + sizeof(wchar_t), 8);
2394 if (name->NextNameOffset == 0)
2396 name = (const void *)name + name->NextNameOffset;
2402 load_starting_lcn(const STREAM_LAYOUT_ENTRY *stream)
2404 const STREAM_EXTENT_ENTRY *entry;
2406 if (stream->ExtentInformationOffset == 0)
2409 entry = (const void *)stream + stream->ExtentInformationOffset;
2411 if (!(entry->Flags & STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS))
2414 return extract_starting_lcn(&entry->ExtentInformation.RetrievalPointers);
2418 load_stream_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2421 const STREAM_LAYOUT_ENTRY *stream =
2422 (const void *)file + file->FirstStreamOffset;
2423 const u32 first_stream_offset = (const u8 *)p - (const u8 *)ni;
2425 struct ntfs_stream *ns = p;
2426 const wchar_t *name;
2429 if (use_stream(file, stream, &name, &name_nchars)) {
2430 ni->first_stream_offset = first_stream_offset;
2432 if (name_nchars == 0)
2433 ni->starting_lcn = load_starting_lcn(stream);
2434 ns->size = stream->EndOfFile;
2435 wmemcpy(ns->name, name, name_nchars);
2436 ns->name[name_nchars] = L'\0';
2437 p += ALIGN(sizeof(struct ntfs_stream) +
2438 (name_nchars + 1) * sizeof(wchar_t), 8);
2440 if (stream->NextStreamOffset == 0)
2442 stream = (const void *)stream + stream->NextStreamOffset;
2447 /* Process the information for a file given by FSCTL_QUERY_FILE_LAYOUT. */
2449 load_one_file(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode_map *inode_map)
2451 const FILE_LAYOUT_INFO_ENTRY *info =
2452 (const void *)file + file->ExtraInfoOffset;
2454 struct ntfs_inode *ni;
2458 u32 special_streams = 0;
2460 inode_size = ALIGN(sizeof(struct ntfs_inode), 8);
2462 /* The root file should have no names, and all other files should have
2463 * at least one name. But just in case, we ignore the names of the root
2464 * file, and we ignore any non-root file with no names. */
2465 if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber)) {
2466 if (file->FirstNameOffset == 0)
2468 ret = validate_names_and_compute_total_length(file, &n);
2474 if (file_has_streams(file)) {
2475 ret = validate_streams_and_compute_total_length(file, &n,
2482 /* To save memory, we allocate the ntfs_dentry's and ntfs_stream's in
2483 * the same memory block as their ntfs_inode. */
2484 ni = CALLOC(1, inode_size);
2486 return WIMLIB_ERR_NOMEM;
2488 ni->ino = file->FileReferenceNumber;
2489 ni->attributes = info->BasicInformation.FileAttributes;
2490 ni->creation_time = info->BasicInformation.CreationTime;
2491 ni->last_write_time = info->BasicInformation.LastWriteTime;
2492 ni->last_access_time = info->BasicInformation.LastAccessTime;
2493 ni->security_id = info->SecurityId;
2494 ni->special_streams = special_streams;
2496 p = FIRST_DENTRY(ni);
2498 if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber))
2499 p = load_name_information(file, ni, p);
2501 if (file_has_streams(file))
2502 p = load_stream_information(file, ni, p);
2504 wimlib_assert((u8 *)p - (u8 *)ni == inode_size);
2506 ntfs_inode_map_add_inode(inode_map, ni);
2511 * Quickly find all files on an NTFS volume by using FSCTL_QUERY_FILE_LAYOUT to
2512 * scan the MFT. The NTFS volume is specified by the NT namespace path @path.
2513 * For each file, allocate an 'ntfs_inode' structure for each file and add it to
2514 * 'inode_map' keyed by inode number. Include NTFS special files such as
2515 * $Bitmap (they will be removed later).
2518 load_files_from_mft(const wchar_t *path, struct ntfs_inode_map *inode_map)
2521 QUERY_FILE_LAYOUT_INPUT in = (QUERY_FILE_LAYOUT_INPUT) {
2523 .Flags = QUERY_FILE_LAYOUT_RESTART |
2524 QUERY_FILE_LAYOUT_INCLUDE_NAMES |
2525 QUERY_FILE_LAYOUT_INCLUDE_STREAMS |
2526 QUERY_FILE_LAYOUT_INCLUDE_EXTENTS |
2527 QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO |
2528 QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED,
2529 .FilterType = QUERY_FILE_LAYOUT_FILTER_TYPE_NONE,
2531 size_t outsize = 32768;
2532 QUERY_FILE_LAYOUT_OUTPUT *out = NULL;
2536 status = winnt_open(path, wcslen(path),
2537 FILE_READ_DATA | FILE_READ_ATTRIBUTES, &h);
2538 if (!NT_SUCCESS(status)) {
2539 ret = -1; /* Silently try standard recursive scan instead */
2544 /* Allocate a buffer for the output of the ioctl. */
2545 out = MALLOC(outsize);
2547 ret = WIMLIB_ERR_NOMEM;
2551 /* Execute FSCTL_QUERY_FILE_LAYOUT until it fails. */
2552 while (NT_SUCCESS(status = winnt_fsctl(h,
2553 FSCTL_QUERY_FILE_LAYOUT,
2555 out, outsize, NULL)))
2557 const FILE_LAYOUT_ENTRY *file =
2558 (const void *)out + out->FirstFileOffset;
2560 ret = load_one_file(file, inode_map);
2563 if (file->NextFileOffset == 0)
2565 file = (const void *)file + file->NextFileOffset;
2567 in.Flags &= ~QUERY_FILE_LAYOUT_RESTART;
2570 /* Enlarge the buffer if needed. */
2571 if (status != STATUS_BUFFER_TOO_SMALL)
2577 /* Normally, FSCTL_QUERY_FILE_LAYOUT fails with STATUS_END_OF_FILE after
2578 * all files have been enumerated. */
2579 if (status != STATUS_END_OF_FILE) {
2580 if (status == STATUS_INVALID_DEVICE_REQUEST /* old OS */ ||
2581 status == STATUS_NOT_SUPPORTED /* Samba volume, WinXP */ ||
2582 status == STATUS_INVALID_PARAMETER /* not root directory */ )
2584 /* Silently try standard recursive scan instead */
2588 L"Error enumerating files on volume \"%ls\"",
2590 /* Try standard recursive scan instead */
2591 ret = WIMLIB_ERR_UNSUPPORTED;
2602 /* Build the list of child dentries for each inode in @map. This is done by
2603 * iterating through each name of each inode and adding it to its parent's
2604 * children list. Note that every name should have a parent, i.e. should belong
2605 * to some directory. The root directory does not have any names. */
2607 build_children_lists(struct ntfs_inode_map *map, struct ntfs_inode **root_ret)
2609 struct ntfs_inode *ni;
2611 avl_tree_for_each_in_order(ni, map->root, struct ntfs_inode, index_node)
2613 struct ntfs_dentry *nd;
2616 if (NTFS_IS_ROOT_FILE(ni->ino)) {
2621 n = ni->num_aliases;
2622 nd = FIRST_DENTRY(ni);
2624 struct ntfs_inode *parent;
2626 parent = ntfs_inode_map_lookup(map, nd->parent_ino);
2627 if (unlikely(!parent)) {
2628 ERROR("Parent inode 0x%016"PRIx64" of"
2629 "directory entry \"%ls\" (inode "
2630 "0x%016"PRIx64") was missing from the "
2632 nd->parent_ino, nd->name, ni->ino);
2633 return WIMLIB_ERR_UNSUPPORTED;
2635 nd->next_child = parent->first_child;
2636 parent->first_child = nd;
2639 nd = NEXT_DENTRY(nd);
2645 struct security_map_node {
2646 struct avl_tree_node index_node;
2647 u32 disk_security_id;
2648 u32 wim_security_id;
2651 /* Map from disk security IDs to WIM security IDs */
2652 struct security_map {
2653 struct avl_tree_node *root;
2656 #define SECURITY_MAP_NODE(node) \
2657 avl_tree_entry((node), struct security_map_node, index_node)
2660 _avl_cmp_security_map_nodes(const struct avl_tree_node *node1,
2661 const struct avl_tree_node *node2)
2663 return cmp_u32(SECURITY_MAP_NODE(node1)->disk_security_id,
2664 SECURITY_MAP_NODE(node2)->disk_security_id);
2668 security_map_lookup(struct security_map *map, u32 disk_security_id)
2670 struct security_map_node tmp;
2671 const struct avl_tree_node *res;
2673 if (disk_security_id == 0) /* No on-disk security ID; uncacheable */
2676 tmp.disk_security_id = disk_security_id;
2677 res = avl_tree_lookup_node(map->root, &tmp.index_node,
2678 _avl_cmp_security_map_nodes);
2681 return SECURITY_MAP_NODE(res)->wim_security_id;
2685 security_map_insert(struct security_map *map, u32 disk_security_id,
2686 u32 wim_security_id)
2688 struct security_map_node *node;
2690 if (disk_security_id == 0) /* No on-disk security ID; uncacheable */
2693 node = MALLOC(sizeof(*node));
2695 return WIMLIB_ERR_NOMEM;
2697 node->disk_security_id = disk_security_id;
2698 node->wim_security_id = wim_security_id;
2699 avl_tree_insert(&map->root, &node->index_node,
2700 _avl_cmp_security_map_nodes);
2705 security_map_destroy(struct security_map *map)
2707 struct security_map_node *node;
2709 avl_tree_for_each_in_postorder(node, map->root,
2710 struct security_map_node, index_node)
2715 * Turn our temporary NTFS structures into the final WIM structures:
2717 * ntfs_inode => wim_inode
2718 * ntfs_dentry => wim_dentry
2719 * ntfs_stream => wim_inode_stream
2721 * This also handles things such as exclusions and issuing progress messages.
2722 * It's similar to winnt_build_dentry_tree(), but this is much faster because
2723 * almost all information we need is already loaded in memory in the ntfs_*
2724 * structures. However, in some cases we still fall back to
2725 * winnt_build_dentry_tree() and/or opening the file.
2728 generate_wim_structures_recursive(struct wim_dentry **root_ret,
2729 const wchar_t *filename, bool is_primary_name,
2730 struct ntfs_inode *ni,
2731 struct winnt_scan_ctx *ctx,
2732 struct ntfs_inode_map *inode_map,
2733 struct security_map *security_map)
2736 struct wim_dentry *root = NULL;
2737 struct wim_inode *inode = NULL;
2738 const struct ntfs_stream *ns;
2740 /* Completely ignore NTFS special files. */
2741 if (NTFS_IS_SPECIAL_FILE(ni->ino))
2744 /* Fall back to the standard scan for unhandled cases. Reparse points,
2745 * in particular, can't be properly handled here because a commonly used
2746 * filter driver (WOF) hides reparse points from regular filesystem APIs
2747 * but not from FSCTL_QUERY_FILE_LAYOUT. */
2748 if (ni->attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
2749 FILE_ATTRIBUTE_ENCRYPTED) ||
2750 ni->special_streams != 0)
2752 ret = winnt_build_dentry_tree(&root, NULL,
2753 ctx->params->cur_path,
2754 ctx->params->cur_path_nchars,
2755 filename, ctx, false);
2756 if (ret) /* Error? */
2758 if (!root) /* Excluded? */
2760 inode = root->d_inode;
2761 goto process_children;
2764 /* Test for exclusion based on path. */
2765 ret = try_exclude(ctx->params);
2766 if (unlikely(ret < 0)) /* Excluded? */
2768 if (unlikely(ret > 0)) /* Error? */
2771 /* Create the WIM dentry and possibly a new WIM inode */
2772 ret = inode_table_new_dentry(ctx->params->inode_table, filename,
2773 ni->ino, ctx->params->capture_root_dev,
2778 inode = root->d_inode;
2780 /* Set the short name if needed. */
2781 if (is_primary_name && *ni->short_name) {
2782 size_t nbytes = wcslen(ni->short_name) * sizeof(wchar_t);
2783 root->d_short_name = memdup(ni->short_name,
2784 nbytes + sizeof(wchar_t));
2785 if (!root->d_short_name) {
2786 ret = WIMLIB_ERR_NOMEM;
2789 root->d_short_name_nbytes = nbytes;
2792 if (inode->i_nlink > 1) { /* Already seen this inode? */
2797 /* The file attributes and timestamps were cached from the MFT. */
2798 inode->i_attributes = ni->attributes;
2799 inode->i_creation_time = ni->creation_time;
2800 inode->i_last_write_time = ni->last_write_time;
2801 inode->i_last_access_time = ni->last_access_time;
2803 /* Set the security descriptor if needed. */
2804 if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)) {
2805 /* Look up the WIM security ID that corresponds to the on-disk
2807 s32 wim_security_id =
2808 security_map_lookup(security_map, ni->security_id);
2809 if (likely(wim_security_id >= 0)) {
2810 /* The mapping for this security ID is already cached.*/
2811 inode->i_security_id = wim_security_id;
2816 /* Create a mapping for this security ID and insert it
2817 * into the security map. */
2819 status = winnt_open(ctx->params->cur_path,
2820 ctx->params->cur_path_nchars,
2822 ACCESS_SYSTEM_SECURITY, &h);
2823 if (!NT_SUCCESS(status)) {
2824 winnt_error(status, L"Can't open \"%ls\" to "
2825 "read security descriptor",
2826 printable_path(ctx));
2827 ret = WIMLIB_ERR_OPEN;
2830 ret = winnt_load_security_descriptor(h, inode, ctx);
2835 ret = security_map_insert(security_map, ni->security_id,
2836 inode->i_security_id);
2842 /* Add data streams based on the cached information from the MFT. */
2843 ns = FIRST_STREAM(ni);
2844 for (u32 i = 0; i < ni->num_streams; i++) {
2845 struct windows_file *windows_file;
2847 /* Reference the stream by path if it's a named data stream, or
2848 * if the volume doesn't support "open by file ID", or if the
2849 * application hasn't explicitly opted in to "open by file ID".
2850 * Otherwise, only save the inode number (file ID). */
2852 !(ctx->vol_flags & FILE_SUPPORTS_OPEN_BY_FILE_ID) ||
2853 !(ctx->params->add_flags & WIMLIB_ADD_FLAG_FILE_PATHS_UNNEEDED))
2855 windows_file = alloc_windows_file(ctx->params->cur_path,
2856 ctx->params->cur_path_nchars,
2862 windows_file = alloc_windows_file_for_file_id(ni->ino,
2863 ctx->params->cur_path,
2864 ctx->params->root_path_nchars,
2868 ret = add_stream(inode, windows_file, ns->size,
2869 STREAM_TYPE_DATA, ns->name,
2870 ctx->params->unhashed_blobs);
2873 ns = NEXT_STREAM(ns);
2876 set_sort_key(inode, ni->starting_lcn);
2878 /* If processing a directory, then recurse to its children. In this
2879 * version there is no need to go to disk, as we already have the list
2880 * of children cached from the MFT. */
2882 if (inode_is_directory(inode)) {
2883 const struct ntfs_dentry *nd = ni->first_child;
2885 while (nd != NULL) {
2886 size_t orig_path_nchars;
2887 struct wim_dentry *child;
2888 const struct ntfs_dentry *next = nd->next_child;
2890 ret = WIMLIB_ERR_NOMEM;
2891 if (!pathbuf_append_name(ctx->params, nd->name,
2896 ret = generate_wim_structures_recursive(
2900 (void *)nd - nd->offset_from_inode,
2905 pathbuf_truncate(ctx->params, orig_path_nchars);
2910 attach_scanned_tree(root, child, ctx->params->blob_table);
2917 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_OK, inode);
2919 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
2921 if (--ni->num_aliases == 0) {
2922 /* Memory usage optimization: when we don't need the ntfs_inode
2923 * (and its names and streams) anymore, free it. */
2924 ntfs_inode_map_remove(inode_map, ni);
2926 if (unlikely(ret)) {
2927 free_dentry_tree(root, ctx->params->blob_table);
2935 winnt_build_dentry_tree_fast(struct wim_dentry **root_ret,
2936 struct winnt_scan_ctx *ctx)
2938 struct ntfs_inode_map inode_map = { .root = NULL };
2939 struct security_map security_map = { .root = NULL };
2940 struct ntfs_inode *root = NULL;
2941 wchar_t *path = ctx->params->cur_path;
2942 size_t path_nchars = ctx->params->cur_path_nchars;
2946 adjust_path = (path[path_nchars - 1] == L'\\');
2948 path[path_nchars - 1] = L'\0';
2950 ret = load_files_from_mft(path, &inode_map);
2953 path[path_nchars - 1] = L'\\';
2958 ret = build_children_lists(&inode_map, &root);
2963 ERROR("The MFT listing for volume \"%ls\" did not include a "
2964 "root directory!", path);
2965 ret = WIMLIB_ERR_UNSUPPORTED;
2969 root->num_aliases = 1;
2971 ret = generate_wim_structures_recursive(root_ret, L"", false, root, ctx,
2972 &inode_map, &security_map);
2974 ntfs_inode_map_destroy(&inode_map);
2975 security_map_destroy(&security_map);
2979 #endif /* ENABLE_FAST_MFT_SCAN */
2981 /*----------------------------------------------------------------------------*
2982 * Entry point for directory tree scans on Windows *
2983 *----------------------------------------------------------------------------*/
2986 win32_build_dentry_tree(struct wim_dentry **root_ret,
2987 const wchar_t *root_disk_path,
2988 struct scan_params *params)
2990 struct winnt_scan_ctx ctx = { .params = params };
2991 UNICODE_STRING ntpath;
2996 if (params->add_flags & WIMLIB_ADD_FLAG_SNAPSHOT)
2997 ret = vss_create_snapshot(root_disk_path, &ntpath, &ctx.snapshot);
2999 ret = win32_path_to_nt_path(root_disk_path, &ntpath);
3004 if (ntpath.Length < 4 * sizeof(wchar_t) ||
3005 wmemcmp(ntpath.Buffer, L"\\??\\", 4))
3007 ERROR("\"%ls\": unrecognized path format", root_disk_path);
3008 ret = WIMLIB_ERR_INVALID_PARAM;
3010 ret = pathbuf_init(params, ntpath.Buffer);
3012 HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
3016 status = winnt_open(params->cur_path, params->cur_path_nchars,
3017 FILE_READ_ATTRIBUTES, &h);
3018 if (!NT_SUCCESS(status)) {
3019 winnt_error(status, L"Can't open \"%ls\"", root_disk_path);
3020 if (status == STATUS_FVE_LOCKED_VOLUME)
3021 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
3023 ret = WIMLIB_ERR_OPEN;
3027 get_volume_information(h, &ctx);
3031 #ifdef ENABLE_FAST_MFT_SCAN
3032 if (ctx.is_ntfs && !_wgetenv(L"WIMLIB_DISABLE_QUERY_FILE_LAYOUT")) {
3033 ret = winnt_build_dentry_tree_fast(root_ret, &ctx);
3034 if (ret >= 0 && ret != WIMLIB_ERR_UNSUPPORTED)
3037 WARNING("A problem occurred during the fast MFT scan.\n"
3038 " Falling back to the standard "
3039 "recursive directory tree scan.");
3043 ret = winnt_build_dentry_tree(root_ret, NULL, params->cur_path,
3044 params->cur_path_nchars, L"", &ctx, true);
3046 vss_put_snapshot(ctx.snapshot);
3048 winnt_do_scan_warnings(root_disk_path, &ctx);
3052 #endif /* __WIN32__ */