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-2017 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"
45 struct winnt_scan_ctx {
46 struct scan_params *params;
49 unsigned long num_get_sd_access_denied;
50 unsigned long num_get_sacl_priv_notheld;
52 /* True if WOF is definitely not attached to the volume being scanned;
53 * false if it may be */
54 bool wof_not_attached;
56 /* A reference to the VSS snapshot being used, or NULL if none */
57 struct vss_snapshot *snapshot;
60 static inline const wchar_t *
61 printable_path(const struct winnt_scan_ctx *ctx)
63 /* Skip over \\?\ or \??\ */
64 return ctx->params->cur_path + 4;
67 /* Description of where data is located on a Windows filesystem */
70 /* Is the data the raw encrypted data of an EFS-encrypted file? */
73 /* Is this file "open by file ID" rather than the regular "open by
74 * path"? "Open by file ID" uses resources more efficiently. */
77 /* The file's LCN (logical cluster number) for sorting, or 0 if unknown.
81 /* Length of the path in bytes, excluding the null terminator if
85 /* A reference to the VSS snapshot containing the file, or NULL if none.
87 struct vss_snapshot *snapshot;
89 /* The path to the file. If 'is_encrypted=0' this is an NT namespace
90 * path; if 'is_encrypted=1' this is a Win32 namespace path. If
91 * 'is_file_id=0', then the path is null-terminated. If 'is_file_id=1'
92 * (only allowed with 'is_encrypted=0') the path ends with a binary file
93 * ID and may not be null-terminated. */
97 /* Allocate a structure to describe the location of a data stream by path. */
98 static struct windows_file *
99 alloc_windows_file(const wchar_t *path, size_t path_nchars,
100 const wchar_t *stream_name, size_t stream_name_nchars,
101 struct vss_snapshot *snapshot, bool is_encrypted)
103 size_t full_path_nbytes;
104 struct windows_file *file;
107 full_path_nbytes = path_nchars * sizeof(wchar_t);
108 if (stream_name_nchars)
109 full_path_nbytes += (1 + stream_name_nchars) * sizeof(wchar_t);
111 file = MALLOC(sizeof(struct windows_file) + full_path_nbytes +
116 file->is_encrypted = is_encrypted;
117 file->is_file_id = 0;
119 file->path_nbytes = full_path_nbytes;
120 file->snapshot = vss_get_snapshot(snapshot);
121 p = wmempcpy(file->path, path, path_nchars);
122 if (stream_name_nchars) {
123 /* Named data stream */
125 p = wmempcpy(p, stream_name, stream_name_nchars);
131 /* Allocate a structure to describe the location of a file by ID. */
132 static struct windows_file *
133 alloc_windows_file_for_file_id(u64 file_id, const wchar_t *root_path,
134 size_t root_path_nchars,
135 struct vss_snapshot *snapshot)
137 size_t full_path_nbytes;
138 struct windows_file *file;
141 full_path_nbytes = (root_path_nchars * sizeof(wchar_t)) +
143 file = MALLOC(sizeof(struct windows_file) + full_path_nbytes +
148 file->is_encrypted = 0;
149 file->is_file_id = 1;
151 file->path_nbytes = full_path_nbytes;
152 file->snapshot = vss_get_snapshot(snapshot);
153 p = wmempcpy(file->path, root_path, root_path_nchars);
154 p = mempcpy(p, &file_id, sizeof(file_id));
159 /* Add a stream, located on a Windows filesystem, to the specified WIM inode. */
161 add_stream(struct wim_inode *inode, struct windows_file *windows_file,
162 u64 stream_size, int stream_type, const utf16lechar *stream_name,
163 struct list_head *unhashed_blobs)
165 struct blob_descriptor *blob = NULL;
166 struct wim_inode_stream *strm;
172 /* If the stream is nonempty, create a blob descriptor for it. */
174 blob = new_blob_descriptor();
177 blob->windows_file = windows_file;
178 blob->blob_location = BLOB_IN_WINDOWS_FILE;
179 blob->file_inode = inode;
180 blob->size = stream_size;
184 strm = inode_add_stream(inode, stream_type, stream_name, blob);
188 prepare_unhashed_blob(blob, inode, strm->stream_id, unhashed_blobs);
192 free_windows_file(windows_file);
196 free_blob_descriptor(blob);
197 ret = WIMLIB_ERR_NOMEM;
201 struct windows_file *
202 clone_windows_file(const struct windows_file *file)
204 struct windows_file *new;
206 new = memdup(file, sizeof(*file) + file->path_nbytes + sizeof(wchar_t));
208 vss_get_snapshot(new->snapshot);
213 free_windows_file(struct windows_file *file)
215 vss_put_snapshot(file->snapshot);
220 cmp_windows_files(const struct windows_file *file1,
221 const struct windows_file *file2)
223 /* Compare by starting LCN (logical cluster number) */
224 int v = cmp_u64(file1->sort_key, file2->sort_key);
228 /* Fall back to comparing files by path (arbitrary heuristic). */
229 v = memcmp(file1->path, file2->path,
230 min(file1->path_nbytes, file2->path_nbytes));
234 return cmp_u32(file1->path_nbytes, file2->path_nbytes);
238 get_windows_file_path(const struct windows_file *file)
244 * Open the file named by the NT namespace path @path of length @path_nchars
245 * characters. If @cur_dir is not NULL then the path is given relative to
246 * @cur_dir; otherwise the path is absolute. @perms is the access mask of
247 * permissions to request on the handle. SYNCHRONIZE permision is always added.
250 winnt_openat(HANDLE cur_dir, const wchar_t *path, size_t path_nchars,
251 ACCESS_MASK perms, HANDLE *h_ret)
253 UNICODE_STRING name = {
254 .Length = path_nchars * sizeof(wchar_t),
255 .MaximumLength = path_nchars * sizeof(wchar_t),
256 .Buffer = (wchar_t *)path,
258 OBJECT_ATTRIBUTES attr = {
259 .Length = sizeof(attr),
260 .RootDirectory = cur_dir,
263 IO_STATUS_BLOCK iosb;
265 ULONG options = FILE_OPEN_REPARSE_POINT | FILE_OPEN_FOR_BACKUP_INTENT;
267 perms |= SYNCHRONIZE;
268 if (perms & (FILE_READ_DATA | FILE_LIST_DIRECTORY)) {
269 options |= FILE_SYNCHRONOUS_IO_NONALERT;
270 options |= FILE_SEQUENTIAL_ONLY;
273 status = NtOpenFile(h_ret, perms, &attr, &iosb,
274 FILE_SHARE_VALID_FLAGS, options);
275 if (!NT_SUCCESS(status)) {
276 /* Try requesting fewer permissions */
277 if (status == STATUS_ACCESS_DENIED ||
278 status == STATUS_PRIVILEGE_NOT_HELD) {
279 if (perms & ACCESS_SYSTEM_SECURITY) {
280 perms &= ~ACCESS_SYSTEM_SECURITY;
283 if (perms & READ_CONTROL) {
284 perms &= ~READ_CONTROL;
293 winnt_open(const wchar_t *path, size_t path_nchars, ACCESS_MASK perms,
296 return winnt_openat(NULL, path, path_nchars, perms, h_ret);
299 static const wchar_t *
300 windows_file_to_string(const struct windows_file *file, u8 *buf, size_t bufsize)
302 if (file->is_file_id) {
305 (u8 *)file->path + file->path_nbytes - sizeof(file_id),
307 swprintf((wchar_t *)buf, L"NTFS inode 0x%016"PRIx64, file_id);
308 } else if (file->path_nbytes + 3 * sizeof(wchar_t) <= bufsize) {
309 swprintf((wchar_t *)buf, L"\"%ls\"", file->path);
311 return L"(name too long)";
313 return (wchar_t *)buf;
317 read_winnt_stream_prefix(const struct windows_file *file,
318 u64 size, const struct consume_chunk_callback *cb)
320 IO_STATUS_BLOCK iosb;
321 UNICODE_STRING name = {
322 .Buffer = (wchar_t *)file->path,
323 .Length = file->path_nbytes,
324 .MaximumLength = file->path_nbytes,
326 OBJECT_ATTRIBUTES attr = {
327 .Length = sizeof(attr),
332 u8 buf[BUFFER_SIZE] _aligned_attribute(8);
336 status = NtOpenFile(&h, FILE_READ_DATA | SYNCHRONIZE,
338 FILE_SHARE_VALID_FLAGS,
339 FILE_OPEN_REPARSE_POINT |
340 FILE_OPEN_FOR_BACKUP_INTENT |
341 FILE_SYNCHRONOUS_IO_NONALERT |
342 FILE_SEQUENTIAL_ONLY |
343 (file->is_file_id ? FILE_OPEN_BY_FILE_ID : 0));
344 if (unlikely(!NT_SUCCESS(status))) {
345 if (status == STATUS_SHARING_VIOLATION) {
346 ERROR("Can't open %ls for reading:\n"
347 " File is in use by another process! "
348 "Consider using snapshot (VSS) mode.",
349 windows_file_to_string(file, buf, sizeof(buf)));
351 winnt_error(status, L"Can't open %ls for reading",
352 windows_file_to_string(file, buf, sizeof(buf)));
354 return WIMLIB_ERR_OPEN;
358 bytes_remaining = size;
359 while (bytes_remaining) {
360 IO_STATUS_BLOCK iosb;
363 const unsigned max_tries = 5;
364 unsigned tries_remaining = max_tries;
366 count = min(sizeof(buf), bytes_remaining);
369 status = NtReadFile(h, NULL, NULL, NULL,
370 &iosb, buf, count, NULL, NULL);
371 if (unlikely(!NT_SUCCESS(status))) {
372 if (status == STATUS_END_OF_FILE) {
373 ERROR("%ls: File was concurrently truncated",
374 windows_file_to_string(file, buf, sizeof(buf)));
375 ret = WIMLIB_ERR_CONCURRENT_MODIFICATION_DETECTED;
377 winnt_warning(status, L"Error reading data from %ls",
378 windows_file_to_string(file, buf, sizeof(buf)));
380 /* Currently these retries are purely a guess;
381 * there is no reproducible problem that they solve. */
382 if (--tries_remaining) {
384 if (status == STATUS_INSUFFICIENT_RESOURCES ||
385 status == STATUS_NO_MEMORY) {
388 WARNING("Retrying after %dms...", delay);
392 ERROR("Too many retries; returning failure");
393 ret = WIMLIB_ERR_READ;
396 } else if (unlikely(tries_remaining != max_tries)) {
397 WARNING("A read request had to be retried multiple times "
398 "before it succeeded!");
401 bytes_read = iosb.Information;
403 bytes_remaining -= bytes_read;
404 ret = consume_chunk(cb, buf, bytes_read);
412 struct win32_encrypted_read_ctx {
413 const struct consume_chunk_callback *cb;
419 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
421 struct win32_encrypted_read_ctx *ctx = _ctx;
423 size_t bytes_to_consume = min(len, ctx->bytes_remaining);
425 if (bytes_to_consume == 0)
426 return ERROR_SUCCESS;
428 ret = consume_chunk(ctx->cb, data, bytes_to_consume);
430 ctx->wimlib_err_code = ret;
431 /* It doesn't matter what error code is returned here, as long
432 * as it isn't ERROR_SUCCESS. */
433 return ERROR_READ_FAULT;
435 ctx->bytes_remaining -= bytes_to_consume;
436 return ERROR_SUCCESS;
440 read_win32_encrypted_file_prefix(const wchar_t *path, bool is_dir, u64 size,
441 const struct consume_chunk_callback *cb)
443 struct win32_encrypted_read_ctx export_ctx;
450 flags |= CREATE_FOR_DIR;
453 export_ctx.wimlib_err_code = 0;
454 export_ctx.bytes_remaining = size;
456 err = OpenEncryptedFileRaw(path, flags, &file_ctx);
457 if (err != ERROR_SUCCESS) {
459 L"Failed to open encrypted file \"%ls\" for raw read",
461 return WIMLIB_ERR_OPEN;
463 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
464 &export_ctx, file_ctx);
465 if (err != ERROR_SUCCESS) {
466 ret = export_ctx.wimlib_err_code;
469 L"Failed to read encrypted file \"%ls\"",
471 ret = WIMLIB_ERR_READ;
473 } else if (export_ctx.bytes_remaining != 0) {
474 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
475 "encrypted file \"%ls\"",
476 size - export_ctx.bytes_remaining, size,
478 ret = WIMLIB_ERR_READ;
482 CloseEncryptedFileRaw(file_ctx);
486 /* Read the first @size bytes from the file, or named data stream of a file,
487 * described by @blob. */
489 read_windows_file_prefix(const struct blob_descriptor *blob, u64 size,
490 const struct consume_chunk_callback *cb)
492 const struct windows_file *file = blob->windows_file;
494 if (unlikely(file->is_encrypted)) {
495 bool is_dir = (blob->file_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY);
496 return read_win32_encrypted_file_prefix(file->path, is_dir, size, cb);
499 return read_winnt_stream_prefix(file, size, cb);
503 * Load the short name of a file into a WIM dentry.
505 static noinline_for_stack NTSTATUS
506 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
508 /* It's not any harder to just make the NtQueryInformationFile() system
509 * call ourselves, and it saves a dumb call to FindFirstFile() which of
510 * course has to create its own handle. */
512 IO_STATUS_BLOCK iosb;
513 u8 buf[128] _aligned_attribute(8);
514 const FILE_NAME_INFORMATION *info;
516 status = NtQueryInformationFile(h, &iosb, buf, sizeof(buf),
517 FileAlternateNameInformation);
518 info = (const FILE_NAME_INFORMATION *)buf;
519 if (NT_SUCCESS(status) && info->FileNameLength != 0) {
520 dentry->d_short_name = utf16le_dupz(info->FileName,
521 info->FileNameLength);
522 if (!dentry->d_short_name)
523 return STATUS_NO_MEMORY;
524 dentry->d_short_name_nbytes = info->FileNameLength;
530 * Load the security descriptor of a file into the corresponding inode and the
531 * WIM image's security descriptor set.
533 static noinline_for_stack int
534 winnt_load_security_descriptor(HANDLE h, struct wim_inode *inode,
535 struct winnt_scan_ctx *ctx)
537 SECURITY_INFORMATION requestedInformation;
538 u8 _buf[4096] _aligned_attribute(8);
545 * LABEL_SECURITY_INFORMATION is needed on Windows Vista and 7 because
546 * Microsoft decided to add mandatory integrity labels to the SACL but
547 * not have them returned by SACL_SECURITY_INFORMATION.
549 * BACKUP_SECURITY_INFORMATION is needed on Windows 8 because Microsoft
550 * decided to add even more stuff to the SACL and still not have it
551 * returned by SACL_SECURITY_INFORMATION; but they did remember that
552 * backup applications exist and simply want to read the stupid thing
553 * once and for all, so they added a flag to read the entire security
556 * Older versions of Windows tolerate these new flags being passed in.
558 requestedInformation = OWNER_SECURITY_INFORMATION |
559 GROUP_SECURITY_INFORMATION |
560 DACL_SECURITY_INFORMATION |
561 SACL_SECURITY_INFORMATION |
562 LABEL_SECURITY_INFORMATION |
563 BACKUP_SECURITY_INFORMATION;
566 bufsize = sizeof(_buf);
569 * We need the file's security descriptor in
570 * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
571 * opened with as many relevant permissions as possible. At this point,
572 * on Windows there are a number of options for reading a file's
573 * security descriptor:
575 * GetFileSecurity(): This takes in a path and returns the
576 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle,
577 * not ours, and the handle created internally doesn't specify
578 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied
579 * errors on some files and directories, even when running as the
582 * GetSecurityInfo(): This takes in a handle and returns the security
583 * descriptor split into a bunch of different parts. This should work,
584 * but it's dumb because we have to put the security descriptor back
587 * BackupRead(): This can read the security descriptor, but this is a
588 * difficult-to-use API, probably only works as the Administrator, and
589 * the format of the returned data is not well documented.
591 * NtQuerySecurityObject(): This is exactly what we need, as it takes
592 * in a handle and returns the security descriptor in
593 * SECURITY_DESCRIPTOR_RELATIVE format. Only problem is that it's a
594 * ntdll function and therefore not officially part of the Win32 API.
597 while (!NT_SUCCESS(status = NtQuerySecurityObject(h,
598 requestedInformation,
599 (PSECURITY_DESCRIPTOR)buf,
604 case STATUS_BUFFER_TOO_SMALL:
605 wimlib_assert(buf == _buf);
606 buf = MALLOC(len_needed);
608 status = STATUS_NO_MEMORY;
611 bufsize = len_needed;
613 case STATUS_PRIVILEGE_NOT_HELD:
614 case STATUS_ACCESS_DENIED:
615 if (ctx->params->add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
617 /* Permission denied in STRICT_ACLS mode, or
621 if (requestedInformation & SACL_SECURITY_INFORMATION) {
622 /* Try again without the SACL. */
623 ctx->num_get_sacl_priv_notheld++;
624 requestedInformation &= ~(SACL_SECURITY_INFORMATION |
625 LABEL_SECURITY_INFORMATION |
626 BACKUP_SECURITY_INFORMATION);
629 /* Fake success (useful when capturing as
630 * non-Administrator). */
631 ctx->num_get_sd_access_denied++;
632 status = STATUS_SUCCESS;
637 /* We can get a length of 0 with Samba. Assume that means "no security
642 /* Add the security descriptor to the WIM image, and save its ID in
643 * the file's inode. */
644 inode->i_security_id = sd_set_add_sd(ctx->params->sd_set, buf, len_needed);
645 if (unlikely(inode->i_security_id < 0))
646 status = STATUS_NO_MEMORY;
648 if (unlikely(buf != _buf))
650 if (!NT_SUCCESS(status)) {
651 winnt_error(status, L"\"%ls\": Can't read security descriptor",
652 printable_path(ctx));
653 return WIMLIB_ERR_STAT;
658 /* Load a file's object ID into the corresponding WIM inode. */
659 static noinline_for_stack int
660 winnt_load_object_id(HANDLE h, struct wim_inode *inode,
661 struct winnt_scan_ctx *ctx)
663 FILE_OBJECTID_BUFFER buffer;
667 if (!(ctx->vol_flags & FILE_SUPPORTS_OBJECT_IDS))
670 status = winnt_fsctl(h, FSCTL_GET_OBJECT_ID, NULL, 0,
671 &buffer, sizeof(buffer), &len);
673 if (status == STATUS_OBJECTID_NOT_FOUND) /* No object ID */
676 if (status == STATUS_INVALID_DEVICE_REQUEST) {
677 /* The filesystem claimed to support object IDs, but we can't
678 * actually read them. This happens with Samba. */
679 ctx->vol_flags &= ~FILE_SUPPORTS_OBJECT_IDS;
683 if (!NT_SUCCESS(status)) {
684 winnt_error(status, L"\"%ls\": Can't read object ID",
685 printable_path(ctx));
686 return WIMLIB_ERR_STAT;
689 if (len == 0) /* No object ID (for directories) */
692 if (!inode_set_object_id(inode, &buffer, len))
693 return WIMLIB_ERR_NOMEM;
699 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
701 const wchar_t *relative_path,
702 size_t relative_path_nchars,
703 const wchar_t *filename,
704 struct winnt_scan_ctx *ctx);
707 winnt_recurse_directory(HANDLE h,
708 struct wim_dentry *parent,
709 struct winnt_scan_ctx *ctx)
712 const size_t bufsize = 8192;
713 IO_STATUS_BLOCK iosb;
717 buf = MALLOC(bufsize);
719 return WIMLIB_ERR_NOMEM;
721 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
722 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
724 while (NT_SUCCESS(status = NtQueryDirectoryFile(h, NULL, NULL, NULL,
726 FileNamesInformation,
727 FALSE, NULL, FALSE)))
729 const FILE_NAMES_INFORMATION *info = buf;
731 if (!should_ignore_filename(info->FileName,
732 info->FileNameLength / 2))
734 struct wim_dentry *child;
735 size_t orig_path_nchars;
736 const wchar_t *filename;
738 ret = WIMLIB_ERR_NOMEM;
739 filename = pathbuf_append_name(ctx->params,
741 info->FileNameLength / 2,
746 ret = winnt_build_dentry_tree_recursive(
750 info->FileNameLength / 2,
754 pathbuf_truncate(ctx->params, orig_path_nchars);
758 attach_scanned_tree(parent, child,
759 ctx->params->blob_table);
761 if (info->NextEntryOffset == 0)
763 info = (const FILE_NAMES_INFORMATION *)
764 ((const u8 *)info + info->NextEntryOffset);
768 if (unlikely(status != STATUS_NO_MORE_FILES)) {
769 winnt_error(status, L"\"%ls\": Can't read directory",
770 printable_path(ctx));
771 ret = WIMLIB_ERR_READ;
778 /* Reparse point fixup status code */
779 #define RP_FIXED (-1)
782 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
785 IO_STATUS_BLOCK iosb;
786 FILE_INTERNAL_INFORMATION int_info;
787 FILE_FS_VOLUME_INFORMATION vol_info;
789 status = NtQueryInformationFile(h, &iosb, &int_info, sizeof(int_info),
790 FileInternalInformation);
791 if (!NT_SUCCESS(status))
794 if (int_info.IndexNumber.QuadPart != ino)
797 status = NtQueryVolumeInformationFile(h, &iosb,
798 &vol_info, sizeof(vol_info),
799 FileFsVolumeInformation);
800 if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
803 if (iosb.Information <
804 offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
805 sizeof(vol_info.VolumeSerialNumber))
808 return (vol_info.VolumeSerialNumber == dev);
812 * This is the Windows equivalent of unix_relativize_link_target(); see there
813 * for general details. This version works with an "absolute" Windows link
814 * target, specified from the root of the Windows kernel object namespace. Note
815 * that we have to open directories with a trailing slash when present because
816 * \??\E: opens the E: device itself and not the filesystem root directory.
818 static const wchar_t *
819 winnt_relativize_link_target(const wchar_t *target, size_t target_nbytes,
823 OBJECT_ATTRIBUTES attr;
824 IO_STATUS_BLOCK iosb;
826 const wchar_t *target_end;
829 target_end = target + (target_nbytes / sizeof(wchar_t));
832 if (target_end == target)
835 /* No leading slash??? */
836 if (target[0] != L'\\')
840 if ((target_end - target) >= 2 &&
841 target[0] == L'\\' && target[1] == L'\\')
844 attr.Length = sizeof(attr);
845 attr.RootDirectory = NULL;
846 attr.ObjectName = &name;
848 attr.SecurityDescriptor = NULL;
849 attr.SecurityQualityOfService = NULL;
851 name.Buffer = (wchar_t *)target;
856 const wchar_t *orig_p = p;
858 /* Skip non-backslashes */
859 while (p != target_end && *p != L'\\')
862 /* Skip backslashes */
863 while (p != target_end && *p == L'\\')
866 /* Append path component */
867 name.Length += (p - orig_p) * sizeof(wchar_t);
868 name.MaximumLength = name.Length;
870 /* Try opening the file */
871 status = NtOpenFile(&h,
872 FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
875 FILE_SHARE_VALID_FLAGS,
876 FILE_OPEN_FOR_BACKUP_INTENT);
878 if (NT_SUCCESS(status)) {
879 /* Reset root directory */
880 if (attr.RootDirectory)
881 NtClose(attr.RootDirectory);
882 attr.RootDirectory = h;
883 name.Buffer = (wchar_t *)p;
886 if (file_has_ino_and_dev(h, ino, dev))
887 goto out_close_root_dir;
889 } while (p != target_end);
894 if (attr.RootDirectory)
895 NtClose(attr.RootDirectory);
896 while (p > target && *(p - 1) == L'\\')
902 winnt_rpfix_progress(struct scan_params *params,
903 const struct link_reparse_point *link, int scan_status)
905 size_t print_name_nchars = link->print_name_nbytes / sizeof(wchar_t);
906 wchar_t print_name0[print_name_nchars + 1];
908 wmemcpy(print_name0, link->print_name, print_name_nchars);
909 print_name0[print_name_nchars] = L'\0';
911 params->progress.scan.symlink_target = print_name0;
912 return do_scan_progress(params, scan_status, NULL);
916 winnt_try_rpfix(struct reparse_buffer_disk *rpbuf, u16 *rpbuflen_p,
917 struct scan_params *params)
919 struct link_reparse_point link;
920 const wchar_t *rel_target;
923 if (parse_link_reparse_point(rpbuf, *rpbuflen_p, &link)) {
924 /* Couldn't understand the reparse data; don't do the fixup. */
929 * Don't do reparse point fixups on relative symbolic links.
931 * On Windows, a relative symbolic link is supposed to be identifiable
932 * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
933 * SYMBOLIC_LINK_RELATIVE. We will use this information, although this
934 * may not always do what the user expects, since drive-relative
935 * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
936 * set, in addition to truly relative symbolic links such as "Users" or
937 * "Users\Public". However, WIMGAPI (as of Windows 8.1) has this same
940 * Otherwise, as far as I can tell, the targets of symbolic links that
941 * are NOT relative, as well as junctions (note: a mountpoint is the
942 * sames thing as a junction), must be NT namespace paths, for example:
944 * - \??\e:\Users\Public
945 * - \DosDevices\e:\Users\Public
946 * - \Device\HardDiskVolume4\Users\Public
947 * - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
948 * - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
950 if (link_is_relative_symlink(&link))
953 rel_target = winnt_relativize_link_target(link.substitute_name,
954 link.substitute_name_nbytes,
955 params->capture_root_ino,
956 params->capture_root_dev);
958 if (rel_target == link.substitute_name) {
959 /* Target points outside of the tree being captured or had an
960 * unrecognized path format. Don't adjust it. */
961 return winnt_rpfix_progress(params, &link,
962 WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK);
965 /* We have an absolute target pointing within the directory being
966 * captured. @rel_target is the suffix of the link target that is the
967 * part relative to the directory being captured.
969 * We will cut off the prefix before this part (which is the path to the
970 * directory being captured) and add a dummy prefix. Since the process
971 * will need to be reversed when applying the image, it doesn't matter
972 * what exactly the prefix is, as long as it looks like an absolute
975 static const wchar_t prefix[6] = L"\\??\\X:";
976 static const size_t num_unprintable_chars = 4;
978 size_t rel_target_nbytes =
979 link.substitute_name_nbytes - ((const u8 *)rel_target -
980 (const u8 *)link.substitute_name);
982 wchar_t tmp[(sizeof(prefix) + rel_target_nbytes) / sizeof(wchar_t)];
984 memcpy(tmp, prefix, sizeof(prefix));
985 memcpy(tmp + ARRAY_LEN(prefix), rel_target, rel_target_nbytes);
987 link.substitute_name = tmp;
988 link.substitute_name_nbytes = sizeof(tmp);
990 link.print_name = link.substitute_name + num_unprintable_chars;
991 link.print_name_nbytes = link.substitute_name_nbytes -
992 (num_unprintable_chars * sizeof(wchar_t));
994 if (make_link_reparse_point(&link, rpbuf, rpbuflen_p))
997 ret = winnt_rpfix_progress(params, &link,
998 WIMLIB_SCAN_DENTRY_FIXED_SYMLINK);
1004 /* Load the reparse data of a file into the corresponding WIM inode. If the
1005 * reparse point is a symbolic link or junction with an absolute target and
1006 * RPFIX mode is enabled, then also rewrite its target to be relative to the
1008 static noinline_for_stack int
1009 winnt_load_reparse_data(HANDLE h, struct wim_inode *inode,
1010 struct winnt_scan_ctx *ctx)
1012 struct reparse_buffer_disk rpbuf;
1018 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1019 /* See comment above assign_stream_types_encrypted() */
1020 WARNING("Ignoring reparse data of encrypted file \"%ls\"",
1021 printable_path(ctx));
1025 status = winnt_fsctl(h, FSCTL_GET_REPARSE_POINT,
1026 NULL, 0, &rpbuf, sizeof(rpbuf), &len);
1027 if (!NT_SUCCESS(status)) {
1028 winnt_error(status, L"\"%ls\": Can't get reparse point",
1029 printable_path(ctx));
1030 return WIMLIB_ERR_READLINK;
1035 if (unlikely(rpbuflen < REPARSE_DATA_OFFSET)) {
1036 ERROR("\"%ls\": reparse point buffer is too short",
1037 printable_path(ctx));
1038 return WIMLIB_ERR_INVALID_REPARSE_DATA;
1041 if (le32_to_cpu(rpbuf.rptag) == WIM_IO_REPARSE_TAG_DEDUP) {
1043 * Windows treats Data Deduplication reparse points specially.
1044 * Reads from the unnamed data stream actually return the
1045 * redirected file contents, even with FILE_OPEN_REPARSE_POINT.
1046 * Deduplicated files also cannot be properly restored without
1047 * also restoring the "System Volume Information" directory,
1048 * which wimlib excludes by default. Therefore, the logical
1049 * behavior for us seems to be to ignore the reparse point and
1050 * treat the file as a normal file.
1052 inode->i_attributes &= ~FILE_ATTRIBUTE_REPARSE_POINT;
1056 if (ctx->params->add_flags & WIMLIB_ADD_FLAG_RPFIX) {
1057 ret = winnt_try_rpfix(&rpbuf, &rpbuflen, ctx->params);
1058 if (ret == RP_FIXED)
1059 inode->i_rp_flags &= ~WIM_RP_FLAG_NOT_FIXED;
1064 inode->i_reparse_tag = le32_to_cpu(rpbuf.rptag);
1065 inode->i_rp_reserved = le16_to_cpu(rpbuf.rpreserved);
1067 if (!inode_add_stream_with_data(inode,
1068 STREAM_TYPE_REPARSE_POINT,
1071 rpbuflen - REPARSE_DATA_OFFSET,
1072 ctx->params->blob_table))
1073 return WIMLIB_ERR_NOMEM;
1079 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
1082 *(u64*)_size_ret += len;
1083 return ERROR_SUCCESS;
1087 win32_get_encrypted_file_size(const wchar_t *path, bool is_dir, u64 *size_ret)
1095 flags |= CREATE_FOR_DIR;
1097 err = OpenEncryptedFileRaw(path, flags, &file_ctx);
1098 if (err != ERROR_SUCCESS) {
1100 L"Failed to open encrypted file \"%ls\" for raw read",
1102 return WIMLIB_ERR_OPEN;
1105 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
1106 size_ret, file_ctx);
1107 if (err != ERROR_SUCCESS) {
1109 L"Failed to read raw encrypted data from \"%ls\"",
1111 ret = WIMLIB_ERR_READ;
1115 CloseEncryptedFileRaw(file_ctx);
1120 winnt_scan_efsrpc_raw_data(struct wim_inode *inode,
1121 struct winnt_scan_ctx *ctx)
1123 wchar_t *path = ctx->params->cur_path;
1124 size_t path_nchars = ctx->params->cur_path_nchars;
1125 const bool is_dir = (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY);
1126 struct windows_file *windows_file;
1130 /* OpenEncryptedFileRaw() expects a Win32 name. */
1131 wimlib_assert(!wmemcmp(path, L"\\??\\", 4));
1134 ret = win32_get_encrypted_file_size(path, is_dir, &size);
1138 /* Empty EFSRPC data does not make sense */
1139 wimlib_assert(size != 0);
1141 windows_file = alloc_windows_file(path, path_nchars, NULL, 0,
1142 ctx->snapshot, true);
1143 ret = add_stream(inode, windows_file, size, STREAM_TYPE_EFSRPC_RAW_DATA,
1144 NO_STREAM_NAME, ctx->params->unhashed_blobs);
1151 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1152 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
1154 const wchar_t *sep, *type, *end;
1156 /* The stream name should be returned as :NAME:TYPE */
1157 if (raw_stream_name_nchars < 1)
1159 if (raw_stream_name[0] != L':')
1163 raw_stream_name_nchars--;
1165 end = raw_stream_name + raw_stream_name_nchars;
1167 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
1172 if (end - type != 5)
1175 if (wmemcmp(type, L"$DATA", 5))
1178 *stream_name_ret = raw_stream_name;
1179 *stream_name_nchars_ret = sep - raw_stream_name;
1184 winnt_scan_data_stream(wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1185 u64 stream_size, struct wim_inode *inode,
1186 struct winnt_scan_ctx *ctx)
1188 wchar_t *stream_name;
1189 size_t stream_name_nchars;
1190 struct windows_file *windows_file;
1192 /* Given the raw stream name (which is something like
1193 * :streamname:$DATA), extract just the stream name part (streamname).
1194 * Ignore any non-$DATA streams. */
1195 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
1196 (const wchar_t **)&stream_name,
1197 &stream_name_nchars))
1200 stream_name[stream_name_nchars] = L'\0';
1202 windows_file = alloc_windows_file(ctx->params->cur_path,
1203 ctx->params->cur_path_nchars,
1204 stream_name, stream_name_nchars,
1205 ctx->snapshot, false);
1206 return add_stream(inode, windows_file, stream_size, STREAM_TYPE_DATA,
1207 stream_name, ctx->params->unhashed_blobs);
1211 * Load information about the data streams of an open file into a WIM inode.
1213 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
1214 * and FindNextStream(). This is done for two reasons:
1216 * - FindFirstStream() opens its own handle to the file or directory and
1217 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
1218 * causing access denied errors on certain files (even when running as the
1220 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
1221 * and later, whereas the stream support in NtQueryInformationFile() was
1222 * already present in Windows XP.
1224 static noinline_for_stack int
1225 winnt_scan_data_streams(HANDLE h, struct wim_inode *inode, u64 file_size,
1226 struct winnt_scan_ctx *ctx)
1229 u8 _buf[4096] _aligned_attribute(8);
1232 IO_STATUS_BLOCK iosb;
1234 FILE_STREAM_INFORMATION *info;
1237 bufsize = sizeof(_buf);
1239 if (!(ctx->vol_flags & FILE_NAMED_STREAMS))
1242 /* Get a buffer containing the stream information. */
1243 while (!NT_SUCCESS(status = NtQueryInformationFile(h,
1247 FileStreamInformation)))
1251 case STATUS_BUFFER_OVERFLOW:
1257 newbuf = MALLOC(bufsize);
1259 newbuf = REALLOC(buf, bufsize);
1261 ret = WIMLIB_ERR_NOMEM;
1267 case STATUS_NOT_IMPLEMENTED:
1268 case STATUS_NOT_SUPPORTED:
1269 case STATUS_INVALID_INFO_CLASS:
1273 L"\"%ls\": Failed to query stream information",
1274 printable_path(ctx));
1275 ret = WIMLIB_ERR_READ;
1280 if (iosb.Information == 0) {
1281 /* No stream information. */
1286 /* Parse one or more stream information structures. */
1287 info = (FILE_STREAM_INFORMATION *)buf;
1289 /* Load the stream information. */
1290 ret = winnt_scan_data_stream(info->StreamName,
1291 info->StreamNameLength / 2,
1292 info->StreamSize.QuadPart,
1297 if (info->NextEntryOffset == 0) {
1298 /* No more stream information. */
1301 /* Advance to next stream information. */
1302 info = (FILE_STREAM_INFORMATION *)
1303 ((u8 *)info + info->NextEntryOffset);
1309 /* The volume does not support named streams. Only capture the unnamed
1311 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1312 FILE_ATTRIBUTE_REPARSE_POINT))
1319 wchar_t stream_name[] = L"::$DATA";
1320 ret = winnt_scan_data_stream(stream_name, 7, file_size,
1324 /* Free buffer if allocated on heap. */
1325 if (unlikely(buf != _buf))
1331 extract_starting_lcn(const RETRIEVAL_POINTERS_BUFFER *extents)
1333 if (extents->ExtentCount < 1)
1336 return extents->Extents[0].Lcn.QuadPart;
1339 static noinline_for_stack u64
1340 get_sort_key(HANDLE h)
1342 STARTING_VCN_INPUT_BUFFER in = { .StartingVcn.QuadPart = 0 };
1343 RETRIEVAL_POINTERS_BUFFER out;
1345 if (!NT_SUCCESS(winnt_fsctl(h, FSCTL_GET_RETRIEVAL_POINTERS,
1346 &in, sizeof(in), &out, sizeof(out), NULL)))
1349 return extract_starting_lcn(&out);
1353 set_sort_key(struct wim_inode *inode, u64 sort_key)
1355 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1356 struct wim_inode_stream *strm = &inode->i_streams[i];
1357 struct blob_descriptor *blob = stream_blob_resolved(strm);
1358 if (blob && blob->blob_location == BLOB_IN_WINDOWS_FILE)
1359 blob->windows_file->sort_key = sort_key;
1364 should_try_to_use_wimboot_hash(const struct wim_inode *inode,
1365 const struct winnt_scan_ctx *ctx)
1367 /* Directories and encrypted files aren't valid for external backing. */
1368 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1369 FILE_ATTRIBUTE_ENCRYPTED))
1372 /* If the file is a reparse point, then try the hash fixup if it's a WOF
1373 * reparse point and we're in WIMBOOT mode. Otherwise, try the hash
1374 * fixup if WOF may be attached. */
1375 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1376 return (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_WOF) &&
1377 (ctx->params->add_flags & WIMLIB_ADD_FLAG_WIMBOOT);
1378 return !ctx->wof_not_attached;
1382 * This function implements an optimization for capturing files from a
1383 * filesystem with a backing WIM(s). If a file is WIM-backed, then we can
1384 * retrieve the SHA-1 message digest of its original contents from its reparse
1385 * point. This may eliminate the need to read the file's data and/or allow the
1386 * file's data to be immediately deduplicated with existing data in the WIM.
1388 * If WOF is attached, then this function is merely an optimization, but
1389 * potentially a very effective one. If WOF is detached, then this function
1390 * really causes WIM-backed files to be, effectively, automatically
1391 * "dereferenced" when possible; the unnamed data stream is updated to reference
1392 * the original contents and the reparse point is removed.
1394 * This function returns 0 if the fixup succeeded or was intentionally not
1395 * executed. Otherwise it returns an error code.
1397 static noinline_for_stack int
1398 try_to_use_wimboot_hash(HANDLE h, struct wim_inode *inode,
1399 struct winnt_scan_ctx *ctx)
1401 struct blob_table *blob_table = ctx->params->blob_table;
1402 struct wim_inode_stream *reparse_strm = NULL;
1403 struct wim_inode_stream *strm;
1404 struct blob_descriptor *blob;
1405 u8 hash[SHA1_HASH_SIZE];
1408 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1409 struct reparse_buffer_disk rpbuf;
1411 struct wof_external_info wof_info;
1412 struct wim_provider_rpdata wim_info;
1413 } *rpdata = (void *)rpbuf.rpdata;
1414 struct blob_descriptor *reparse_blob;
1416 /* The file has a WOF reparse point, so WOF must be detached.
1417 * We can read the reparse point directly. */
1418 ctx->wof_not_attached = true;
1419 reparse_strm = inode_get_unnamed_stream(inode, STREAM_TYPE_REPARSE_POINT);
1420 reparse_blob = stream_blob_resolved(reparse_strm);
1422 if (!reparse_blob || reparse_blob->size < sizeof(*rpdata))
1423 return 0; /* Not a WIM-backed file */
1425 ret = read_blob_into_buf(reparse_blob, rpdata);
1429 if (rpdata->wof_info.version != WOF_CURRENT_VERSION ||
1430 rpdata->wof_info.provider != WOF_PROVIDER_WIM ||
1431 rpdata->wim_info.version != 2)
1432 return 0; /* Not a WIM-backed file */
1434 /* Okay, this is a WIM backed file. Get its SHA-1 hash. */
1435 copy_hash(hash, rpdata->wim_info.unnamed_data_stream_hash);
1438 struct wof_external_info wof_info;
1439 struct wim_provider_external_info wim_info;
1443 /* WOF may be attached. Try reading this file's external
1445 status = winnt_fsctl(h, FSCTL_GET_EXTERNAL_BACKING,
1446 NULL, 0, &out, sizeof(out), NULL);
1448 /* Is WOF not attached? */
1449 if (status == STATUS_INVALID_DEVICE_REQUEST ||
1450 status == STATUS_NOT_SUPPORTED) {
1451 ctx->wof_not_attached = true;
1455 /* Is this file not externally backed? */
1456 if (status == STATUS_OBJECT_NOT_EXTERNALLY_BACKED)
1459 /* Does this file have an unknown type of external backing that
1460 * needed a larger information buffer? */
1461 if (status == STATUS_BUFFER_TOO_SMALL)
1464 /* Was there some other failure? */
1465 if (status != STATUS_SUCCESS) {
1467 L"\"%ls\": FSCTL_GET_EXTERNAL_BACKING failed",
1468 printable_path(ctx));
1469 return WIMLIB_ERR_STAT;
1472 /* Is this file backed by a WIM? */
1473 if (out.wof_info.version != WOF_CURRENT_VERSION ||
1474 out.wof_info.provider != WOF_PROVIDER_WIM ||
1475 out.wim_info.version != WIM_PROVIDER_CURRENT_VERSION)
1478 /* Okay, this is a WIM backed file. Get its SHA-1 hash. */
1479 copy_hash(hash, out.wim_info.unnamed_data_stream_hash);
1482 /* If the file's unnamed data stream is nonempty, then fill in its hash
1483 * and deduplicate it if possible.
1485 * With WOF detached, we require that the blob *must* de-duplicable for
1486 * any action can be taken, since without WOF we can't fall back to
1487 * getting the "dereferenced" data by reading the stream (the real
1488 * stream is sparse and contains all zeroes). */
1489 strm = inode_get_unnamed_data_stream(inode);
1490 if (strm && (blob = stream_blob_resolved(strm))) {
1491 struct blob_descriptor **back_ptr;
1493 if (reparse_strm && !lookup_blob(blob_table, hash))
1495 back_ptr = retrieve_pointer_to_unhashed_blob(blob);
1496 copy_hash(blob->hash, hash);
1497 if (after_blob_hashed(blob, back_ptr, blob_table) != blob)
1498 free_blob_descriptor(blob);
1501 /* Remove the reparse point, if present. */
1503 inode_remove_stream(inode, reparse_strm, blob_table);
1504 inode->i_attributes &= ~(FILE_ATTRIBUTE_REPARSE_POINT |
1505 FILE_ATTRIBUTE_SPARSE_FILE);
1506 if (inode->i_attributes == 0)
1507 inode->i_attributes = FILE_ATTRIBUTE_NORMAL;
1517 u64 last_write_time;
1518 u64 last_access_time;
1523 static noinline_for_stack NTSTATUS
1524 get_file_info(HANDLE h, struct file_info *info)
1526 IO_STATUS_BLOCK iosb;
1528 FILE_ALL_INFORMATION all_info;
1530 status = NtQueryInformationFile(h, &iosb, &all_info, sizeof(all_info),
1531 FileAllInformation);
1533 if (unlikely(!NT_SUCCESS(status) && status != STATUS_BUFFER_OVERFLOW))
1536 info->attributes = all_info.BasicInformation.FileAttributes;
1537 info->num_links = all_info.StandardInformation.NumberOfLinks;
1538 info->creation_time = all_info.BasicInformation.CreationTime.QuadPart;
1539 info->last_write_time = all_info.BasicInformation.LastWriteTime.QuadPart;
1540 info->last_access_time = all_info.BasicInformation.LastAccessTime.QuadPart;
1541 info->ino = all_info.InternalInformation.IndexNumber.QuadPart;
1542 info->end_of_file = all_info.StandardInformation.EndOfFile.QuadPart;
1543 return STATUS_SUCCESS;
1547 get_volume_information(HANDLE h, struct winnt_scan_ctx *ctx)
1549 u8 _attr_info[sizeof(FILE_FS_ATTRIBUTE_INFORMATION) + 128] _aligned_attribute(8);
1550 FILE_FS_ATTRIBUTE_INFORMATION *attr_info = (void *)_attr_info;
1551 FILE_FS_VOLUME_INFORMATION vol_info;
1552 struct file_info file_info;
1553 IO_STATUS_BLOCK iosb;
1556 /* Get volume flags */
1557 status = NtQueryVolumeInformationFile(h, &iosb, attr_info,
1559 FileFsAttributeInformation);
1560 if (NT_SUCCESS(status)) {
1561 ctx->vol_flags = attr_info->FileSystemAttributes;
1562 ctx->is_ntfs = (attr_info->FileSystemNameLength == 4 * sizeof(wchar_t)) &&
1563 !wmemcmp(attr_info->FileSystemName, L"NTFS", 4);
1565 winnt_warning(status, L"\"%ls\": Can't get volume attributes",
1566 printable_path(ctx));
1569 /* Get volume ID. */
1570 status = NtQueryVolumeInformationFile(h, &iosb, &vol_info,
1572 FileFsVolumeInformation);
1573 if ((NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW) &&
1574 (iosb.Information >= offsetof(FILE_FS_VOLUME_INFORMATION,
1575 VolumeSerialNumber) +
1576 sizeof(vol_info.VolumeSerialNumber)))
1578 ctx->params->capture_root_dev = vol_info.VolumeSerialNumber;
1580 winnt_warning(status, L"\"%ls\": Can't get volume ID",
1581 printable_path(ctx));
1584 /* Get inode number. */
1585 status = get_file_info(h, &file_info);
1586 if (NT_SUCCESS(status)) {
1587 ctx->params->capture_root_ino = file_info.ino;
1589 winnt_warning(status, L"\"%ls\": Can't get file information",
1590 printable_path(ctx));
1595 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1597 const wchar_t *relative_path,
1598 size_t relative_path_nchars,
1599 const wchar_t *filename,
1600 struct winnt_scan_ctx *ctx)
1602 struct wim_dentry *root = NULL;
1603 struct wim_inode *inode = NULL;
1607 struct file_info file_info;
1610 ret = try_exclude(ctx->params);
1611 if (unlikely(ret < 0)) /* Excluded? */
1613 if (unlikely(ret > 0)) /* Error? */
1616 /* Open the file with permission to read metadata. Although we will
1617 * later need a handle with FILE_LIST_DIRECTORY permission (or,
1618 * equivalently, FILE_READ_DATA; they're the same numeric value) if the
1619 * file is a directory, it can significantly slow things down to request
1620 * this permission on all nondirectories. Perhaps it causes Windows to
1621 * start prefetching the file contents... */
1622 status = winnt_openat(cur_dir, relative_path, relative_path_nchars,
1623 FILE_READ_ATTRIBUTES | READ_CONTROL |
1624 ACCESS_SYSTEM_SECURITY,
1626 if (unlikely(!NT_SUCCESS(status))) {
1627 if (status == STATUS_DELETE_PENDING) {
1628 WARNING("\"%ls\": Deletion pending; skipping file",
1629 printable_path(ctx));
1633 if (status == STATUS_SHARING_VIOLATION) {
1634 ERROR("Can't open \"%ls\":\n"
1635 " File is in use by another process! "
1636 "Consider using snapshot (VSS) mode.",
1637 printable_path(ctx));
1638 ret = WIMLIB_ERR_OPEN;
1641 winnt_error(status, L"\"%ls\": Can't open file",
1642 printable_path(ctx));
1643 if (status == STATUS_FVE_LOCKED_VOLUME)
1644 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1646 ret = WIMLIB_ERR_OPEN;
1650 /* Get information about the file. */
1651 status = get_file_info(h, &file_info);
1652 if (!NT_SUCCESS(status)) {
1653 winnt_error(status, L"\"%ls\": Can't get file information",
1654 printable_path(ctx));
1655 ret = WIMLIB_ERR_STAT;
1659 /* Create a WIM dentry with an associated inode, which may be shared.
1661 * However, we need to explicitly check for directories and files with
1662 * only 1 link and refuse to hard link them. This is because Windows
1663 * has a bug where it can return duplicate File IDs for files and
1664 * directories on the FAT filesystem.
1666 * Since we don't follow mount points on Windows, we don't need to query
1667 * the volume ID per-file. Just once, for the root, is enough. But we
1668 * can't simply pass 0, because then there could be inode collisions
1669 * among multiple calls to win32_build_dentry_tree() that are scanning
1670 * files on different volumes. */
1671 ret = inode_table_new_dentry(ctx->params->inode_table,
1674 ctx->params->capture_root_dev,
1675 (file_info.num_links <= 1),
1680 /* Get the short (DOS) name of the file. */
1681 status = winnt_get_short_name(h, root);
1683 /* If we can't read the short filename for any reason other than
1684 * out-of-memory, just ignore the error and assume the file has no short
1685 * name. This shouldn't be an issue, since the short names are
1686 * essentially obsolete anyway. */
1687 if (unlikely(status == STATUS_NO_MEMORY)) {
1688 ret = WIMLIB_ERR_NOMEM;
1692 inode = root->d_inode;
1694 if (inode->i_nlink > 1) {
1695 /* Shared inode (hard link); skip reading per-inode information.
1700 inode->i_attributes = file_info.attributes;
1701 inode->i_creation_time = file_info.creation_time;
1702 inode->i_last_write_time = file_info.last_write_time;
1703 inode->i_last_access_time = file_info.last_access_time;
1705 /* Get the file's security descriptor, unless we are capturing in
1706 * NO_ACLS mode or the volume does not support security descriptors. */
1707 if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1708 && (ctx->vol_flags & FILE_PERSISTENT_ACLS))
1710 ret = winnt_load_security_descriptor(h, inode, ctx);
1715 /* Get the file's object ID. */
1716 ret = winnt_load_object_id(h, inode, ctx);
1720 /* If this is a reparse point, load the reparse data. */
1721 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1722 ret = winnt_load_reparse_data(h, inode, ctx);
1727 sort_key = get_sort_key(h);
1729 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1730 /* Load information about the raw encrypted data. This is
1731 * needed for any directory or non-directory that has
1732 * FILE_ATTRIBUTE_ENCRYPTED set.
1734 * Note: since OpenEncryptedFileRaw() fails with
1735 * ERROR_SHARING_VIOLATION if there are any open handles to the
1736 * file, we have to close the file and re-open it later if
1740 ret = winnt_scan_efsrpc_raw_data(inode, ctx);
1745 * Load information about data streams (unnamed and named).
1747 * Skip this step for encrypted files, since the data from
1748 * ReadEncryptedFileRaw() already contains all data streams (and
1749 * they do in fact all get restored by WriteEncryptedFileRaw().)
1751 * Note: WIMGAPI (as of Windows 8.1) gets wrong and stores both
1752 * the EFSRPC data and the named data stream(s)...!
1754 ret = winnt_scan_data_streams(h,
1756 file_info.end_of_file,
1762 if (unlikely(should_try_to_use_wimboot_hash(inode, ctx))) {
1763 ret = try_to_use_wimboot_hash(h, inode, ctx);
1768 set_sort_key(inode, sort_key);
1770 if (inode_is_directory(inode)) {
1772 /* Directory: recurse to children. */
1774 /* Re-open the directory with FILE_LIST_DIRECTORY access. */
1779 status = winnt_openat(cur_dir, relative_path,
1780 relative_path_nchars, FILE_LIST_DIRECTORY,
1782 if (!NT_SUCCESS(status)) {
1783 winnt_error(status, L"\"%ls\": Can't open directory",
1784 printable_path(ctx));
1785 ret = WIMLIB_ERR_OPEN;
1788 ret = winnt_recurse_directory(h, root, ctx);
1795 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_OK, inode);
1797 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1801 if (unlikely(ret)) {
1802 free_dentry_tree(root, ctx->params->blob_table);
1804 ret = report_scan_error(ctx->params, ret);
1811 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_ctx *ctx)
1813 if (likely(ctx->num_get_sacl_priv_notheld == 0 &&
1814 ctx->num_get_sd_access_denied == 0))
1817 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1818 if (ctx->num_get_sacl_priv_notheld != 0) {
1819 WARNING("- Could not capture SACL (System Access Control List)\n"
1820 " on %lu files or directories.",
1821 ctx->num_get_sacl_priv_notheld);
1823 if (ctx->num_get_sd_access_denied != 0) {
1824 WARNING("- Could not capture security descriptor at all\n"
1825 " on %lu files or directories.",
1826 ctx->num_get_sd_access_denied);
1828 WARNING("To fully capture all security descriptors, run the program\n"
1829 " with Administrator rights.");
1832 /*----------------------------------------------------------------------------*
1833 * Fast MFT scan implementation *
1834 *----------------------------------------------------------------------------*/
1836 #define ENABLE_FAST_MFT_SCAN 1
1838 #ifdef ENABLE_FAST_MFT_SCAN
1841 u64 StartingCluster;
1846 u64 StartingFileReferenceNumber;
1847 u64 EndingFileReferenceNumber;
1848 } FILE_REFERENCE_RANGE;
1850 /* The FSCTL_QUERY_FILE_LAYOUT ioctl. This ioctl can be used on Windows 8 and
1851 * later to scan the MFT of an NTFS volume. */
1852 #define FSCTL_QUERY_FILE_LAYOUT CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 157, METHOD_NEITHER, FILE_ANY_ACCESS)
1854 /* The input to FSCTL_QUERY_FILE_LAYOUT */
1857 #define QUERY_FILE_LAYOUT_RESTART 0x00000001
1858 #define QUERY_FILE_LAYOUT_INCLUDE_NAMES 0x00000002
1859 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS 0x00000004
1860 #define QUERY_FILE_LAYOUT_INCLUDE_EXTENTS 0x00000008
1861 #define QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO 0x00000010
1862 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED 0x00000020
1864 #define QUERY_FILE_LAYOUT_FILTER_TYPE_NONE 0
1865 #define QUERY_FILE_LAYOUT_FILTER_TYPE_CLUSTERS 1
1866 #define QUERY_FILE_LAYOUT_FILTER_TYPE_FILEID 2
1867 #define QUERY_FILE_LAYOUT_NUM_FILTER_TYPES 3
1871 CLUSTER_RANGE ClusterRanges[1];
1872 FILE_REFERENCE_RANGE FileReferenceRanges[1];
1874 } QUERY_FILE_LAYOUT_INPUT;
1876 /* The header of the buffer returned by FSCTL_QUERY_FILE_LAYOUT */
1879 u32 FirstFileOffset;
1880 #define QUERY_FILE_LAYOUT_SINGLE_INSTANCED 0x00000001
1883 } QUERY_FILE_LAYOUT_OUTPUT;
1885 /* Inode information returned by FSCTL_QUERY_FILE_LAYOUT */
1891 u64 FileReferenceNumber;
1892 u32 FirstNameOffset;
1893 u32 FirstStreamOffset;
1894 u32 ExtraInfoOffset;
1896 } FILE_LAYOUT_ENTRY;
1898 /* Extra inode information returned by FSCTL_QUERY_FILE_LAYOUT */
1910 } FILE_LAYOUT_INFO_ENTRY;
1912 /* Filename (or dentry) information returned by FSCTL_QUERY_FILE_LAYOUT */
1915 #define FILE_LAYOUT_NAME_ENTRY_PRIMARY 0x00000001
1916 #define FILE_LAYOUT_NAME_ENTRY_DOS 0x00000002
1918 u64 ParentFileReferenceNumber;
1921 wchar_t FileName[1];
1922 } FILE_LAYOUT_NAME_ENTRY;
1924 /* Stream information returned by FSCTL_QUERY_FILE_LAYOUT */
1927 u32 NextStreamOffset;
1928 #define STREAM_LAYOUT_ENTRY_IMMOVABLE 0x00000001
1929 #define STREAM_LAYOUT_ENTRY_PINNED 0x00000002
1930 #define STREAM_LAYOUT_ENTRY_RESIDENT 0x00000004
1931 #define STREAM_LAYOUT_ENTRY_NO_CLUSTERS_ALLOCATED 0x00000008
1933 u32 ExtentInformationOffset;
1938 u32 StreamIdentifierLength;
1939 wchar_t StreamIdentifier[1];
1940 } STREAM_LAYOUT_ENTRY;
1944 #define STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS 0x00000001
1945 #define STREAM_EXTENT_ENTRY_ALL_EXTENTS 0x00000002
1948 RETRIEVAL_POINTERS_BUFFER RetrievalPointers;
1949 } ExtentInformation;
1950 } STREAM_EXTENT_ENTRY;
1952 /* Extract the MFT number part of the full inode number */
1953 #define NTFS_MFT_NO(ref) ((ref) & (((u64)1 << 48) - 1))
1955 /* Is the file the root directory of the NTFS volume? The root directory always
1956 * occupies MFT record 5. */
1957 #define NTFS_IS_ROOT_FILE(ino) (NTFS_MFT_NO(ino) == 5)
1959 /* Is the file a special NTFS file, other than the root directory? The special
1960 * files are the first 16 records in the MFT. */
1961 #define NTFS_IS_SPECIAL_FILE(ino) \
1962 (NTFS_MFT_NO(ino) <= 15 && !NTFS_IS_ROOT_FILE(ino))
1964 /* Intermediate inode structure. This is used to temporarily save information
1965 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_inode'. */
1967 struct avl_tree_node index_node;
1970 u64 last_access_time;
1971 u64 last_write_time;
1976 u32 num_streams : 31;
1977 u32 have_object_id : 1;
1978 u32 first_stream_offset;
1979 struct ntfs_dentry *first_child;
1980 wchar_t short_name[13];
1983 /* Intermediate dentry structure. This is used to temporarily save information
1984 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_dentry'. */
1985 struct ntfs_dentry {
1986 u32 offset_from_inode : 31;
1989 /* Note: build_children_lists() replaces 'parent_ino' with
1992 struct ntfs_dentry *next_child;
1997 /* Intermediate stream structure. This is used to temporarily save information
1998 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct
1999 * wim_inode_stream'. */
2000 struct ntfs_stream {
2005 /* Map of all known NTFS inodes, keyed by inode number */
2006 struct ntfs_inode_map {
2007 struct avl_tree_node *root;
2010 #define NTFS_INODE(node) \
2011 avl_tree_entry((node), struct ntfs_inode, index_node)
2013 #define SKIP_ALIGNED(p, size) ((void *)(p) + ALIGN((size), 8))
2015 /* Get a pointer to the first dentry of the inode. */
2016 #define FIRST_DENTRY(ni) SKIP_ALIGNED((ni), sizeof(struct ntfs_inode))
2018 /* Get a pointer to the first stream of the inode. */
2019 #define FIRST_STREAM(ni) ((const void *)ni + ni->first_stream_offset)
2021 /* Advance to the next dentry of the inode. */
2022 #define NEXT_DENTRY(nd) SKIP_ALIGNED((nd), sizeof(struct ntfs_dentry) + \
2023 (wcslen((nd)->name) + 1) * sizeof(wchar_t))
2025 /* Advance to the next stream of the inode. */
2026 #define NEXT_STREAM(ns) SKIP_ALIGNED((ns), sizeof(struct ntfs_stream) + \
2027 (wcslen((ns)->name) + 1) * sizeof(wchar_t))
2030 _avl_cmp_ntfs_inodes(const struct avl_tree_node *node1,
2031 const struct avl_tree_node *node2)
2033 return cmp_u64(NTFS_INODE(node1)->ino, NTFS_INODE(node2)->ino);
2036 /* Adds an NTFS inode to the map. */
2038 ntfs_inode_map_add_inode(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2040 if (avl_tree_insert(&map->root, &ni->index_node, _avl_cmp_ntfs_inodes)) {
2041 WARNING("Inode 0x%016"PRIx64" is a duplicate!", ni->ino);
2046 /* Find an ntfs_inode in the map by inode number. Returns NULL if not found. */
2047 static struct ntfs_inode *
2048 ntfs_inode_map_lookup(struct ntfs_inode_map *map, u64 ino)
2050 struct ntfs_inode tmp;
2051 struct avl_tree_node *res;
2054 res = avl_tree_lookup_node(map->root, &tmp.index_node, _avl_cmp_ntfs_inodes);
2057 return NTFS_INODE(res);
2060 /* Remove an ntfs_inode from the map and free it. */
2062 ntfs_inode_map_remove(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2064 avl_tree_remove(&map->root, &ni->index_node);
2068 /* Free all ntfs_inodes in the map. */
2070 ntfs_inode_map_destroy(struct ntfs_inode_map *map)
2072 struct ntfs_inode *ni;
2074 avl_tree_for_each_in_postorder(ni, map->root, struct ntfs_inode, index_node)
2079 file_has_streams(const FILE_LAYOUT_ENTRY *file)
2081 return (file->FirstStreamOffset != 0) &&
2082 !(file->FileAttributes & FILE_ATTRIBUTE_ENCRYPTED);
2086 is_valid_name_entry(const FILE_LAYOUT_NAME_ENTRY *name)
2088 return name->FileNameLength > 0 &&
2089 name->FileNameLength % 2 == 0 &&
2090 !wmemchr(name->FileName, L'\0', name->FileNameLength / 2) &&
2091 (!(name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) ||
2092 name->FileNameLength <= 24);
2095 /* Validate the FILE_LAYOUT_NAME_ENTRYs of the specified file and compute the
2096 * total length in bytes of the ntfs_dentry structures needed to hold the name
2099 validate_names_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2100 size_t *total_length_ret)
2102 const FILE_LAYOUT_NAME_ENTRY *name =
2103 (const void *)file + file->FirstNameOffset;
2105 size_t num_long_names = 0;
2108 if (unlikely(!is_valid_name_entry(name))) {
2109 ERROR("Invalid FILE_LAYOUT_NAME_ENTRY! "
2110 "FileReferenceNumber=0x%016"PRIx64", "
2111 "FileNameLength=%"PRIu32", "
2112 "FileName=%.*ls, Flags=0x%08"PRIx32,
2113 file->FileReferenceNumber,
2114 name->FileNameLength,
2115 (int)(name->FileNameLength / 2),
2116 name->FileName, name->Flags);
2117 return WIMLIB_ERR_UNSUPPORTED;
2119 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2121 total += ALIGN(sizeof(struct ntfs_dentry) +
2122 name->FileNameLength + sizeof(wchar_t),
2125 if (name->NextNameOffset == 0)
2127 name = (const void *)name + name->NextNameOffset;
2130 if (unlikely(num_long_names == 0)) {
2131 ERROR("Inode 0x%016"PRIx64" has no long names!",
2132 file->FileReferenceNumber);
2133 return WIMLIB_ERR_UNSUPPORTED;
2136 *total_length_ret = total;
2141 is_valid_stream_entry(const STREAM_LAYOUT_ENTRY *stream)
2143 return stream->StreamIdentifierLength % 2 == 0 &&
2144 !wmemchr(stream->StreamIdentifier , L'\0',
2145 stream->StreamIdentifierLength / 2);
2149 is_object_id_stream(const STREAM_LAYOUT_ENTRY *stream)
2151 return stream->StreamIdentifierLength == 24 &&
2152 !wmemcmp(stream->StreamIdentifier, L"::$OBJECT_ID", 12);
2156 * If the specified STREAM_LAYOUT_ENTRY represents a DATA stream as opposed to
2157 * some other type of NTFS stream such as a STANDARD_INFORMATION stream, return
2158 * true and set *stream_name_ret and *stream_name_nchars_ret to specify just the
2159 * stream name. For example, ":foo:$DATA" would become "foo" with length 3
2160 * characters. Otherwise return false.
2163 use_stream(const FILE_LAYOUT_ENTRY *file, const STREAM_LAYOUT_ENTRY *stream,
2164 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
2166 const wchar_t *stream_name;
2167 size_t stream_name_nchars;
2169 if (stream->StreamIdentifierLength == 0) {
2170 /* The unnamed data stream may be given as an empty string
2171 * rather than as "::$DATA". Handle it both ways. */
2173 stream_name_nchars = 0;
2174 } else if (!get_data_stream_name(stream->StreamIdentifier,
2175 stream->StreamIdentifierLength / 2,
2176 &stream_name, &stream_name_nchars))
2179 /* Skip the unnamed data stream for directories. */
2180 if (stream_name_nchars == 0 &&
2181 (file->FileAttributes & FILE_ATTRIBUTE_DIRECTORY))
2184 *stream_name_ret = stream_name;
2185 *stream_name_nchars_ret = stream_name_nchars;
2189 /* Validate the STREAM_LAYOUT_ENTRYs of the specified file and compute the total
2190 * length in bytes of the ntfs_stream structures needed to hold the stream
2191 * information. In addition, set *have_object_id_ret=true if the file has an
2192 * object ID stream. */
2194 validate_streams_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2195 size_t *total_length_ret,
2196 bool *have_object_id_ret)
2198 const STREAM_LAYOUT_ENTRY *stream =
2199 (const void *)file + file->FirstStreamOffset;
2202 const wchar_t *name;
2205 if (unlikely(!is_valid_stream_entry(stream))) {
2206 WARNING("Invalid STREAM_LAYOUT_ENTRY! "
2207 "FileReferenceNumber=0x%016"PRIx64", "
2208 "StreamIdentifierLength=%"PRIu32", "
2209 "StreamIdentifier=%.*ls",
2210 file->FileReferenceNumber,
2211 stream->StreamIdentifierLength,
2212 (int)(stream->StreamIdentifierLength / 2),
2213 stream->StreamIdentifier);
2214 return WIMLIB_ERR_UNSUPPORTED;
2217 if (use_stream(file, stream, &name, &name_nchars)) {
2218 total += ALIGN(sizeof(struct ntfs_stream) +
2219 (name_nchars + 1) * sizeof(wchar_t), 8);
2220 } else if (is_object_id_stream(stream)) {
2221 *have_object_id_ret = true;
2223 if (stream->NextStreamOffset == 0)
2225 stream = (const void *)stream + stream->NextStreamOffset;
2228 *total_length_ret = total;
2233 load_name_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2236 const FILE_LAYOUT_NAME_ENTRY *name =
2237 (const void *)file + file->FirstNameOffset;
2239 struct ntfs_dentry *nd = p;
2240 /* Note that a name may be just a short (DOS) name, just a long
2241 * name, or both a short name and a long name. If there is a
2242 * short name, one name should also be marked as "primary" to
2243 * indicate which long name the short name is associated with.
2244 * Also, there should be at most one short name per inode. */
2245 if (name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) {
2246 memcpy(ni->short_name,
2247 name->FileName, name->FileNameLength);
2248 ni->short_name[name->FileNameLength / 2] = L'\0';
2250 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2252 nd->offset_from_inode = (u8 *)nd - (u8 *)ni;
2253 nd->is_primary = ((name->Flags &
2254 FILE_LAYOUT_NAME_ENTRY_PRIMARY) != 0);
2255 nd->parent_ino = name->ParentFileReferenceNumber;
2256 memcpy(nd->name, name->FileName, name->FileNameLength);
2257 nd->name[name->FileNameLength / 2] = L'\0';
2258 p += ALIGN(sizeof(struct ntfs_dentry) +
2259 name->FileNameLength + sizeof(wchar_t), 8);
2261 if (name->NextNameOffset == 0)
2263 name = (const void *)name + name->NextNameOffset;
2269 load_starting_lcn(const STREAM_LAYOUT_ENTRY *stream)
2271 const STREAM_EXTENT_ENTRY *entry;
2273 if (stream->ExtentInformationOffset == 0)
2276 entry = (const void *)stream + stream->ExtentInformationOffset;
2278 if (!(entry->Flags & STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS))
2281 return extract_starting_lcn(&entry->ExtentInformation.RetrievalPointers);
2285 load_stream_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2288 const STREAM_LAYOUT_ENTRY *stream =
2289 (const void *)file + file->FirstStreamOffset;
2290 const u32 first_stream_offset = (const u8 *)p - (const u8 *)ni;
2292 struct ntfs_stream *ns = p;
2293 const wchar_t *name;
2296 if (use_stream(file, stream, &name, &name_nchars)) {
2297 ni->first_stream_offset = first_stream_offset;
2299 if (name_nchars == 0)
2300 ni->starting_lcn = load_starting_lcn(stream);
2301 ns->size = stream->EndOfFile;
2302 wmemcpy(ns->name, name, name_nchars);
2303 ns->name[name_nchars] = L'\0';
2304 p += ALIGN(sizeof(struct ntfs_stream) +
2305 (name_nchars + 1) * sizeof(wchar_t), 8);
2307 if (stream->NextStreamOffset == 0)
2309 stream = (const void *)stream + stream->NextStreamOffset;
2314 /* Process the information for a file given by FSCTL_QUERY_FILE_LAYOUT. */
2316 load_one_file(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode_map *inode_map)
2318 const FILE_LAYOUT_INFO_ENTRY *info =
2319 (const void *)file + file->ExtraInfoOffset;
2321 struct ntfs_inode *ni;
2325 bool have_object_id = false;
2327 inode_size = ALIGN(sizeof(struct ntfs_inode), 8);
2329 /* The root file should have no names, and all other files should have
2330 * at least one name. But just in case, we ignore the names of the root
2331 * file, and we ignore any non-root file with no names. */
2332 if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber)) {
2333 if (file->FirstNameOffset == 0)
2335 ret = validate_names_and_compute_total_length(file, &n);
2341 if (file_has_streams(file)) {
2342 ret = validate_streams_and_compute_total_length(file, &n,
2349 /* To save memory, we allocate the ntfs_dentry's and ntfs_stream's in
2350 * the same memory block as their ntfs_inode. */
2351 ni = CALLOC(1, inode_size);
2353 return WIMLIB_ERR_NOMEM;
2355 ni->ino = file->FileReferenceNumber;
2356 ni->attributes = info->BasicInformation.FileAttributes;
2357 ni->creation_time = info->BasicInformation.CreationTime;
2358 ni->last_write_time = info->BasicInformation.LastWriteTime;
2359 ni->last_access_time = info->BasicInformation.LastAccessTime;
2360 ni->security_id = info->SecurityId;
2361 ni->have_object_id = have_object_id;
2363 p = FIRST_DENTRY(ni);
2365 if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber))
2366 p = load_name_information(file, ni, p);
2368 if (file_has_streams(file))
2369 p = load_stream_information(file, ni, p);
2371 wimlib_assert((u8 *)p - (u8 *)ni == inode_size);
2373 ntfs_inode_map_add_inode(inode_map, ni);
2378 * Quickly find all files on an NTFS volume by using FSCTL_QUERY_FILE_LAYOUT to
2379 * scan the MFT. The NTFS volume is specified by the NT namespace path @path.
2380 * For each file, allocate an 'ntfs_inode' structure for each file and add it to
2381 * 'inode_map' keyed by inode number. Include NTFS special files such as
2382 * $Bitmap (they will be removed later).
2385 load_files_from_mft(const wchar_t *path, struct ntfs_inode_map *inode_map)
2388 QUERY_FILE_LAYOUT_INPUT in = (QUERY_FILE_LAYOUT_INPUT) {
2390 .Flags = QUERY_FILE_LAYOUT_RESTART |
2391 QUERY_FILE_LAYOUT_INCLUDE_NAMES |
2392 QUERY_FILE_LAYOUT_INCLUDE_STREAMS |
2393 QUERY_FILE_LAYOUT_INCLUDE_EXTENTS |
2394 QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO |
2395 QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED,
2396 .FilterType = QUERY_FILE_LAYOUT_FILTER_TYPE_NONE,
2398 size_t outsize = 32768;
2399 QUERY_FILE_LAYOUT_OUTPUT *out = NULL;
2403 status = winnt_open(path, wcslen(path),
2404 FILE_READ_DATA | FILE_READ_ATTRIBUTES, &h);
2405 if (!NT_SUCCESS(status)) {
2406 ret = -1; /* Silently try standard recursive scan instead */
2411 /* Allocate a buffer for the output of the ioctl. */
2412 out = MALLOC(outsize);
2414 ret = WIMLIB_ERR_NOMEM;
2418 /* Execute FSCTL_QUERY_FILE_LAYOUT until it fails. */
2419 while (NT_SUCCESS(status = winnt_fsctl(h,
2420 FSCTL_QUERY_FILE_LAYOUT,
2422 out, outsize, NULL)))
2424 const FILE_LAYOUT_ENTRY *file =
2425 (const void *)out + out->FirstFileOffset;
2427 ret = load_one_file(file, inode_map);
2430 if (file->NextFileOffset == 0)
2432 file = (const void *)file + file->NextFileOffset;
2434 in.Flags &= ~QUERY_FILE_LAYOUT_RESTART;
2437 /* Enlarge the buffer if needed. */
2438 if (status != STATUS_BUFFER_TOO_SMALL)
2444 /* Normally, FSCTL_QUERY_FILE_LAYOUT fails with STATUS_END_OF_FILE after
2445 * all files have been enumerated. */
2446 if (status != STATUS_END_OF_FILE) {
2447 if (status == STATUS_INVALID_DEVICE_REQUEST /* old OS */ ||
2448 status == STATUS_INVALID_PARAMETER /* not root directory */ ) {
2449 /* Silently try standard recursive scan instead */
2453 L"Error enumerating files on volume \"%ls\"",
2455 /* Try standard recursive scan instead */
2456 ret = WIMLIB_ERR_UNSUPPORTED;
2467 /* Build the list of child dentries for each inode in @map. This is done by
2468 * iterating through each name of each inode and adding it to its parent's
2469 * children list. Note that every name should have a parent, i.e. should belong
2470 * to some directory. The root directory does not have any names. */
2472 build_children_lists(struct ntfs_inode_map *map, struct ntfs_inode **root_ret)
2474 struct ntfs_inode *ni;
2476 avl_tree_for_each_in_order(ni, map->root, struct ntfs_inode, index_node)
2478 struct ntfs_dentry *nd;
2481 if (NTFS_IS_ROOT_FILE(ni->ino)) {
2486 n = ni->num_aliases;
2487 nd = FIRST_DENTRY(ni);
2489 struct ntfs_inode *parent;
2491 parent = ntfs_inode_map_lookup(map, nd->parent_ino);
2492 if (unlikely(!parent)) {
2493 ERROR("Parent inode 0x%016"PRIx64" of"
2494 "directory entry \"%ls\" (inode "
2495 "0x%016"PRIx64") was missing from the "
2497 nd->parent_ino, nd->name, ni->ino);
2498 return WIMLIB_ERR_UNSUPPORTED;
2500 nd->next_child = parent->first_child;
2501 parent->first_child = nd;
2504 nd = NEXT_DENTRY(nd);
2510 struct security_map_node {
2511 struct avl_tree_node index_node;
2512 u32 disk_security_id;
2513 u32 wim_security_id;
2516 /* Map from disk security IDs to WIM security IDs */
2517 struct security_map {
2518 struct avl_tree_node *root;
2521 #define SECURITY_MAP_NODE(node) \
2522 avl_tree_entry((node), struct security_map_node, index_node)
2525 _avl_cmp_security_map_nodes(const struct avl_tree_node *node1,
2526 const struct avl_tree_node *node2)
2528 return cmp_u32(SECURITY_MAP_NODE(node1)->disk_security_id,
2529 SECURITY_MAP_NODE(node2)->disk_security_id);
2533 security_map_lookup(struct security_map *map, u32 disk_security_id)
2535 struct security_map_node tmp;
2536 const struct avl_tree_node *res;
2538 if (disk_security_id == 0) /* No on-disk security ID; uncacheable */
2541 tmp.disk_security_id = disk_security_id;
2542 res = avl_tree_lookup_node(map->root, &tmp.index_node,
2543 _avl_cmp_security_map_nodes);
2546 return SECURITY_MAP_NODE(res)->wim_security_id;
2550 security_map_insert(struct security_map *map, u32 disk_security_id,
2551 u32 wim_security_id)
2553 struct security_map_node *node;
2555 if (disk_security_id == 0) /* No on-disk security ID; uncacheable */
2558 node = MALLOC(sizeof(*node));
2560 return WIMLIB_ERR_NOMEM;
2562 node->disk_security_id = disk_security_id;
2563 node->wim_security_id = wim_security_id;
2564 avl_tree_insert(&map->root, &node->index_node,
2565 _avl_cmp_security_map_nodes);
2570 security_map_destroy(struct security_map *map)
2572 struct security_map_node *node;
2574 avl_tree_for_each_in_postorder(node, map->root,
2575 struct security_map_node, index_node)
2580 * Turn our temporary NTFS structures into the final WIM structures:
2582 * ntfs_inode => wim_inode
2583 * ntfs_dentry => wim_dentry
2584 * ntfs_stream => wim_inode_stream
2586 * This also handles things such as exclusions and issuing progress messages.
2587 * It's similar to winnt_build_dentry_tree_recursive(), but this is much faster
2588 * because almost all information we need is already loaded in memory in the
2589 * ntfs_* structures. However, in some cases we still fall back to
2590 * winnt_build_dentry_tree_recursive() and/or opening the file.
2593 generate_wim_structures_recursive(struct wim_dentry **root_ret,
2594 const wchar_t *filename, bool is_primary_name,
2595 struct ntfs_inode *ni,
2596 struct winnt_scan_ctx *ctx,
2597 struct ntfs_inode_map *inode_map,
2598 struct security_map *security_map)
2601 struct wim_dentry *root = NULL;
2602 struct wim_inode *inode = NULL;
2603 const struct ntfs_stream *ns;
2605 /* Completely ignore NTFS special files. */
2606 if (NTFS_IS_SPECIAL_FILE(ni->ino))
2609 /* Fall back to a recursive scan for unhandled cases. Reparse points,
2610 * in particular, can't be properly handled here because a commonly used
2611 * filter driver (WOF) hides reparse points from regular filesystem APIs
2612 * but not from FSCTL_QUERY_FILE_LAYOUT. */
2613 if (ni->attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
2614 FILE_ATTRIBUTE_ENCRYPTED) ||
2617 ret = winnt_build_dentry_tree_recursive(&root,
2619 ctx->params->cur_path,
2620 ctx->params->cur_path_nchars,
2626 /* Test for exclusion based on path. */
2627 ret = try_exclude(ctx->params);
2628 if (unlikely(ret < 0)) /* Excluded? */
2630 if (unlikely(ret > 0)) /* Error? */
2633 /* Create the WIM dentry and possibly a new WIM inode */
2634 ret = inode_table_new_dentry(ctx->params->inode_table, filename,
2635 ni->ino, ctx->params->capture_root_dev,
2640 inode = root->d_inode;
2642 /* Set the short name if needed. */
2643 if (is_primary_name && *ni->short_name) {
2644 size_t nbytes = wcslen(ni->short_name) * sizeof(wchar_t);
2645 root->d_short_name = memdup(ni->short_name,
2646 nbytes + sizeof(wchar_t));
2647 if (!root->d_short_name) {
2648 ret = WIMLIB_ERR_NOMEM;
2651 root->d_short_name_nbytes = nbytes;
2654 if (inode->i_nlink > 1) { /* Already seen this inode? */
2659 /* The file attributes and timestamps were cached from the MFT. */
2660 inode->i_attributes = ni->attributes;
2661 inode->i_creation_time = ni->creation_time;
2662 inode->i_last_write_time = ni->last_write_time;
2663 inode->i_last_access_time = ni->last_access_time;
2665 /* Set the security descriptor if needed. */
2666 if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)) {
2667 /* Look up the WIM security ID that corresponds to the on-disk
2669 s32 wim_security_id =
2670 security_map_lookup(security_map, ni->security_id);
2671 if (likely(wim_security_id >= 0)) {
2672 /* The mapping for this security ID is already cached.*/
2673 inode->i_security_id = wim_security_id;
2678 /* Create a mapping for this security ID and insert it
2679 * into the security map. */
2681 status = winnt_open(ctx->params->cur_path,
2682 ctx->params->cur_path_nchars,
2684 ACCESS_SYSTEM_SECURITY, &h);
2685 if (!NT_SUCCESS(status)) {
2686 winnt_error(status, L"Can't open \"%ls\" to "
2687 "read security descriptor",
2688 printable_path(ctx));
2689 ret = WIMLIB_ERR_OPEN;
2692 ret = winnt_load_security_descriptor(h, inode, ctx);
2697 ret = security_map_insert(security_map, ni->security_id,
2698 inode->i_security_id);
2704 /* Add data streams based on the cached information from the MFT. */
2705 ns = FIRST_STREAM(ni);
2706 for (u32 i = 0; i < ni->num_streams; i++) {
2707 struct windows_file *windows_file;
2709 /* Reference the stream by path if it's a named data stream, or
2710 * if the volume doesn't support "open by file ID", or if the
2711 * application hasn't explicitly opted in to "open by file ID".
2712 * Otherwise, only save the inode number (file ID). */
2714 !(ctx->vol_flags & FILE_SUPPORTS_OPEN_BY_FILE_ID) ||
2715 !(ctx->params->add_flags & WIMLIB_ADD_FLAG_FILE_PATHS_UNNEEDED))
2717 windows_file = alloc_windows_file(ctx->params->cur_path,
2718 ctx->params->cur_path_nchars,
2724 windows_file = alloc_windows_file_for_file_id(ni->ino,
2725 ctx->params->cur_path,
2726 ctx->params->root_path_nchars,
2730 ret = add_stream(inode, windows_file, ns->size,
2731 STREAM_TYPE_DATA, ns->name,
2732 ctx->params->unhashed_blobs);
2735 ns = NEXT_STREAM(ns);
2738 set_sort_key(inode, ni->starting_lcn);
2740 /* If processing a directory, then recurse to its children. In this
2741 * version there is no need to go to disk, as we already have the list
2742 * of children cached from the MFT. */
2743 if (inode_is_directory(inode)) {
2744 const struct ntfs_dentry *nd = ni->first_child;
2746 while (nd != NULL) {
2747 size_t orig_path_nchars;
2748 struct wim_dentry *child;
2749 const struct ntfs_dentry *next = nd->next_child;
2751 ret = WIMLIB_ERR_NOMEM;
2752 if (!pathbuf_append_name(ctx->params, nd->name,
2757 ret = generate_wim_structures_recursive(
2761 (void *)nd - nd->offset_from_inode,
2766 pathbuf_truncate(ctx->params, orig_path_nchars);
2771 attach_scanned_tree(root, child, ctx->params->blob_table);
2778 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_OK, inode);
2780 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
2782 if (--ni->num_aliases == 0) {
2783 /* Memory usage optimization: when we don't need the ntfs_inode
2784 * (and its names and streams) anymore, free it. */
2785 ntfs_inode_map_remove(inode_map, ni);
2787 if (unlikely(ret)) {
2788 free_dentry_tree(root, ctx->params->blob_table);
2796 winnt_build_dentry_tree_fast(struct wim_dentry **root_ret,
2797 struct winnt_scan_ctx *ctx)
2799 struct ntfs_inode_map inode_map = { .root = NULL };
2800 struct security_map security_map = { .root = NULL };
2801 struct ntfs_inode *root = NULL;
2802 wchar_t *path = ctx->params->cur_path;
2803 size_t path_nchars = ctx->params->cur_path_nchars;
2807 adjust_path = (path[path_nchars - 1] == L'\\');
2809 path[path_nchars - 1] = L'\0';
2811 ret = load_files_from_mft(path, &inode_map);
2814 path[path_nchars - 1] = L'\\';
2819 ret = build_children_lists(&inode_map, &root);
2824 ERROR("The MFT listing for volume \"%ls\" did not include a "
2825 "root directory!", path);
2826 ret = WIMLIB_ERR_UNSUPPORTED;
2830 root->num_aliases = 1;
2832 ret = generate_wim_structures_recursive(root_ret, L"", false, root, ctx,
2833 &inode_map, &security_map);
2835 ntfs_inode_map_destroy(&inode_map);
2836 security_map_destroy(&security_map);
2840 #endif /* ENABLE_FAST_MFT_SCAN */
2842 /*----------------------------------------------------------------------------*
2843 * Entry point for directory tree scans on Windows *
2844 *----------------------------------------------------------------------------*/
2847 win32_build_dentry_tree(struct wim_dentry **root_ret,
2848 const wchar_t *root_disk_path,
2849 struct scan_params *params)
2851 struct winnt_scan_ctx ctx = { .params = params };
2852 UNICODE_STRING ntpath;
2857 if (params->add_flags & WIMLIB_ADD_FLAG_SNAPSHOT)
2858 ret = vss_create_snapshot(root_disk_path, &ntpath, &ctx.snapshot);
2860 ret = win32_path_to_nt_path(root_disk_path, &ntpath);
2865 if (ntpath.Length < 4 * sizeof(wchar_t) ||
2866 wmemcmp(ntpath.Buffer, L"\\??\\", 4))
2868 ERROR("\"%ls\": unrecognized path format", root_disk_path);
2869 ret = WIMLIB_ERR_INVALID_PARAM;
2871 ret = pathbuf_init(params, ntpath.Buffer);
2873 HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
2877 status = winnt_open(params->cur_path, params->cur_path_nchars,
2878 FILE_READ_ATTRIBUTES, &h);
2879 if (!NT_SUCCESS(status)) {
2880 winnt_error(status, L"Can't open \"%ls\"", root_disk_path);
2881 if (status == STATUS_FVE_LOCKED_VOLUME)
2882 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
2884 ret = WIMLIB_ERR_OPEN;
2888 get_volume_information(h, &ctx);
2892 #ifdef ENABLE_FAST_MFT_SCAN
2893 if (ctx.is_ntfs && !_wgetenv(L"WIMLIB_DISABLE_QUERY_FILE_LAYOUT")) {
2894 ret = winnt_build_dentry_tree_fast(root_ret, &ctx);
2895 if (ret >= 0 && ret != WIMLIB_ERR_UNSUPPORTED)
2898 WARNING("A problem occurred during the fast MFT scan.\n"
2899 " Falling back to the standard "
2900 "recursive directory tree scan.");
2904 ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
2906 params->cur_path_nchars,
2909 vss_put_snapshot(ctx.snapshot);
2911 winnt_do_scan_warnings(root_disk_path, &ctx);
2915 #endif /* __WIN32__ */