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-2016 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 wchar_t *full_path)
63 /* Skip over \\?\ or \??\ */
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 read_blob_callbacks *cbs)
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 = call_consume_chunk(buf, bytes_read, cbs);
412 struct win32_encrypted_read_ctx {
413 const struct read_blob_callbacks *cbs;
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 = call_consume_chunk(data, bytes_to_consume, ctx->cbs);
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 read_blob_callbacks *cbs)
443 struct win32_encrypted_read_ctx export_ctx;
450 flags |= CREATE_FOR_DIR;
452 export_ctx.cbs = cbs;
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",
460 printable_path(path));
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\"",
470 printable_path(path));
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,
477 printable_path(path));
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 read_blob_callbacks *cbs)
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, cbs);
499 return read_winnt_stream_prefix(file, size, cbs);
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 const wchar_t *full_path,
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(full_path));
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 const wchar_t *full_path, struct winnt_scan_ctx *ctx)
664 FILE_OBJECTID_BUFFER buffer;
668 if (!(ctx->vol_flags & FILE_SUPPORTS_OBJECT_IDS))
671 status = winnt_fsctl(h, FSCTL_GET_OBJECT_ID, NULL, 0,
672 &buffer, sizeof(buffer), &len);
674 if (status == STATUS_OBJECTID_NOT_FOUND) /* No object ID */
677 if (status == STATUS_INVALID_DEVICE_REQUEST) {
678 /* The filesystem claimed to support object IDs, but we can't
679 * actually read them. This happens with Samba. */
680 ctx->vol_flags &= ~FILE_SUPPORTS_OBJECT_IDS;
684 if (!NT_SUCCESS(status)) {
685 winnt_error(status, L"\"%ls\": Can't read object ID",
686 printable_path(full_path));
687 return WIMLIB_ERR_STAT;
690 if (len == 0) /* No object ID (for directories) */
693 if (!inode_set_object_id(inode, &buffer, len))
694 return WIMLIB_ERR_NOMEM;
700 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
703 size_t full_path_nchars,
704 wchar_t *relative_path,
705 size_t relative_path_nchars,
706 const wchar_t *filename,
707 struct winnt_scan_ctx *ctx);
710 winnt_recurse_directory(HANDLE h,
712 size_t full_path_nchars,
713 struct wim_dentry *parent,
714 struct winnt_scan_ctx *ctx)
717 const size_t bufsize = 8192;
718 IO_STATUS_BLOCK iosb;
722 buf = MALLOC(bufsize);
724 return WIMLIB_ERR_NOMEM;
726 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
727 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
729 while (NT_SUCCESS(status = NtQueryDirectoryFile(h, NULL, NULL, NULL,
731 FileNamesInformation,
732 FALSE, NULL, FALSE)))
734 const FILE_NAMES_INFORMATION *info = buf;
736 if (!should_ignore_filename(info->FileName,
737 info->FileNameLength / 2))
741 struct wim_dentry *child;
743 p = full_path + full_path_nchars;
744 /* Only add a backslash if we don't already have
745 * one. This prevents a duplicate backslash
746 * from being added when the path to the capture
747 * dir had a trailing backslash. */
748 if (*(p - 1) != L'\\')
751 p = wmempcpy(filename, info->FileName,
752 info->FileNameLength / 2);
755 ret = winnt_build_dentry_tree_recursive(
761 info->FileNameLength / 2,
765 full_path[full_path_nchars] = L'\0';
769 attach_scanned_tree(parent, child,
770 ctx->params->blob_table);
772 if (info->NextEntryOffset == 0)
774 info = (const FILE_NAMES_INFORMATION *)
775 ((const u8 *)info + info->NextEntryOffset);
779 if (unlikely(status != STATUS_NO_MORE_FILES)) {
780 winnt_error(status, L"\"%ls\": Can't read directory",
781 printable_path(full_path));
782 ret = WIMLIB_ERR_READ;
789 /* Reparse point fixup status code */
790 #define RP_FIXED (-1)
793 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
796 IO_STATUS_BLOCK iosb;
797 FILE_INTERNAL_INFORMATION int_info;
798 FILE_FS_VOLUME_INFORMATION vol_info;
800 status = NtQueryInformationFile(h, &iosb, &int_info, sizeof(int_info),
801 FileInternalInformation);
802 if (!NT_SUCCESS(status))
805 if (int_info.IndexNumber.QuadPart != ino)
808 status = NtQueryVolumeInformationFile(h, &iosb,
809 &vol_info, sizeof(vol_info),
810 FileFsVolumeInformation);
811 if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
814 if (iosb.Information <
815 offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
816 sizeof(vol_info.VolumeSerialNumber))
819 return (vol_info.VolumeSerialNumber == dev);
823 * This is the Windows equivalent of unix_relativize_link_target(); see there
824 * for general details. This version works with an "absolute" Windows link
825 * target, specified from the root of the Windows kernel object namespace. Note
826 * that we have to open directories with a trailing slash when present because
827 * \??\E: opens the E: device itself and not the filesystem root directory.
829 static const wchar_t *
830 winnt_relativize_link_target(const wchar_t *target, size_t target_nbytes,
834 OBJECT_ATTRIBUTES attr;
835 IO_STATUS_BLOCK iosb;
837 const wchar_t *target_end;
840 target_end = target + (target_nbytes / sizeof(wchar_t));
843 if (target_end == target)
846 /* No leading slash??? */
847 if (target[0] != L'\\')
851 if ((target_end - target) >= 2 &&
852 target[0] == L'\\' && target[1] == L'\\')
855 attr.Length = sizeof(attr);
856 attr.RootDirectory = NULL;
857 attr.ObjectName = &name;
859 attr.SecurityDescriptor = NULL;
860 attr.SecurityQualityOfService = NULL;
862 name.Buffer = (wchar_t *)target;
867 const wchar_t *orig_p = p;
869 /* Skip non-backslashes */
870 while (p != target_end && *p != L'\\')
873 /* Skip backslashes */
874 while (p != target_end && *p == L'\\')
877 /* Append path component */
878 name.Length += (p - orig_p) * sizeof(wchar_t);
879 name.MaximumLength = name.Length;
881 /* Try opening the file */
882 status = NtOpenFile(&h,
883 FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
886 FILE_SHARE_VALID_FLAGS,
887 FILE_OPEN_FOR_BACKUP_INTENT);
889 if (NT_SUCCESS(status)) {
890 /* Reset root directory */
891 if (attr.RootDirectory)
892 NtClose(attr.RootDirectory);
893 attr.RootDirectory = h;
894 name.Buffer = (wchar_t *)p;
897 if (file_has_ino_and_dev(h, ino, dev))
898 goto out_close_root_dir;
900 } while (p != target_end);
905 if (attr.RootDirectory)
906 NtClose(attr.RootDirectory);
907 while (p > target && *(p - 1) == L'\\')
913 winnt_rpfix_progress(struct scan_params *params, const wchar_t *path,
914 const struct link_reparse_point *link, int scan_status)
916 size_t print_name_nchars = link->print_name_nbytes / sizeof(wchar_t);
917 wchar_t print_name0[print_name_nchars + 1];
919 wmemcpy(print_name0, link->print_name, print_name_nchars);
920 print_name0[print_name_nchars] = L'\0';
922 params->progress.scan.cur_path = path;
923 params->progress.scan.symlink_target = print_name0;
924 return do_scan_progress(params, scan_status, NULL);
928 winnt_try_rpfix(struct reparse_buffer_disk *rpbuf, u16 *rpbuflen_p,
929 const wchar_t *path, struct scan_params *params)
931 struct link_reparse_point link;
932 const wchar_t *rel_target;
935 if (parse_link_reparse_point(rpbuf, *rpbuflen_p, &link)) {
936 /* Couldn't understand the reparse data; don't do the fixup. */
941 * Don't do reparse point fixups on relative symbolic links.
943 * On Windows, a relative symbolic link is supposed to be identifiable
944 * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
945 * SYMBOLIC_LINK_RELATIVE. We will use this information, although this
946 * may not always do what the user expects, since drive-relative
947 * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
948 * set, in addition to truly relative symbolic links such as "Users" or
949 * "Users\Public". However, WIMGAPI (as of Windows 8.1) has this same
952 * Otherwise, as far as I can tell, the targets of symbolic links that
953 * are NOT relative, as well as junctions (note: a mountpoint is the
954 * sames thing as a junction), must be NT namespace paths, for example:
956 * - \??\e:\Users\Public
957 * - \DosDevices\e:\Users\Public
958 * - \Device\HardDiskVolume4\Users\Public
959 * - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
960 * - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
962 if (link_is_relative_symlink(&link))
965 rel_target = winnt_relativize_link_target(link.substitute_name,
966 link.substitute_name_nbytes,
967 params->capture_root_ino,
968 params->capture_root_dev);
970 if (rel_target == link.substitute_name) {
971 /* Target points outside of the tree being captured or had an
972 * unrecognized path format. Don't adjust it. */
973 return winnt_rpfix_progress(params, path, &link,
974 WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK);
977 /* We have an absolute target pointing within the directory being
978 * captured. @rel_target is the suffix of the link target that is the
979 * part relative to the directory being captured.
981 * We will cut off the prefix before this part (which is the path to the
982 * directory being captured) and add a dummy prefix. Since the process
983 * will need to be reversed when applying the image, it doesn't matter
984 * what exactly the prefix is, as long as it looks like an absolute
987 static const wchar_t prefix[6] = L"\\??\\X:";
988 static const size_t num_unprintable_chars = 4;
990 size_t rel_target_nbytes =
991 link.substitute_name_nbytes - ((const u8 *)rel_target -
992 (const u8 *)link.substitute_name);
994 wchar_t tmp[(sizeof(prefix) + rel_target_nbytes) / sizeof(wchar_t)];
996 memcpy(tmp, prefix, sizeof(prefix));
997 memcpy(tmp + ARRAY_LEN(prefix), rel_target, rel_target_nbytes);
999 link.substitute_name = tmp;
1000 link.substitute_name_nbytes = sizeof(tmp);
1002 link.print_name = link.substitute_name + num_unprintable_chars;
1003 link.print_name_nbytes = link.substitute_name_nbytes -
1004 (num_unprintable_chars * sizeof(wchar_t));
1006 if (make_link_reparse_point(&link, rpbuf, rpbuflen_p))
1009 ret = winnt_rpfix_progress(params, path, &link,
1010 WIMLIB_SCAN_DENTRY_FIXED_SYMLINK);
1016 /* Load the reparse data of a file into the corresponding WIM inode. If the
1017 * reparse point is a symbolic link or junction with an absolute target and
1018 * RPFIX mode is enabled, then also rewrite its target to be relative to the
1020 static noinline_for_stack int
1021 winnt_load_reparse_data(HANDLE h, struct wim_inode *inode,
1022 const wchar_t *full_path, struct scan_params *params)
1024 struct reparse_buffer_disk rpbuf;
1030 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1031 /* See comment above assign_stream_types_encrypted() */
1032 WARNING("Ignoring reparse data of encrypted file \"%ls\"",
1033 printable_path(full_path));
1037 status = winnt_fsctl(h, FSCTL_GET_REPARSE_POINT,
1038 NULL, 0, &rpbuf, sizeof(rpbuf), &len);
1039 if (!NT_SUCCESS(status)) {
1040 winnt_error(status, L"\"%ls\": Can't get reparse point",
1041 printable_path(full_path));
1042 return WIMLIB_ERR_READLINK;
1047 if (unlikely(rpbuflen < REPARSE_DATA_OFFSET)) {
1048 ERROR("\"%ls\": reparse point buffer is too short",
1049 printable_path(full_path));
1050 return WIMLIB_ERR_INVALID_REPARSE_DATA;
1053 if (le32_to_cpu(rpbuf.rptag) == WIM_IO_REPARSE_TAG_DEDUP) {
1055 * Windows treats Data Deduplication reparse points specially.
1056 * Reads from the unnamed data stream actually return the
1057 * redirected file contents, even with FILE_OPEN_REPARSE_POINT.
1058 * Deduplicated files also cannot be properly restored without
1059 * also restoring the "System Volume Information" directory,
1060 * which wimlib excludes by default. Therefore, the logical
1061 * behavior for us seems to be to ignore the reparse point and
1062 * treat the file as a normal file.
1064 inode->i_attributes &= ~FILE_ATTRIBUTE_REPARSE_POINT;
1068 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX) {
1069 ret = winnt_try_rpfix(&rpbuf, &rpbuflen, full_path, params);
1070 if (ret == RP_FIXED)
1071 inode->i_rp_flags &= ~WIM_RP_FLAG_NOT_FIXED;
1076 inode->i_reparse_tag = le32_to_cpu(rpbuf.rptag);
1077 inode->i_rp_reserved = le16_to_cpu(rpbuf.rpreserved);
1079 if (!inode_add_stream_with_data(inode,
1080 STREAM_TYPE_REPARSE_POINT,
1083 rpbuflen - REPARSE_DATA_OFFSET,
1084 params->blob_table))
1085 return WIMLIB_ERR_NOMEM;
1091 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
1094 *(u64*)_size_ret += len;
1095 return ERROR_SUCCESS;
1099 win32_get_encrypted_file_size(const wchar_t *path, bool is_dir, u64 *size_ret)
1107 flags |= CREATE_FOR_DIR;
1109 err = OpenEncryptedFileRaw(path, flags, &file_ctx);
1110 if (err != ERROR_SUCCESS) {
1112 L"Failed to open encrypted file \"%ls\" for raw read",
1113 printable_path(path));
1114 return WIMLIB_ERR_OPEN;
1117 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
1118 size_ret, file_ctx);
1119 if (err != ERROR_SUCCESS) {
1121 L"Failed to read raw encrypted data from \"%ls\"",
1122 printable_path(path));
1123 ret = WIMLIB_ERR_READ;
1127 CloseEncryptedFileRaw(file_ctx);
1132 winnt_scan_efsrpc_raw_data(struct wim_inode *inode,
1133 wchar_t *path, size_t path_nchars,
1134 struct winnt_scan_ctx *ctx)
1136 const bool is_dir = (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY);
1137 struct windows_file *windows_file;
1141 /* OpenEncryptedFileRaw() expects a Win32 name. */
1142 wimlib_assert(!wmemcmp(path, L"\\??\\", 4));
1145 ret = win32_get_encrypted_file_size(path, is_dir, &size);
1149 /* Empty EFSRPC data does not make sense */
1150 wimlib_assert(size != 0);
1152 windows_file = alloc_windows_file(path, path_nchars, NULL, 0,
1153 ctx->snapshot, true);
1154 ret = add_stream(inode, windows_file, size, STREAM_TYPE_EFSRPC_RAW_DATA,
1155 NO_STREAM_NAME, ctx->params->unhashed_blobs);
1162 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1163 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
1165 const wchar_t *sep, *type, *end;
1167 /* The stream name should be returned as :NAME:TYPE */
1168 if (raw_stream_name_nchars < 1)
1170 if (raw_stream_name[0] != L':')
1174 raw_stream_name_nchars--;
1176 end = raw_stream_name + raw_stream_name_nchars;
1178 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
1183 if (end - type != 5)
1186 if (wmemcmp(type, L"$DATA", 5))
1189 *stream_name_ret = raw_stream_name;
1190 *stream_name_nchars_ret = sep - raw_stream_name;
1195 winnt_scan_data_stream(const wchar_t *path, size_t path_nchars,
1196 wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1197 u64 stream_size, struct wim_inode *inode,
1198 struct winnt_scan_ctx *ctx)
1200 wchar_t *stream_name;
1201 size_t stream_name_nchars;
1202 struct windows_file *windows_file;
1204 /* Given the raw stream name (which is something like
1205 * :streamname:$DATA), extract just the stream name part (streamname).
1206 * Ignore any non-$DATA streams. */
1207 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
1208 (const wchar_t **)&stream_name,
1209 &stream_name_nchars))
1212 stream_name[stream_name_nchars] = L'\0';
1214 windows_file = alloc_windows_file(path, path_nchars,
1215 stream_name, stream_name_nchars,
1216 ctx->snapshot, false);
1217 return add_stream(inode, windows_file, stream_size, STREAM_TYPE_DATA,
1218 stream_name, ctx->params->unhashed_blobs);
1222 * Load information about the data streams of an open file into a WIM inode.
1224 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
1225 * and FindNextStream(). This is done for two reasons:
1227 * - FindFirstStream() opens its own handle to the file or directory and
1228 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
1229 * causing access denied errors on certain files (even when running as the
1231 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
1232 * and later, whereas the stream support in NtQueryInformationFile() was
1233 * already present in Windows XP.
1235 static noinline_for_stack int
1236 winnt_scan_data_streams(HANDLE h, const wchar_t *path, size_t path_nchars,
1237 struct wim_inode *inode, u64 file_size,
1238 struct winnt_scan_ctx *ctx)
1241 u8 _buf[4096] _aligned_attribute(8);
1244 IO_STATUS_BLOCK iosb;
1246 FILE_STREAM_INFORMATION *info;
1249 bufsize = sizeof(_buf);
1251 if (!(ctx->vol_flags & FILE_NAMED_STREAMS))
1254 /* Get a buffer containing the stream information. */
1255 while (!NT_SUCCESS(status = NtQueryInformationFile(h,
1259 FileStreamInformation)))
1263 case STATUS_BUFFER_OVERFLOW:
1269 newbuf = MALLOC(bufsize);
1271 newbuf = REALLOC(buf, bufsize);
1273 ret = WIMLIB_ERR_NOMEM;
1279 case STATUS_NOT_IMPLEMENTED:
1280 case STATUS_NOT_SUPPORTED:
1281 case STATUS_INVALID_INFO_CLASS:
1285 L"\"%ls\": Failed to query stream information",
1286 printable_path(path));
1287 ret = WIMLIB_ERR_READ;
1292 if (iosb.Information == 0) {
1293 /* No stream information. */
1298 /* Parse one or more stream information structures. */
1299 info = (FILE_STREAM_INFORMATION *)buf;
1301 /* Load the stream information. */
1302 ret = winnt_scan_data_stream(path, path_nchars,
1304 info->StreamNameLength / 2,
1305 info->StreamSize.QuadPart,
1310 if (info->NextEntryOffset == 0) {
1311 /* No more stream information. */
1314 /* Advance to next stream information. */
1315 info = (FILE_STREAM_INFORMATION *)
1316 ((u8 *)info + info->NextEntryOffset);
1322 /* The volume does not support named streams. Only capture the unnamed
1324 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1325 FILE_ATTRIBUTE_REPARSE_POINT))
1332 wchar_t stream_name[] = L"::$DATA";
1333 ret = winnt_scan_data_stream(path, path_nchars, stream_name, 7,
1334 file_size, inode, ctx);
1337 /* Free buffer if allocated on heap. */
1338 if (unlikely(buf != _buf))
1344 extract_starting_lcn(const RETRIEVAL_POINTERS_BUFFER *extents)
1346 if (extents->ExtentCount < 1)
1349 return extents->Extents[0].Lcn.QuadPart;
1352 static noinline_for_stack u64
1353 get_sort_key(HANDLE h)
1355 STARTING_VCN_INPUT_BUFFER in = { .StartingVcn.QuadPart = 0 };
1356 RETRIEVAL_POINTERS_BUFFER out;
1358 if (!NT_SUCCESS(winnt_fsctl(h, FSCTL_GET_RETRIEVAL_POINTERS,
1359 &in, sizeof(in), &out, sizeof(out), NULL)))
1362 return extract_starting_lcn(&out);
1366 set_sort_key(struct wim_inode *inode, u64 sort_key)
1368 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1369 struct wim_inode_stream *strm = &inode->i_streams[i];
1370 struct blob_descriptor *blob = stream_blob_resolved(strm);
1371 if (blob && blob->blob_location == BLOB_IN_WINDOWS_FILE)
1372 blob->windows_file->sort_key = sort_key;
1377 should_try_to_use_wimboot_hash(const struct wim_inode *inode,
1378 const struct winnt_scan_ctx *ctx,
1379 const struct scan_params *params)
1381 /* Directories and encrypted files aren't valid for external backing. */
1382 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1383 FILE_ATTRIBUTE_ENCRYPTED))
1386 /* If the file is a reparse point, then try the hash fixup if it's a WOF
1387 * reparse point and we're in WIMBOOT mode. Otherwise, try the hash
1388 * fixup if WOF may be attached. */
1389 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1390 return (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_WOF) &&
1391 (params->add_flags & WIMLIB_ADD_FLAG_WIMBOOT);
1392 return !ctx->wof_not_attached;
1396 * This function implements an optimization for capturing files from a
1397 * filesystem with a backing WIM(s). If a file is WIM-backed, then we can
1398 * retrieve the SHA-1 message digest of its original contents from its reparse
1399 * point. This may eliminate the need to read the file's data and/or allow the
1400 * file's data to be immediately deduplicated with existing data in the WIM.
1402 * If WOF is attached, then this function is merely an optimization, but
1403 * potentially a very effective one. If WOF is detached, then this function
1404 * really causes WIM-backed files to be, effectively, automatically
1405 * "dereferenced" when possible; the unnamed data stream is updated to reference
1406 * the original contents and the reparse point is removed.
1408 * This function returns 0 if the fixup succeeded or was intentionally not
1409 * executed. Otherwise it returns an error code.
1411 static noinline_for_stack int
1412 try_to_use_wimboot_hash(HANDLE h, struct wim_inode *inode,
1413 struct winnt_scan_ctx *ctx, const wchar_t *full_path)
1415 struct blob_table *blob_table = ctx->params->blob_table;
1416 struct wim_inode_stream *reparse_strm = NULL;
1417 struct wim_inode_stream *strm;
1418 struct blob_descriptor *blob;
1419 u8 hash[SHA1_HASH_SIZE];
1422 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1423 struct reparse_buffer_disk rpbuf;
1425 struct wof_external_info wof_info;
1426 struct wim_provider_rpdata wim_info;
1427 } *rpdata = (void *)rpbuf.rpdata;
1428 struct blob_descriptor *reparse_blob;
1430 /* The file has a WOF reparse point, so WOF must be detached.
1431 * We can read the reparse point directly. */
1432 ctx->wof_not_attached = true;
1433 reparse_strm = inode_get_unnamed_stream(inode, STREAM_TYPE_REPARSE_POINT);
1434 reparse_blob = stream_blob_resolved(reparse_strm);
1436 if (!reparse_blob || reparse_blob->size < sizeof(*rpdata))
1437 return 0; /* Not a WIM-backed file */
1439 ret = read_blob_into_buf(reparse_blob, rpdata);
1443 if (rpdata->wof_info.version != WOF_CURRENT_VERSION ||
1444 rpdata->wof_info.provider != WOF_PROVIDER_WIM ||
1445 rpdata->wim_info.version != 2)
1446 return 0; /* Not a WIM-backed file */
1448 /* Okay, this is a WIM backed file. Get its SHA-1 hash. */
1449 copy_hash(hash, rpdata->wim_info.unnamed_data_stream_hash);
1452 struct wof_external_info wof_info;
1453 struct wim_provider_external_info wim_info;
1457 /* WOF may be attached. Try reading this file's external
1459 status = winnt_fsctl(h, FSCTL_GET_EXTERNAL_BACKING,
1460 NULL, 0, &out, sizeof(out), NULL);
1462 /* Is WOF not attached? */
1463 if (status == STATUS_INVALID_DEVICE_REQUEST ||
1464 status == STATUS_NOT_SUPPORTED) {
1465 ctx->wof_not_attached = true;
1469 /* Is this file not externally backed? */
1470 if (status == STATUS_OBJECT_NOT_EXTERNALLY_BACKED)
1473 /* Does this file have an unknown type of external backing that
1474 * needed a larger information buffer? */
1475 if (status == STATUS_BUFFER_TOO_SMALL)
1478 /* Was there some other failure? */
1479 if (status != STATUS_SUCCESS) {
1481 L"\"%ls\": FSCTL_GET_EXTERNAL_BACKING failed",
1483 return WIMLIB_ERR_STAT;
1486 /* Is this file backed by a WIM? */
1487 if (out.wof_info.version != WOF_CURRENT_VERSION ||
1488 out.wof_info.provider != WOF_PROVIDER_WIM ||
1489 out.wim_info.version != WIM_PROVIDER_CURRENT_VERSION)
1492 /* Okay, this is a WIM backed file. Get its SHA-1 hash. */
1493 copy_hash(hash, out.wim_info.unnamed_data_stream_hash);
1496 /* If the file's unnamed data stream is nonempty, then fill in its hash
1497 * and deduplicate it if possible.
1499 * With WOF detached, we require that the blob *must* de-duplicable for
1500 * any action can be taken, since without WOF we can't fall back to
1501 * getting the "dereferenced" data by reading the stream (the real
1502 * stream is sparse and contains all zeroes). */
1503 strm = inode_get_unnamed_data_stream(inode);
1504 if (strm && (blob = stream_blob_resolved(strm))) {
1505 struct blob_descriptor **back_ptr;
1507 if (reparse_strm && !lookup_blob(blob_table, hash))
1509 back_ptr = retrieve_pointer_to_unhashed_blob(blob);
1510 copy_hash(blob->hash, hash);
1511 if (after_blob_hashed(blob, back_ptr, blob_table) != blob)
1512 free_blob_descriptor(blob);
1515 /* Remove the reparse point, if present. */
1517 inode_remove_stream(inode, reparse_strm, blob_table);
1518 inode->i_attributes &= ~(FILE_ATTRIBUTE_REPARSE_POINT |
1519 FILE_ATTRIBUTE_SPARSE_FILE);
1520 if (inode->i_attributes == 0)
1521 inode->i_attributes = FILE_ATTRIBUTE_NORMAL;
1531 u64 last_write_time;
1532 u64 last_access_time;
1537 static noinline_for_stack NTSTATUS
1538 get_file_info(HANDLE h, struct file_info *info)
1540 IO_STATUS_BLOCK iosb;
1542 FILE_ALL_INFORMATION all_info;
1544 status = NtQueryInformationFile(h, &iosb, &all_info, sizeof(all_info),
1545 FileAllInformation);
1547 if (unlikely(!NT_SUCCESS(status) && status != STATUS_BUFFER_OVERFLOW))
1550 info->attributes = all_info.BasicInformation.FileAttributes;
1551 info->num_links = all_info.StandardInformation.NumberOfLinks;
1552 info->creation_time = all_info.BasicInformation.CreationTime.QuadPart;
1553 info->last_write_time = all_info.BasicInformation.LastWriteTime.QuadPart;
1554 info->last_access_time = all_info.BasicInformation.LastAccessTime.QuadPart;
1555 info->ino = all_info.InternalInformation.IndexNumber.QuadPart;
1556 info->end_of_file = all_info.StandardInformation.EndOfFile.QuadPart;
1557 return STATUS_SUCCESS;
1561 get_volume_information(HANDLE h, const wchar_t *full_path,
1562 struct winnt_scan_ctx *ctx)
1564 u8 _attr_info[sizeof(FILE_FS_ATTRIBUTE_INFORMATION) + 128] _aligned_attribute(8);
1565 FILE_FS_ATTRIBUTE_INFORMATION *attr_info = (void *)_attr_info;
1566 FILE_FS_VOLUME_INFORMATION vol_info;
1567 struct file_info file_info;
1568 IO_STATUS_BLOCK iosb;
1571 /* Get volume flags */
1572 status = NtQueryVolumeInformationFile(h, &iosb, attr_info,
1574 FileFsAttributeInformation);
1575 if (NT_SUCCESS(status)) {
1576 ctx->vol_flags = attr_info->FileSystemAttributes;
1577 ctx->is_ntfs = (attr_info->FileSystemNameLength == 4 * sizeof(wchar_t)) &&
1578 !wmemcmp(attr_info->FileSystemName, L"NTFS", 4);
1580 winnt_warning(status, L"\"%ls\": Can't get volume attributes",
1581 printable_path(full_path));
1584 /* Get volume ID. */
1585 status = NtQueryVolumeInformationFile(h, &iosb, &vol_info,
1587 FileFsVolumeInformation);
1588 if ((NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW) &&
1589 (iosb.Information >= offsetof(FILE_FS_VOLUME_INFORMATION,
1590 VolumeSerialNumber) +
1591 sizeof(vol_info.VolumeSerialNumber)))
1593 ctx->params->capture_root_dev = vol_info.VolumeSerialNumber;
1595 winnt_warning(status, L"\"%ls\": Can't get volume ID",
1596 printable_path(full_path));
1599 /* Get inode number. */
1600 status = get_file_info(h, &file_info);
1601 if (NT_SUCCESS(status)) {
1602 ctx->params->capture_root_ino = file_info.ino;
1604 winnt_warning(status, L"\"%ls\": Can't get file information",
1605 printable_path(full_path));
1610 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1613 size_t full_path_nchars,
1614 wchar_t *relative_path,
1615 size_t relative_path_nchars,
1616 const wchar_t *filename,
1617 struct winnt_scan_ctx *ctx)
1619 struct wim_dentry *root = NULL;
1620 struct wim_inode *inode = NULL;
1624 struct file_info file_info;
1627 ret = try_exclude(full_path, ctx->params);
1628 if (unlikely(ret < 0)) /* Excluded? */
1630 if (unlikely(ret > 0)) /* Error? */
1633 /* Open the file with permission to read metadata. Although we will
1634 * later need a handle with FILE_LIST_DIRECTORY permission (or,
1635 * equivalently, FILE_READ_DATA; they're the same numeric value) if the
1636 * file is a directory, it can significantly slow things down to request
1637 * this permission on all nondirectories. Perhaps it causes Windows to
1638 * start prefetching the file contents... */
1639 status = winnt_openat(cur_dir, relative_path, relative_path_nchars,
1640 FILE_READ_ATTRIBUTES | READ_CONTROL |
1641 ACCESS_SYSTEM_SECURITY,
1643 if (unlikely(!NT_SUCCESS(status))) {
1644 if (status == STATUS_DELETE_PENDING) {
1645 WARNING("\"%ls\": Deletion pending; skipping file",
1646 printable_path(full_path));
1650 if (status == STATUS_SHARING_VIOLATION) {
1651 ERROR("Can't open \"%ls\":\n"
1652 " File is in use by another process! "
1653 "Consider using snapshot (VSS) mode.",
1654 printable_path(full_path));
1655 ret = WIMLIB_ERR_OPEN;
1658 winnt_error(status, L"\"%ls\": Can't open file",
1659 printable_path(full_path));
1660 if (status == STATUS_FVE_LOCKED_VOLUME)
1661 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1663 ret = WIMLIB_ERR_OPEN;
1667 /* Get information about the file. */
1668 status = get_file_info(h, &file_info);
1669 if (!NT_SUCCESS(status)) {
1670 winnt_error(status, L"\"%ls\": Can't get file information",
1671 printable_path(full_path));
1672 ret = WIMLIB_ERR_STAT;
1676 /* Create a WIM dentry with an associated inode, which may be shared.
1678 * However, we need to explicitly check for directories and files with
1679 * only 1 link and refuse to hard link them. This is because Windows
1680 * has a bug where it can return duplicate File IDs for files and
1681 * directories on the FAT filesystem.
1683 * Since we don't follow mount points on Windows, we don't need to query
1684 * the volume ID per-file. Just once, for the root, is enough. But we
1685 * can't simply pass 0, because then there could be inode collisions
1686 * among multiple calls to win32_build_dentry_tree() that are scanning
1687 * files on different volumes. */
1688 ret = inode_table_new_dentry(ctx->params->inode_table,
1691 ctx->params->capture_root_dev,
1692 (file_info.num_links <= 1),
1697 /* Get the short (DOS) name of the file. */
1698 status = winnt_get_short_name(h, root);
1700 /* If we can't read the short filename for any reason other than
1701 * out-of-memory, just ignore the error and assume the file has no short
1702 * name. This shouldn't be an issue, since the short names are
1703 * essentially obsolete anyway. */
1704 if (unlikely(status == STATUS_NO_MEMORY)) {
1705 ret = WIMLIB_ERR_NOMEM;
1709 inode = root->d_inode;
1711 if (inode->i_nlink > 1) {
1712 /* Shared inode (hard link); skip reading per-inode information.
1717 inode->i_attributes = file_info.attributes;
1718 inode->i_creation_time = file_info.creation_time;
1719 inode->i_last_write_time = file_info.last_write_time;
1720 inode->i_last_access_time = file_info.last_access_time;
1722 /* Get the file's security descriptor, unless we are capturing in
1723 * NO_ACLS mode or the volume does not support security descriptors. */
1724 if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1725 && (ctx->vol_flags & FILE_PERSISTENT_ACLS))
1727 ret = winnt_load_security_descriptor(h, inode, full_path, ctx);
1732 /* Get the file's object ID. */
1733 ret = winnt_load_object_id(h, inode, full_path, ctx);
1737 /* If this is a reparse point, load the reparse data. */
1738 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1739 ret = winnt_load_reparse_data(h, inode, full_path, ctx->params);
1744 sort_key = get_sort_key(h);
1746 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1747 /* Load information about the raw encrypted data. This is
1748 * needed for any directory or non-directory that has
1749 * FILE_ATTRIBUTE_ENCRYPTED set.
1751 * Note: since OpenEncryptedFileRaw() fails with
1752 * ERROR_SHARING_VIOLATION if there are any open handles to the
1753 * file, we have to close the file and re-open it later if
1757 ret = winnt_scan_efsrpc_raw_data(inode, full_path,
1758 full_path_nchars, ctx);
1763 * Load information about data streams (unnamed and named).
1765 * Skip this step for encrypted files, since the data from
1766 * ReadEncryptedFileRaw() already contains all data streams (and
1767 * they do in fact all get restored by WriteEncryptedFileRaw().)
1769 * Note: WIMGAPI (as of Windows 8.1) gets wrong and stores both
1770 * the EFSRPC data and the named data stream(s)...!
1772 ret = winnt_scan_data_streams(h,
1776 file_info.end_of_file,
1782 if (unlikely(should_try_to_use_wimboot_hash(inode, ctx, ctx->params))) {
1783 ret = try_to_use_wimboot_hash(h, inode, ctx, full_path);
1788 set_sort_key(inode, sort_key);
1790 if (inode_is_directory(inode)) {
1792 /* Directory: recurse to children. */
1794 /* Re-open the directory with FILE_LIST_DIRECTORY access. */
1799 status = winnt_openat(cur_dir, relative_path,
1800 relative_path_nchars, FILE_LIST_DIRECTORY,
1802 if (!NT_SUCCESS(status)) {
1803 winnt_error(status, L"\"%ls\": Can't open directory",
1804 printable_path(full_path));
1805 ret = WIMLIB_ERR_OPEN;
1808 ret = winnt_recurse_directory(h,
1818 ctx->params->progress.scan.cur_path = full_path;
1820 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_OK, inode);
1822 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1826 if (unlikely(ret)) {
1827 free_dentry_tree(root, ctx->params->blob_table);
1829 ret = report_scan_error(ctx->params, ret, full_path);
1836 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_ctx *ctx)
1838 if (likely(ctx->num_get_sacl_priv_notheld == 0 &&
1839 ctx->num_get_sd_access_denied == 0))
1842 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1843 if (ctx->num_get_sacl_priv_notheld != 0) {
1844 WARNING("- Could not capture SACL (System Access Control List)\n"
1845 " on %lu files or directories.",
1846 ctx->num_get_sacl_priv_notheld);
1848 if (ctx->num_get_sd_access_denied != 0) {
1849 WARNING("- Could not capture security descriptor at all\n"
1850 " on %lu files or directories.",
1851 ctx->num_get_sd_access_denied);
1853 WARNING("To fully capture all security descriptors, run the program\n"
1854 " with Administrator rights.");
1857 /*----------------------------------------------------------------------------*
1858 * Fast MFT scan implementation *
1859 *----------------------------------------------------------------------------*/
1861 #define ENABLE_FAST_MFT_SCAN 1
1863 #ifdef ENABLE_FAST_MFT_SCAN
1866 u64 StartingCluster;
1871 u64 StartingFileReferenceNumber;
1872 u64 EndingFileReferenceNumber;
1873 } FILE_REFERENCE_RANGE;
1875 /* The FSCTL_QUERY_FILE_LAYOUT ioctl. This ioctl can be used on Windows 8 and
1876 * later to scan the MFT of an NTFS volume. */
1877 #define FSCTL_QUERY_FILE_LAYOUT CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 157, METHOD_NEITHER, FILE_ANY_ACCESS)
1879 /* The input to FSCTL_QUERY_FILE_LAYOUT */
1882 #define QUERY_FILE_LAYOUT_RESTART 0x00000001
1883 #define QUERY_FILE_LAYOUT_INCLUDE_NAMES 0x00000002
1884 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS 0x00000004
1885 #define QUERY_FILE_LAYOUT_INCLUDE_EXTENTS 0x00000008
1886 #define QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO 0x00000010
1887 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED 0x00000020
1889 #define QUERY_FILE_LAYOUT_FILTER_TYPE_NONE 0
1890 #define QUERY_FILE_LAYOUT_FILTER_TYPE_CLUSTERS 1
1891 #define QUERY_FILE_LAYOUT_FILTER_TYPE_FILEID 2
1892 #define QUERY_FILE_LAYOUT_NUM_FILTER_TYPES 3
1896 CLUSTER_RANGE ClusterRanges[1];
1897 FILE_REFERENCE_RANGE FileReferenceRanges[1];
1899 } QUERY_FILE_LAYOUT_INPUT;
1901 /* The header of the buffer returned by FSCTL_QUERY_FILE_LAYOUT */
1904 u32 FirstFileOffset;
1905 #define QUERY_FILE_LAYOUT_SINGLE_INSTANCED 0x00000001
1908 } QUERY_FILE_LAYOUT_OUTPUT;
1910 /* Inode information returned by FSCTL_QUERY_FILE_LAYOUT */
1916 u64 FileReferenceNumber;
1917 u32 FirstNameOffset;
1918 u32 FirstStreamOffset;
1919 u32 ExtraInfoOffset;
1921 } FILE_LAYOUT_ENTRY;
1923 /* Extra inode information returned by FSCTL_QUERY_FILE_LAYOUT */
1935 } FILE_LAYOUT_INFO_ENTRY;
1937 /* Filename (or dentry) information returned by FSCTL_QUERY_FILE_LAYOUT */
1940 #define FILE_LAYOUT_NAME_ENTRY_PRIMARY 0x00000001
1941 #define FILE_LAYOUT_NAME_ENTRY_DOS 0x00000002
1943 u64 ParentFileReferenceNumber;
1946 wchar_t FileName[1];
1947 } FILE_LAYOUT_NAME_ENTRY;
1949 /* Stream information returned by FSCTL_QUERY_FILE_LAYOUT */
1952 u32 NextStreamOffset;
1953 #define STREAM_LAYOUT_ENTRY_IMMOVABLE 0x00000001
1954 #define STREAM_LAYOUT_ENTRY_PINNED 0x00000002
1955 #define STREAM_LAYOUT_ENTRY_RESIDENT 0x00000004
1956 #define STREAM_LAYOUT_ENTRY_NO_CLUSTERS_ALLOCATED 0x00000008
1958 u32 ExtentInformationOffset;
1963 u32 StreamIdentifierLength;
1964 wchar_t StreamIdentifier[1];
1965 } STREAM_LAYOUT_ENTRY;
1969 #define STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS 0x00000001
1970 #define STREAM_EXTENT_ENTRY_ALL_EXTENTS 0x00000002
1973 RETRIEVAL_POINTERS_BUFFER RetrievalPointers;
1974 } ExtentInformation;
1975 } STREAM_EXTENT_ENTRY;
1977 /* Extract the MFT number part of the full inode number */
1978 #define NTFS_MFT_NO(ref) ((ref) & (((u64)1 << 48) - 1))
1980 /* Is the file the root directory of the NTFS volume? The root directory always
1981 * occupies MFT record 5. */
1982 #define NTFS_IS_ROOT_FILE(ino) (NTFS_MFT_NO(ino) == 5)
1984 /* Is the file a special NTFS file, other than the root directory? The special
1985 * files are the first 16 records in the MFT. */
1986 #define NTFS_IS_SPECIAL_FILE(ino) \
1987 (NTFS_MFT_NO(ino) <= 15 && !NTFS_IS_ROOT_FILE(ino))
1989 /* Intermediate inode structure. This is used to temporarily save information
1990 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_inode'. */
1992 struct avl_tree_node index_node;
1995 u64 last_access_time;
1996 u64 last_write_time;
2001 u32 num_streams : 31;
2002 u32 have_object_id : 1;
2003 u32 first_stream_offset;
2004 struct ntfs_dentry *first_child;
2005 wchar_t short_name[13];
2008 /* Intermediate dentry structure. This is used to temporarily save information
2009 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_dentry'. */
2010 struct ntfs_dentry {
2011 u32 offset_from_inode : 31;
2014 /* Note: build_children_lists() replaces 'parent_ino' with
2017 struct ntfs_dentry *next_child;
2022 /* Intermediate stream structure. This is used to temporarily save information
2023 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct
2024 * wim_inode_stream'. */
2025 struct ntfs_stream {
2030 /* Map of all known NTFS inodes, keyed by inode number */
2031 struct ntfs_inode_map {
2032 struct avl_tree_node *root;
2035 #define NTFS_INODE(node) \
2036 avl_tree_entry((node), struct ntfs_inode, index_node)
2038 #define SKIP_ALIGNED(p, size) ((void *)(p) + ALIGN((size), 8))
2040 /* Get a pointer to the first dentry of the inode. */
2041 #define FIRST_DENTRY(ni) SKIP_ALIGNED((ni), sizeof(struct ntfs_inode))
2043 /* Get a pointer to the first stream of the inode. */
2044 #define FIRST_STREAM(ni) ((const void *)ni + ni->first_stream_offset)
2046 /* Advance to the next dentry of the inode. */
2047 #define NEXT_DENTRY(nd) SKIP_ALIGNED((nd), sizeof(struct ntfs_dentry) + \
2048 (wcslen((nd)->name) + 1) * sizeof(wchar_t))
2050 /* Advance to the next stream of the inode. */
2051 #define NEXT_STREAM(ns) SKIP_ALIGNED((ns), sizeof(struct ntfs_stream) + \
2052 (wcslen((ns)->name) + 1) * sizeof(wchar_t))
2055 _avl_cmp_ntfs_inodes(const struct avl_tree_node *node1,
2056 const struct avl_tree_node *node2)
2058 return cmp_u64(NTFS_INODE(node1)->ino, NTFS_INODE(node2)->ino);
2061 /* Adds an NTFS inode to the map. */
2063 ntfs_inode_map_add_inode(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2065 if (avl_tree_insert(&map->root, &ni->index_node, _avl_cmp_ntfs_inodes)) {
2066 WARNING("Inode 0x%016"PRIx64" is a duplicate!", ni->ino);
2071 /* Find an ntfs_inode in the map by inode number. Returns NULL if not found. */
2072 static struct ntfs_inode *
2073 ntfs_inode_map_lookup(struct ntfs_inode_map *map, u64 ino)
2075 struct ntfs_inode tmp;
2076 struct avl_tree_node *res;
2079 res = avl_tree_lookup_node(map->root, &tmp.index_node, _avl_cmp_ntfs_inodes);
2082 return NTFS_INODE(res);
2085 /* Remove an ntfs_inode from the map and free it. */
2087 ntfs_inode_map_remove(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2089 avl_tree_remove(&map->root, &ni->index_node);
2093 /* Free all ntfs_inodes in the map. */
2095 ntfs_inode_map_destroy(struct ntfs_inode_map *map)
2097 struct ntfs_inode *ni;
2099 avl_tree_for_each_in_postorder(ni, map->root, struct ntfs_inode, index_node)
2104 file_has_streams(const FILE_LAYOUT_ENTRY *file)
2106 return (file->FirstStreamOffset != 0) &&
2107 !(file->FileAttributes & FILE_ATTRIBUTE_ENCRYPTED);
2111 is_valid_name_entry(const FILE_LAYOUT_NAME_ENTRY *name)
2113 return name->FileNameLength > 0 &&
2114 name->FileNameLength % 2 == 0 &&
2115 !wmemchr(name->FileName, L'\0', name->FileNameLength / 2) &&
2116 (!(name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) ||
2117 name->FileNameLength <= 24);
2120 /* Validate the FILE_LAYOUT_NAME_ENTRYs of the specified file and compute the
2121 * total length in bytes of the ntfs_dentry structures needed to hold the name
2124 validate_names_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2125 size_t *total_length_ret)
2127 const FILE_LAYOUT_NAME_ENTRY *name =
2128 (const void *)file + file->FirstNameOffset;
2130 size_t num_long_names = 0;
2133 if (unlikely(!is_valid_name_entry(name))) {
2134 ERROR("Invalid FILE_LAYOUT_NAME_ENTRY! "
2135 "FileReferenceNumber=0x%016"PRIx64", "
2136 "FileNameLength=%"PRIu32", "
2137 "FileName=%.*ls, Flags=0x%08"PRIx32,
2138 file->FileReferenceNumber,
2139 name->FileNameLength,
2140 (int)(name->FileNameLength / 2),
2141 name->FileName, name->Flags);
2142 return WIMLIB_ERR_UNSUPPORTED;
2144 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2146 total += ALIGN(sizeof(struct ntfs_dentry) +
2147 name->FileNameLength + sizeof(wchar_t),
2150 if (name->NextNameOffset == 0)
2152 name = (const void *)name + name->NextNameOffset;
2155 if (unlikely(num_long_names == 0)) {
2156 ERROR("Inode 0x%016"PRIx64" has no long names!",
2157 file->FileReferenceNumber);
2158 return WIMLIB_ERR_UNSUPPORTED;
2161 *total_length_ret = total;
2166 is_valid_stream_entry(const STREAM_LAYOUT_ENTRY *stream)
2168 return stream->StreamIdentifierLength % 2 == 0 &&
2169 !wmemchr(stream->StreamIdentifier , L'\0',
2170 stream->StreamIdentifierLength / 2);
2174 is_object_id_stream(const STREAM_LAYOUT_ENTRY *stream)
2176 return stream->StreamIdentifierLength == 24 &&
2177 !wmemcmp(stream->StreamIdentifier, L"::$OBJECT_ID", 12);
2181 * If the specified STREAM_LAYOUT_ENTRY represents a DATA stream as opposed to
2182 * some other type of NTFS stream such as a STANDARD_INFORMATION stream, return
2183 * true and set *stream_name_ret and *stream_name_nchars_ret to specify just the
2184 * stream name. For example, ":foo:$DATA" would become "foo" with length 3
2185 * characters. Otherwise return false.
2188 use_stream(const FILE_LAYOUT_ENTRY *file, const STREAM_LAYOUT_ENTRY *stream,
2189 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
2191 const wchar_t *stream_name;
2192 size_t stream_name_nchars;
2194 if (stream->StreamIdentifierLength == 0) {
2195 /* The unnamed data stream may be given as an empty string
2196 * rather than as "::$DATA". Handle it both ways. */
2198 stream_name_nchars = 0;
2199 } else if (!get_data_stream_name(stream->StreamIdentifier,
2200 stream->StreamIdentifierLength / 2,
2201 &stream_name, &stream_name_nchars))
2204 /* Skip the unnamed data stream for directories. */
2205 if (stream_name_nchars == 0 &&
2206 (file->FileAttributes & FILE_ATTRIBUTE_DIRECTORY))
2209 *stream_name_ret = stream_name;
2210 *stream_name_nchars_ret = stream_name_nchars;
2214 /* Validate the STREAM_LAYOUT_ENTRYs of the specified file and compute the total
2215 * length in bytes of the ntfs_stream structures needed to hold the stream
2216 * information. In addition, set *have_object_id_ret=true if the file has an
2217 * object ID stream. */
2219 validate_streams_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2220 size_t *total_length_ret,
2221 bool *have_object_id_ret)
2223 const STREAM_LAYOUT_ENTRY *stream =
2224 (const void *)file + file->FirstStreamOffset;
2227 const wchar_t *name;
2230 if (unlikely(!is_valid_stream_entry(stream))) {
2231 WARNING("Invalid STREAM_LAYOUT_ENTRY! "
2232 "FileReferenceNumber=0x%016"PRIx64", "
2233 "StreamIdentifierLength=%"PRIu32", "
2234 "StreamIdentifier=%.*ls",
2235 file->FileReferenceNumber,
2236 stream->StreamIdentifierLength,
2237 (int)(stream->StreamIdentifierLength / 2),
2238 stream->StreamIdentifier);
2239 return WIMLIB_ERR_UNSUPPORTED;
2242 if (use_stream(file, stream, &name, &name_nchars)) {
2243 total += ALIGN(sizeof(struct ntfs_stream) +
2244 (name_nchars + 1) * sizeof(wchar_t), 8);
2245 } else if (is_object_id_stream(stream)) {
2246 *have_object_id_ret = true;
2248 if (stream->NextStreamOffset == 0)
2250 stream = (const void *)stream + stream->NextStreamOffset;
2253 *total_length_ret = total;
2258 load_name_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2261 const FILE_LAYOUT_NAME_ENTRY *name =
2262 (const void *)file + file->FirstNameOffset;
2264 struct ntfs_dentry *nd = p;
2265 /* Note that a name may be just a short (DOS) name, just a long
2266 * name, or both a short name and a long name. If there is a
2267 * short name, one name should also be marked as "primary" to
2268 * indicate which long name the short name is associated with.
2269 * Also, there should be at most one short name per inode. */
2270 if (name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) {
2271 memcpy(ni->short_name,
2272 name->FileName, name->FileNameLength);
2273 ni->short_name[name->FileNameLength / 2] = L'\0';
2275 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2277 nd->offset_from_inode = (u8 *)nd - (u8 *)ni;
2278 nd->is_primary = ((name->Flags &
2279 FILE_LAYOUT_NAME_ENTRY_PRIMARY) != 0);
2280 nd->parent_ino = name->ParentFileReferenceNumber;
2281 memcpy(nd->name, name->FileName, name->FileNameLength);
2282 nd->name[name->FileNameLength / 2] = L'\0';
2283 p += ALIGN(sizeof(struct ntfs_dentry) +
2284 name->FileNameLength + sizeof(wchar_t), 8);
2286 if (name->NextNameOffset == 0)
2288 name = (const void *)name + name->NextNameOffset;
2294 load_starting_lcn(const STREAM_LAYOUT_ENTRY *stream)
2296 const STREAM_EXTENT_ENTRY *entry;
2298 if (stream->ExtentInformationOffset == 0)
2301 entry = (const void *)stream + stream->ExtentInformationOffset;
2303 if (!(entry->Flags & STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS))
2306 return extract_starting_lcn(&entry->ExtentInformation.RetrievalPointers);
2310 load_stream_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2313 const STREAM_LAYOUT_ENTRY *stream =
2314 (const void *)file + file->FirstStreamOffset;
2315 const u32 first_stream_offset = (const u8 *)p - (const u8 *)ni;
2317 struct ntfs_stream *ns = p;
2318 const wchar_t *name;
2321 if (use_stream(file, stream, &name, &name_nchars)) {
2322 ni->first_stream_offset = first_stream_offset;
2324 if (name_nchars == 0)
2325 ni->starting_lcn = load_starting_lcn(stream);
2326 ns->size = stream->EndOfFile;
2327 wmemcpy(ns->name, name, name_nchars);
2328 ns->name[name_nchars] = L'\0';
2329 p += ALIGN(sizeof(struct ntfs_stream) +
2330 (name_nchars + 1) * sizeof(wchar_t), 8);
2332 if (stream->NextStreamOffset == 0)
2334 stream = (const void *)stream + stream->NextStreamOffset;
2339 /* Process the information for a file given by FSCTL_QUERY_FILE_LAYOUT. */
2341 load_one_file(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode_map *inode_map)
2343 const FILE_LAYOUT_INFO_ENTRY *info =
2344 (const void *)file + file->ExtraInfoOffset;
2346 struct ntfs_inode *ni;
2350 bool have_object_id = false;
2352 inode_size = ALIGN(sizeof(struct ntfs_inode), 8);
2354 /* The root file should have no names, and all other files should have
2355 * at least one name. But just in case, we ignore the names of the root
2356 * file, and we ignore any non-root file with no names. */
2357 if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber)) {
2358 if (file->FirstNameOffset == 0)
2360 ret = validate_names_and_compute_total_length(file, &n);
2366 if (file_has_streams(file)) {
2367 ret = validate_streams_and_compute_total_length(file, &n,
2374 /* To save memory, we allocate the ntfs_dentry's and ntfs_stream's in
2375 * the same memory block as their ntfs_inode. */
2376 ni = CALLOC(1, inode_size);
2378 return WIMLIB_ERR_NOMEM;
2380 ni->ino = file->FileReferenceNumber;
2381 ni->attributes = info->BasicInformation.FileAttributes;
2382 ni->creation_time = info->BasicInformation.CreationTime;
2383 ni->last_write_time = info->BasicInformation.LastWriteTime;
2384 ni->last_access_time = info->BasicInformation.LastAccessTime;
2385 ni->security_id = info->SecurityId;
2386 ni->have_object_id = have_object_id;
2388 p = FIRST_DENTRY(ni);
2390 if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber))
2391 p = load_name_information(file, ni, p);
2393 if (file_has_streams(file))
2394 p = load_stream_information(file, ni, p);
2396 wimlib_assert((u8 *)p - (u8 *)ni == inode_size);
2398 ntfs_inode_map_add_inode(inode_map, ni);
2403 * Quickly find all files on an NTFS volume by using FSCTL_QUERY_FILE_LAYOUT to
2404 * scan the MFT. The NTFS volume is specified by the NT namespace path @path.
2405 * For each file, allocate an 'ntfs_inode' structure for each file and add it to
2406 * 'inode_map' keyed by inode number. Include NTFS special files such as
2407 * $Bitmap (they will be removed later).
2410 load_files_from_mft(const wchar_t *path, struct ntfs_inode_map *inode_map)
2413 QUERY_FILE_LAYOUT_INPUT in = (QUERY_FILE_LAYOUT_INPUT) {
2415 .Flags = QUERY_FILE_LAYOUT_RESTART |
2416 QUERY_FILE_LAYOUT_INCLUDE_NAMES |
2417 QUERY_FILE_LAYOUT_INCLUDE_STREAMS |
2418 QUERY_FILE_LAYOUT_INCLUDE_EXTENTS |
2419 QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO |
2420 QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED,
2421 .FilterType = QUERY_FILE_LAYOUT_FILTER_TYPE_NONE,
2423 size_t outsize = 32768;
2424 QUERY_FILE_LAYOUT_OUTPUT *out = NULL;
2428 status = winnt_open(path, wcslen(path),
2429 FILE_READ_DATA | FILE_READ_ATTRIBUTES, &h);
2430 if (!NT_SUCCESS(status)) {
2431 ret = -1; /* Silently try standard recursive scan instead */
2436 /* Allocate a buffer for the output of the ioctl. */
2437 out = MALLOC(outsize);
2439 ret = WIMLIB_ERR_NOMEM;
2443 /* Execute FSCTL_QUERY_FILE_LAYOUT until it fails. */
2444 while (NT_SUCCESS(status = winnt_fsctl(h,
2445 FSCTL_QUERY_FILE_LAYOUT,
2447 out, outsize, NULL)))
2449 const FILE_LAYOUT_ENTRY *file =
2450 (const void *)out + out->FirstFileOffset;
2452 ret = load_one_file(file, inode_map);
2455 if (file->NextFileOffset == 0)
2457 file = (const void *)file + file->NextFileOffset;
2459 in.Flags &= ~QUERY_FILE_LAYOUT_RESTART;
2462 /* Enlarge the buffer if needed. */
2463 if (status != STATUS_BUFFER_TOO_SMALL)
2469 /* Normally, FSCTL_QUERY_FILE_LAYOUT fails with STATUS_END_OF_FILE after
2470 * all files have been enumerated. */
2471 if (status != STATUS_END_OF_FILE) {
2472 if (status == STATUS_INVALID_DEVICE_REQUEST /* old OS */ ||
2473 status == STATUS_INVALID_PARAMETER /* not root directory */ ) {
2474 /* Silently try standard recursive scan instead */
2478 L"Error enumerating files on volume \"%ls\"",
2480 /* Try standard recursive scan instead */
2481 ret = WIMLIB_ERR_UNSUPPORTED;
2492 /* Build the list of child dentries for each inode in @map. This is done by
2493 * iterating through each name of each inode and adding it to its parent's
2494 * children list. Note that every name should have a parent, i.e. should belong
2495 * to some directory. The root directory does not have any names. */
2497 build_children_lists(struct ntfs_inode_map *map, struct ntfs_inode **root_ret)
2499 struct ntfs_inode *ni;
2501 avl_tree_for_each_in_order(ni, map->root, struct ntfs_inode, index_node)
2503 struct ntfs_dentry *nd;
2506 if (NTFS_IS_ROOT_FILE(ni->ino)) {
2511 n = ni->num_aliases;
2512 nd = FIRST_DENTRY(ni);
2514 struct ntfs_inode *parent;
2516 parent = ntfs_inode_map_lookup(map, nd->parent_ino);
2517 if (unlikely(!parent)) {
2518 ERROR("Parent inode 0x%016"PRIx64" of"
2519 "directory entry \"%ls\" (inode "
2520 "0x%016"PRIx64") was missing from the "
2522 nd->parent_ino, nd->name, ni->ino);
2523 return WIMLIB_ERR_UNSUPPORTED;
2525 nd->next_child = parent->first_child;
2526 parent->first_child = nd;
2529 nd = NEXT_DENTRY(nd);
2535 struct security_map_node {
2536 struct avl_tree_node index_node;
2537 u32 disk_security_id;
2538 u32 wim_security_id;
2541 /* Map from disk security IDs to WIM security IDs */
2542 struct security_map {
2543 struct avl_tree_node *root;
2546 #define SECURITY_MAP_NODE(node) \
2547 avl_tree_entry((node), struct security_map_node, index_node)
2550 _avl_cmp_security_map_nodes(const struct avl_tree_node *node1,
2551 const struct avl_tree_node *node2)
2553 return cmp_u32(SECURITY_MAP_NODE(node1)->disk_security_id,
2554 SECURITY_MAP_NODE(node2)->disk_security_id);
2558 security_map_lookup(struct security_map *map, u32 disk_security_id)
2560 struct security_map_node tmp;
2561 const struct avl_tree_node *res;
2563 if (disk_security_id == 0) /* No on-disk security ID; uncacheable */
2566 tmp.disk_security_id = disk_security_id;
2567 res = avl_tree_lookup_node(map->root, &tmp.index_node,
2568 _avl_cmp_security_map_nodes);
2571 return SECURITY_MAP_NODE(res)->wim_security_id;
2575 security_map_insert(struct security_map *map, u32 disk_security_id,
2576 u32 wim_security_id)
2578 struct security_map_node *node;
2580 if (disk_security_id == 0) /* No on-disk security ID; uncacheable */
2583 node = MALLOC(sizeof(*node));
2585 return WIMLIB_ERR_NOMEM;
2587 node->disk_security_id = disk_security_id;
2588 node->wim_security_id = wim_security_id;
2589 avl_tree_insert(&map->root, &node->index_node,
2590 _avl_cmp_security_map_nodes);
2595 security_map_destroy(struct security_map *map)
2597 struct security_map_node *node;
2599 avl_tree_for_each_in_postorder(node, map->root,
2600 struct security_map_node, index_node)
2605 * Turn our temporary NTFS structures into the final WIM structures:
2607 * ntfs_inode => wim_inode
2608 * ntfs_dentry => wim_dentry
2609 * ntfs_stream => wim_inode_stream
2611 * This also handles things such as exclusions and issuing progress messages.
2612 * It's similar to winnt_build_dentry_tree_recursive(), but this is much faster
2613 * because almost all information we need is already loaded in memory in the
2614 * ntfs_* structures. However, in some cases we still fall back to
2615 * winnt_build_dentry_tree_recursive() and/or opening the file.
2618 generate_wim_structures_recursive(struct wim_dentry **root_ret,
2619 wchar_t *path, size_t path_nchars,
2620 const wchar_t *filename, bool is_primary_name,
2621 struct ntfs_inode *ni,
2622 struct winnt_scan_ctx *ctx,
2623 struct ntfs_inode_map *inode_map,
2624 struct security_map *security_map)
2627 struct wim_dentry *root = NULL;
2628 struct wim_inode *inode = NULL;
2629 const struct ntfs_stream *ns;
2631 /* Completely ignore NTFS special files. */
2632 if (NTFS_IS_SPECIAL_FILE(ni->ino))
2635 /* Fall back to a recursive scan for unhandled cases. Reparse points,
2636 * in particular, can't be properly handled here because a commonly used
2637 * filter driver (WOF) hides reparse points from regular filesystem APIs
2638 * but not from FSCTL_QUERY_FILE_LAYOUT. */
2639 if (ni->attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
2640 FILE_ATTRIBUTE_ENCRYPTED) ||
2643 ret = winnt_build_dentry_tree_recursive(&root,
2654 /* Test for exclusion based on path. */
2655 ret = try_exclude(path, ctx->params);
2656 if (unlikely(ret < 0)) /* Excluded? */
2658 if (unlikely(ret > 0)) /* Error? */
2661 /* Create the WIM dentry and possibly a new WIM inode */
2662 ret = inode_table_new_dentry(ctx->params->inode_table, filename,
2663 ni->ino, ctx->params->capture_root_dev,
2668 inode = root->d_inode;
2670 /* Set the short name if needed. */
2671 if (is_primary_name && *ni->short_name) {
2672 size_t nbytes = wcslen(ni->short_name) * sizeof(wchar_t);
2673 root->d_short_name = memdup(ni->short_name,
2674 nbytes + sizeof(wchar_t));
2675 if (!root->d_short_name) {
2676 ret = WIMLIB_ERR_NOMEM;
2679 root->d_short_name_nbytes = nbytes;
2682 if (inode->i_nlink > 1) { /* Already seen this inode? */
2687 /* The file attributes and timestamps were cached from the MFT. */
2688 inode->i_attributes = ni->attributes;
2689 inode->i_creation_time = ni->creation_time;
2690 inode->i_last_write_time = ni->last_write_time;
2691 inode->i_last_access_time = ni->last_access_time;
2693 /* Set the security descriptor if needed. */
2694 if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)) {
2695 /* Look up the WIM security ID that corresponds to the on-disk
2697 s32 wim_security_id =
2698 security_map_lookup(security_map, ni->security_id);
2699 if (likely(wim_security_id >= 0)) {
2700 /* The mapping for this security ID is already cached.*/
2701 inode->i_security_id = wim_security_id;
2706 /* Create a mapping for this security ID and insert it
2707 * into the security map. */
2709 status = winnt_open(path, path_nchars,
2711 ACCESS_SYSTEM_SECURITY, &h);
2712 if (!NT_SUCCESS(status)) {
2713 winnt_error(status, L"Can't open \"%ls\" to "
2714 "read security descriptor",
2715 printable_path(path));
2716 ret = WIMLIB_ERR_OPEN;
2719 ret = winnt_load_security_descriptor(h, inode, path, ctx);
2724 ret = security_map_insert(security_map, ni->security_id,
2725 inode->i_security_id);
2731 /* Add data streams based on the cached information from the MFT. */
2732 ns = FIRST_STREAM(ni);
2733 for (u32 i = 0; i < ni->num_streams; i++) {
2734 struct windows_file *windows_file;
2736 /* Reference the stream by path if it's a named data stream, or
2737 * if the volume doesn't support "open by file ID", or if the
2738 * application hasn't explicitly opted in to "open by file ID".
2739 * Otherwise, only save the inode number (file ID). */
2741 !(ctx->vol_flags & FILE_SUPPORTS_OPEN_BY_FILE_ID) ||
2742 !(ctx->params->add_flags & WIMLIB_ADD_FLAG_FILE_PATHS_UNNEEDED))
2744 windows_file = alloc_windows_file(path,
2751 windows_file = alloc_windows_file_for_file_id(ni->ino,
2753 ctx->params->capture_root_nchars + 1,
2757 ret = add_stream(inode, windows_file, ns->size,
2758 STREAM_TYPE_DATA, ns->name,
2759 ctx->params->unhashed_blobs);
2762 ns = NEXT_STREAM(ns);
2765 set_sort_key(inode, ni->starting_lcn);
2767 /* If processing a directory, then recurse to its children. In this
2768 * version there is no need to go to disk, as we already have the list
2769 * of children cached from the MFT. */
2770 if (inode_is_directory(inode)) {
2771 const struct ntfs_dentry *nd = ni->first_child;
2773 while (nd != NULL) {
2774 const size_t name_len = wcslen(nd->name);
2775 wchar_t *p = path + path_nchars;
2776 struct wim_dentry *child;
2777 const struct ntfs_dentry *next = nd->next_child;
2779 if (*(p - 1) != L'\\')
2781 p = wmempcpy(p, nd->name, name_len);
2784 ret = generate_wim_structures_recursive(
2790 (void *)nd - nd->offset_from_inode,
2795 path[path_nchars] = L'\0';
2800 attach_scanned_tree(root, child, ctx->params->blob_table);
2806 ctx->params->progress.scan.cur_path = path;
2808 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_OK, inode);
2810 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
2812 if (--ni->num_aliases == 0) {
2813 /* Memory usage optimization: when we don't need the ntfs_inode
2814 * (and its names and streams) anymore, free it. */
2815 ntfs_inode_map_remove(inode_map, ni);
2817 if (unlikely(ret)) {
2818 free_dentry_tree(root, ctx->params->blob_table);
2826 winnt_build_dentry_tree_fast(struct wim_dentry **root_ret, wchar_t *path,
2827 size_t path_nchars, struct winnt_scan_ctx *ctx)
2829 struct ntfs_inode_map inode_map = { .root = NULL };
2830 struct security_map security_map = { .root = NULL };
2831 struct ntfs_inode *root = NULL;
2835 adjust_path = (path[path_nchars - 1] == L'\\');
2837 path[path_nchars - 1] = L'\0';
2839 ret = load_files_from_mft(path, &inode_map);
2842 path[path_nchars - 1] = L'\\';
2847 ret = build_children_lists(&inode_map, &root);
2852 ERROR("The MFT listing for volume \"%ls\" did not include a "
2853 "root directory!", path);
2854 ret = WIMLIB_ERR_UNSUPPORTED;
2858 root->num_aliases = 1;
2860 ret = generate_wim_structures_recursive(root_ret, path, path_nchars,
2861 L"", false, root, ctx,
2862 &inode_map, &security_map);
2864 ntfs_inode_map_destroy(&inode_map);
2865 security_map_destroy(&security_map);
2869 #endif /* ENABLE_FAST_MFT_SCAN */
2871 /*----------------------------------------------------------------------------*
2872 * Entry point for directory tree scans on Windows *
2873 *----------------------------------------------------------------------------*/
2875 #define WINDOWS_NT_MAX_PATH 32768
2878 win32_build_dentry_tree(struct wim_dentry **root_ret,
2879 const wchar_t *root_disk_path,
2880 struct scan_params *params)
2882 wchar_t *path = NULL;
2883 struct winnt_scan_ctx ctx = { .params = params };
2884 UNICODE_STRING ntpath;
2885 size_t ntpath_nchars;
2890 /* WARNING: There is no check for overflow later when this buffer is
2891 * being used! But it's as long as the maximum path length understood
2892 * by Windows NT (which is NOT the same as MAX_PATH). */
2893 path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
2895 return WIMLIB_ERR_NOMEM;
2897 if (params->add_flags & WIMLIB_ADD_FLAG_SNAPSHOT)
2898 ret = vss_create_snapshot(root_disk_path, &ntpath, &ctx.snapshot);
2900 ret = win32_path_to_nt_path(root_disk_path, &ntpath);
2905 if (ntpath.Length < 4 * sizeof(wchar_t) ||
2906 ntpath.Length > WINDOWS_NT_MAX_PATH * sizeof(wchar_t) ||
2907 wmemcmp(ntpath.Buffer, L"\\??\\", 4))
2909 ERROR("\"%ls\": unrecognized path format", root_disk_path);
2910 ret = WIMLIB_ERR_INVALID_PARAM;
2912 ntpath_nchars = ntpath.Length / sizeof(wchar_t);
2913 wmemcpy(path, ntpath.Buffer, ntpath_nchars);
2914 path[ntpath_nchars] = L'\0';
2916 params->capture_root_nchars = ntpath_nchars;
2917 if (path[ntpath_nchars - 1] == L'\\')
2918 params->capture_root_nchars--;
2921 HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
2925 status = winnt_open(path, ntpath_nchars, FILE_READ_ATTRIBUTES, &h);
2926 if (!NT_SUCCESS(status)) {
2927 winnt_error(status, L"Can't open \"%ls\"", printable_path(path));
2928 if (status == STATUS_FVE_LOCKED_VOLUME)
2929 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
2931 ret = WIMLIB_ERR_OPEN;
2935 get_volume_information(h, path, &ctx);
2939 #ifdef ENABLE_FAST_MFT_SCAN
2940 if (ctx.is_ntfs && !_wgetenv(L"WIMLIB_DISABLE_QUERY_FILE_LAYOUT")) {
2941 ret = winnt_build_dentry_tree_fast(root_ret, path,
2942 ntpath_nchars, &ctx);
2943 if (ret >= 0 && ret != WIMLIB_ERR_UNSUPPORTED)
2946 WARNING("A problem occurred during the fast MFT scan.\n"
2947 " Falling back to the standard "
2948 "recursive directory tree scan.");
2952 ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
2953 path, ntpath_nchars,
2954 path, ntpath_nchars,
2957 vss_put_snapshot(ctx.snapshot);
2960 winnt_do_scan_warnings(root_disk_path, &ctx);
2964 #endif /* __WIN32__ */