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 (params->add_flags & WIMLIB_ADD_FLAG_RPFIX) {
1054 ret = winnt_try_rpfix(&rpbuf, &rpbuflen, full_path, params);
1055 if (ret == RP_FIXED)
1056 inode->i_rp_flags &= ~WIM_RP_FLAG_NOT_FIXED;
1061 inode->i_reparse_tag = le32_to_cpu(rpbuf.rptag);
1062 inode->i_rp_reserved = le16_to_cpu(rpbuf.rpreserved);
1064 if (!inode_add_stream_with_data(inode,
1065 STREAM_TYPE_REPARSE_POINT,
1068 rpbuflen - REPARSE_DATA_OFFSET,
1069 params->blob_table))
1070 return WIMLIB_ERR_NOMEM;
1076 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
1079 *(u64*)_size_ret += len;
1080 return ERROR_SUCCESS;
1084 win32_get_encrypted_file_size(const wchar_t *path, bool is_dir, u64 *size_ret)
1092 flags |= CREATE_FOR_DIR;
1094 err = OpenEncryptedFileRaw(path, flags, &file_ctx);
1095 if (err != ERROR_SUCCESS) {
1097 L"Failed to open encrypted file \"%ls\" for raw read",
1098 printable_path(path));
1099 return WIMLIB_ERR_OPEN;
1102 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
1103 size_ret, file_ctx);
1104 if (err != ERROR_SUCCESS) {
1106 L"Failed to read raw encrypted data from \"%ls\"",
1107 printable_path(path));
1108 ret = WIMLIB_ERR_READ;
1112 CloseEncryptedFileRaw(file_ctx);
1117 winnt_scan_efsrpc_raw_data(struct wim_inode *inode,
1118 wchar_t *path, size_t path_nchars,
1119 struct winnt_scan_ctx *ctx)
1121 const bool is_dir = (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY);
1122 struct windows_file *windows_file;
1126 /* OpenEncryptedFileRaw() expects a Win32 name. */
1127 wimlib_assert(!wmemcmp(path, L"\\??\\", 4));
1130 ret = win32_get_encrypted_file_size(path, is_dir, &size);
1134 /* Empty EFSRPC data does not make sense */
1135 wimlib_assert(size != 0);
1137 windows_file = alloc_windows_file(path, path_nchars, NULL, 0,
1138 ctx->snapshot, true);
1139 ret = add_stream(inode, windows_file, size, STREAM_TYPE_EFSRPC_RAW_DATA,
1140 NO_STREAM_NAME, ctx->params->unhashed_blobs);
1147 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1148 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
1150 const wchar_t *sep, *type, *end;
1152 /* The stream name should be returned as :NAME:TYPE */
1153 if (raw_stream_name_nchars < 1)
1155 if (raw_stream_name[0] != L':')
1159 raw_stream_name_nchars--;
1161 end = raw_stream_name + raw_stream_name_nchars;
1163 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
1168 if (end - type != 5)
1171 if (wmemcmp(type, L"$DATA", 5))
1174 *stream_name_ret = raw_stream_name;
1175 *stream_name_nchars_ret = sep - raw_stream_name;
1180 winnt_scan_data_stream(const wchar_t *path, size_t path_nchars,
1181 wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1182 u64 stream_size, struct wim_inode *inode,
1183 struct winnt_scan_ctx *ctx)
1185 wchar_t *stream_name;
1186 size_t stream_name_nchars;
1187 struct windows_file *windows_file;
1189 /* Given the raw stream name (which is something like
1190 * :streamname:$DATA), extract just the stream name part (streamname).
1191 * Ignore any non-$DATA streams. */
1192 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
1193 (const wchar_t **)&stream_name,
1194 &stream_name_nchars))
1197 stream_name[stream_name_nchars] = L'\0';
1199 windows_file = alloc_windows_file(path, path_nchars,
1200 stream_name, stream_name_nchars,
1201 ctx->snapshot, false);
1202 return add_stream(inode, windows_file, stream_size, STREAM_TYPE_DATA,
1203 stream_name, ctx->params->unhashed_blobs);
1207 * Load information about the data streams of an open file into a WIM inode.
1209 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
1210 * and FindNextStream(). This is done for two reasons:
1212 * - FindFirstStream() opens its own handle to the file or directory and
1213 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
1214 * causing access denied errors on certain files (even when running as the
1216 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
1217 * and later, whereas the stream support in NtQueryInformationFile() was
1218 * already present in Windows XP.
1220 static noinline_for_stack int
1221 winnt_scan_data_streams(HANDLE h, const wchar_t *path, size_t path_nchars,
1222 struct wim_inode *inode, u64 file_size,
1223 struct winnt_scan_ctx *ctx)
1226 u8 _buf[4096] _aligned_attribute(8);
1229 IO_STATUS_BLOCK iosb;
1231 FILE_STREAM_INFORMATION *info;
1234 bufsize = sizeof(_buf);
1236 if (!(ctx->vol_flags & FILE_NAMED_STREAMS))
1239 /* Get a buffer containing the stream information. */
1240 while (!NT_SUCCESS(status = NtQueryInformationFile(h,
1244 FileStreamInformation)))
1248 case STATUS_BUFFER_OVERFLOW:
1254 newbuf = MALLOC(bufsize);
1256 newbuf = REALLOC(buf, bufsize);
1258 ret = WIMLIB_ERR_NOMEM;
1264 case STATUS_NOT_IMPLEMENTED:
1265 case STATUS_NOT_SUPPORTED:
1266 case STATUS_INVALID_INFO_CLASS:
1270 L"\"%ls\": Failed to query stream information",
1271 printable_path(path));
1272 ret = WIMLIB_ERR_READ;
1277 if (iosb.Information == 0) {
1278 /* No stream information. */
1283 /* Parse one or more stream information structures. */
1284 info = (FILE_STREAM_INFORMATION *)buf;
1286 /* Load the stream information. */
1287 ret = winnt_scan_data_stream(path, path_nchars,
1289 info->StreamNameLength / 2,
1290 info->StreamSize.QuadPart,
1295 if (info->NextEntryOffset == 0) {
1296 /* No more stream information. */
1299 /* Advance to next stream information. */
1300 info = (FILE_STREAM_INFORMATION *)
1301 ((u8 *)info + info->NextEntryOffset);
1307 /* The volume does not support named streams. Only capture the unnamed
1309 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1310 FILE_ATTRIBUTE_REPARSE_POINT))
1317 wchar_t stream_name[] = L"::$DATA";
1318 ret = winnt_scan_data_stream(path, path_nchars, stream_name, 7,
1319 file_size, inode, ctx);
1322 /* Free buffer if allocated on heap. */
1323 if (unlikely(buf != _buf))
1329 extract_starting_lcn(const RETRIEVAL_POINTERS_BUFFER *extents)
1331 if (extents->ExtentCount < 1)
1334 return extents->Extents[0].Lcn.QuadPart;
1337 static noinline_for_stack u64
1338 get_sort_key(HANDLE h)
1340 STARTING_VCN_INPUT_BUFFER in = { .StartingVcn.QuadPart = 0 };
1341 RETRIEVAL_POINTERS_BUFFER out;
1343 if (!NT_SUCCESS(winnt_fsctl(h, FSCTL_GET_RETRIEVAL_POINTERS,
1344 &in, sizeof(in), &out, sizeof(out), NULL)))
1347 return extract_starting_lcn(&out);
1351 set_sort_key(struct wim_inode *inode, u64 sort_key)
1353 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1354 struct wim_inode_stream *strm = &inode->i_streams[i];
1355 struct blob_descriptor *blob = stream_blob_resolved(strm);
1356 if (blob && blob->blob_location == BLOB_IN_WINDOWS_FILE)
1357 blob->windows_file->sort_key = sort_key;
1362 should_try_to_use_wimboot_hash(const struct wim_inode *inode,
1363 const struct winnt_scan_ctx *ctx,
1364 const struct scan_params *params)
1366 /* Directories and encrypted files aren't valid for external backing. */
1367 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1368 FILE_ATTRIBUTE_ENCRYPTED))
1371 /* If the file is a reparse point, then try the hash fixup if it's a WOF
1372 * reparse point and we're in WIMBOOT mode. Otherwise, try the hash
1373 * fixup if WOF may be attached. */
1374 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1375 return (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_WOF) &&
1376 (params->add_flags & WIMLIB_ADD_FLAG_WIMBOOT);
1377 return !ctx->wof_not_attached;
1381 * This function implements an optimization for capturing files from a
1382 * filesystem with a backing WIM(s). If a file is WIM-backed, then we can
1383 * retrieve the SHA-1 message digest of its original contents from its reparse
1384 * point. This may eliminate the need to read the file's data and/or allow the
1385 * file's data to be immediately deduplicated with existing data in the WIM.
1387 * If WOF is attached, then this function is merely an optimization, but
1388 * potentially a very effective one. If WOF is detached, then this function
1389 * really causes WIM-backed files to be, effectively, automatically
1390 * "dereferenced" when possible; the unnamed data stream is updated to reference
1391 * the original contents and the reparse point is removed.
1393 * This function returns 0 if the fixup succeeded or was intentionally not
1394 * executed. Otherwise it returns an error code.
1396 static noinline_for_stack int
1397 try_to_use_wimboot_hash(HANDLE h, struct wim_inode *inode,
1398 struct winnt_scan_ctx *ctx, const wchar_t *full_path)
1400 struct blob_table *blob_table = ctx->params->blob_table;
1401 struct wim_inode_stream *reparse_strm = NULL;
1402 struct wim_inode_stream *strm;
1403 struct blob_descriptor *blob;
1404 u8 hash[SHA1_HASH_SIZE];
1407 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1408 struct reparse_buffer_disk rpbuf;
1410 struct wof_external_info wof_info;
1411 struct wim_provider_rpdata wim_info;
1412 } *rpdata = (void *)rpbuf.rpdata;
1413 struct blob_descriptor *reparse_blob;
1415 /* The file has a WOF reparse point, so WOF must be detached.
1416 * We can read the reparse point directly. */
1417 ctx->wof_not_attached = true;
1418 reparse_strm = inode_get_unnamed_stream(inode, STREAM_TYPE_REPARSE_POINT);
1419 reparse_blob = stream_blob_resolved(reparse_strm);
1421 if (!reparse_blob || reparse_blob->size < sizeof(*rpdata))
1422 return 0; /* Not a WIM-backed file */
1424 ret = read_blob_into_buf(reparse_blob, rpdata);
1428 if (rpdata->wof_info.version != WOF_CURRENT_VERSION ||
1429 rpdata->wof_info.provider != WOF_PROVIDER_WIM ||
1430 rpdata->wim_info.version != 2)
1431 return 0; /* Not a WIM-backed file */
1433 /* Okay, this is a WIM backed file. Get its SHA-1 hash. */
1434 copy_hash(hash, rpdata->wim_info.unnamed_data_stream_hash);
1437 struct wof_external_info wof_info;
1438 struct wim_provider_external_info wim_info;
1442 /* WOF may be attached. Try reading this file's external
1444 status = winnt_fsctl(h, FSCTL_GET_EXTERNAL_BACKING,
1445 NULL, 0, &out, sizeof(out), NULL);
1447 /* Is WOF not attached? */
1448 if (status == STATUS_INVALID_DEVICE_REQUEST ||
1449 status == STATUS_NOT_SUPPORTED) {
1450 ctx->wof_not_attached = true;
1454 /* Is this file not externally backed? */
1455 if (status == STATUS_OBJECT_NOT_EXTERNALLY_BACKED)
1458 /* Does this file have an unknown type of external backing that
1459 * needed a larger information buffer? */
1460 if (status == STATUS_BUFFER_TOO_SMALL)
1463 /* Was there some other failure? */
1464 if (status != STATUS_SUCCESS) {
1466 L"\"%ls\": FSCTL_GET_EXTERNAL_BACKING failed",
1468 return WIMLIB_ERR_STAT;
1471 /* Is this file backed by a WIM? */
1472 if (out.wof_info.version != WOF_CURRENT_VERSION ||
1473 out.wof_info.provider != WOF_PROVIDER_WIM ||
1474 out.wim_info.version != WIM_PROVIDER_CURRENT_VERSION)
1477 /* Okay, this is a WIM backed file. Get its SHA-1 hash. */
1478 copy_hash(hash, out.wim_info.unnamed_data_stream_hash);
1481 /* If the file's unnamed data stream is nonempty, then fill in its hash
1482 * and deduplicate it if possible.
1484 * With WOF detached, we require that the blob *must* de-duplicable for
1485 * any action can be taken, since without WOF we can't fall back to
1486 * getting the "dereferenced" data by reading the stream (the real
1487 * stream is sparse and contains all zeroes). */
1488 strm = inode_get_unnamed_data_stream(inode);
1489 if (strm && (blob = stream_blob_resolved(strm))) {
1490 struct blob_descriptor **back_ptr;
1492 if (reparse_strm && !lookup_blob(blob_table, hash))
1494 back_ptr = retrieve_pointer_to_unhashed_blob(blob);
1495 copy_hash(blob->hash, hash);
1496 if (after_blob_hashed(blob, back_ptr, blob_table) != blob)
1497 free_blob_descriptor(blob);
1500 /* Remove the reparse point, if present. */
1502 inode_remove_stream(inode, reparse_strm, blob_table);
1503 inode->i_attributes &= ~(FILE_ATTRIBUTE_REPARSE_POINT |
1504 FILE_ATTRIBUTE_SPARSE_FILE);
1505 if (inode->i_attributes == 0)
1506 inode->i_attributes = FILE_ATTRIBUTE_NORMAL;
1516 u64 last_write_time;
1517 u64 last_access_time;
1522 static noinline_for_stack NTSTATUS
1523 get_file_info(HANDLE h, struct file_info *info)
1525 IO_STATUS_BLOCK iosb;
1527 FILE_ALL_INFORMATION all_info;
1529 status = NtQueryInformationFile(h, &iosb, &all_info, sizeof(all_info),
1530 FileAllInformation);
1532 if (unlikely(!NT_SUCCESS(status) && status != STATUS_BUFFER_OVERFLOW))
1535 info->attributes = all_info.BasicInformation.FileAttributes;
1536 info->num_links = all_info.StandardInformation.NumberOfLinks;
1537 info->creation_time = all_info.BasicInformation.CreationTime.QuadPart;
1538 info->last_write_time = all_info.BasicInformation.LastWriteTime.QuadPart;
1539 info->last_access_time = all_info.BasicInformation.LastAccessTime.QuadPart;
1540 info->ino = all_info.InternalInformation.IndexNumber.QuadPart;
1541 info->end_of_file = all_info.StandardInformation.EndOfFile.QuadPart;
1542 return STATUS_SUCCESS;
1546 get_volume_information(HANDLE h, const wchar_t *full_path,
1547 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(full_path));
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(full_path));
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(full_path));
1595 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1598 size_t full_path_nchars,
1599 wchar_t *relative_path,
1600 size_t relative_path_nchars,
1601 const wchar_t *filename,
1602 struct winnt_scan_ctx *ctx)
1604 struct wim_dentry *root = NULL;
1605 struct wim_inode *inode = NULL;
1609 struct file_info file_info;
1612 ret = try_exclude(full_path, ctx->params);
1613 if (unlikely(ret < 0)) /* Excluded? */
1615 if (unlikely(ret > 0)) /* Error? */
1618 /* Open the file with permission to read metadata. Although we will
1619 * later need a handle with FILE_LIST_DIRECTORY permission (or,
1620 * equivalently, FILE_READ_DATA; they're the same numeric value) if the
1621 * file is a directory, it can significantly slow things down to request
1622 * this permission on all nondirectories. Perhaps it causes Windows to
1623 * start prefetching the file contents... */
1624 status = winnt_openat(cur_dir, relative_path, relative_path_nchars,
1625 FILE_READ_ATTRIBUTES | READ_CONTROL |
1626 ACCESS_SYSTEM_SECURITY,
1628 if (unlikely(!NT_SUCCESS(status))) {
1629 if (status == STATUS_DELETE_PENDING) {
1630 WARNING("\"%ls\": Deletion pending; skipping file",
1631 printable_path(full_path));
1635 if (status == STATUS_SHARING_VIOLATION) {
1636 ERROR("Can't open \"%ls\":\n"
1637 " File is in use by another process! "
1638 "Consider using snapshot (VSS) mode.",
1639 printable_path(full_path));
1640 ret = WIMLIB_ERR_OPEN;
1643 winnt_error(status, L"\"%ls\": Can't open file",
1644 printable_path(full_path));
1645 if (status == STATUS_FVE_LOCKED_VOLUME)
1646 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1648 ret = WIMLIB_ERR_OPEN;
1652 /* Get information about the file. */
1653 status = get_file_info(h, &file_info);
1654 if (!NT_SUCCESS(status)) {
1655 winnt_error(status, L"\"%ls\": Can't get file information",
1656 printable_path(full_path));
1657 ret = WIMLIB_ERR_STAT;
1661 /* Create a WIM dentry with an associated inode, which may be shared.
1663 * However, we need to explicitly check for directories and files with
1664 * only 1 link and refuse to hard link them. This is because Windows
1665 * has a bug where it can return duplicate File IDs for files and
1666 * directories on the FAT filesystem.
1668 * Since we don't follow mount points on Windows, we don't need to query
1669 * the volume ID per-file. Just once, for the root, is enough. But we
1670 * can't simply pass 0, because then there could be inode collisions
1671 * among multiple calls to win32_build_dentry_tree() that are scanning
1672 * files on different volumes. */
1673 ret = inode_table_new_dentry(ctx->params->inode_table,
1676 ctx->params->capture_root_dev,
1677 (file_info.num_links <= 1),
1682 /* Get the short (DOS) name of the file. */
1683 status = winnt_get_short_name(h, root);
1685 /* If we can't read the short filename for any reason other than
1686 * out-of-memory, just ignore the error and assume the file has no short
1687 * name. This shouldn't be an issue, since the short names are
1688 * essentially obsolete anyway. */
1689 if (unlikely(status == STATUS_NO_MEMORY)) {
1690 ret = WIMLIB_ERR_NOMEM;
1694 inode = root->d_inode;
1696 if (inode->i_nlink > 1) {
1697 /* Shared inode (hard link); skip reading per-inode information.
1702 inode->i_attributes = file_info.attributes;
1703 inode->i_creation_time = file_info.creation_time;
1704 inode->i_last_write_time = file_info.last_write_time;
1705 inode->i_last_access_time = file_info.last_access_time;
1707 /* Get the file's security descriptor, unless we are capturing in
1708 * NO_ACLS mode or the volume does not support security descriptors. */
1709 if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1710 && (ctx->vol_flags & FILE_PERSISTENT_ACLS))
1712 ret = winnt_load_security_descriptor(h, inode, full_path, ctx);
1717 /* Get the file's object ID. */
1718 ret = winnt_load_object_id(h, inode, full_path, ctx);
1722 /* If this is a reparse point, load the reparse data. */
1723 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1724 ret = winnt_load_reparse_data(h, inode, full_path, ctx->params);
1729 sort_key = get_sort_key(h);
1731 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1732 /* Load information about the raw encrypted data. This is
1733 * needed for any directory or non-directory that has
1734 * FILE_ATTRIBUTE_ENCRYPTED set.
1736 * Note: since OpenEncryptedFileRaw() fails with
1737 * ERROR_SHARING_VIOLATION if there are any open handles to the
1738 * file, we have to close the file and re-open it later if
1742 ret = winnt_scan_efsrpc_raw_data(inode, full_path,
1743 full_path_nchars, ctx);
1748 * Load information about data streams (unnamed and named).
1750 * Skip this step for encrypted files, since the data from
1751 * ReadEncryptedFileRaw() already contains all data streams (and
1752 * they do in fact all get restored by WriteEncryptedFileRaw().)
1754 * Note: WIMGAPI (as of Windows 8.1) gets wrong and stores both
1755 * the EFSRPC data and the named data stream(s)...!
1757 ret = winnt_scan_data_streams(h,
1761 file_info.end_of_file,
1767 if (unlikely(should_try_to_use_wimboot_hash(inode, ctx, ctx->params))) {
1768 ret = try_to_use_wimboot_hash(h, inode, ctx, full_path);
1773 set_sort_key(inode, sort_key);
1775 if (inode_is_directory(inode)) {
1777 /* Directory: recurse to children. */
1779 /* Re-open the directory with FILE_LIST_DIRECTORY access. */
1784 status = winnt_openat(cur_dir, relative_path,
1785 relative_path_nchars, FILE_LIST_DIRECTORY,
1787 if (!NT_SUCCESS(status)) {
1788 winnt_error(status, L"\"%ls\": Can't open directory",
1789 printable_path(full_path));
1790 ret = WIMLIB_ERR_OPEN;
1793 ret = winnt_recurse_directory(h,
1803 ctx->params->progress.scan.cur_path = full_path;
1805 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_OK, inode);
1807 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1811 if (unlikely(ret)) {
1812 free_dentry_tree(root, ctx->params->blob_table);
1814 ret = report_scan_error(ctx->params, ret, full_path);
1821 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_ctx *ctx)
1823 if (likely(ctx->num_get_sacl_priv_notheld == 0 &&
1824 ctx->num_get_sd_access_denied == 0))
1827 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1828 if (ctx->num_get_sacl_priv_notheld != 0) {
1829 WARNING("- Could not capture SACL (System Access Control List)\n"
1830 " on %lu files or directories.",
1831 ctx->num_get_sacl_priv_notheld);
1833 if (ctx->num_get_sd_access_denied != 0) {
1834 WARNING("- Could not capture security descriptor at all\n"
1835 " on %lu files or directories.",
1836 ctx->num_get_sd_access_denied);
1838 WARNING("To fully capture all security descriptors, run the program\n"
1839 " with Administrator rights.");
1842 /*----------------------------------------------------------------------------*
1843 * Fast MFT scan implementation *
1844 *----------------------------------------------------------------------------*/
1846 #define ENABLE_FAST_MFT_SCAN 1
1848 #ifdef ENABLE_FAST_MFT_SCAN
1851 u64 StartingCluster;
1856 u64 StartingFileReferenceNumber;
1857 u64 EndingFileReferenceNumber;
1858 } FILE_REFERENCE_RANGE;
1860 /* The FSCTL_QUERY_FILE_LAYOUT ioctl. This ioctl can be used on Windows 8 and
1861 * later to scan the MFT of an NTFS volume. */
1862 #define FSCTL_QUERY_FILE_LAYOUT CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 157, METHOD_NEITHER, FILE_ANY_ACCESS)
1864 /* The input to FSCTL_QUERY_FILE_LAYOUT */
1867 #define QUERY_FILE_LAYOUT_RESTART 0x00000001
1868 #define QUERY_FILE_LAYOUT_INCLUDE_NAMES 0x00000002
1869 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS 0x00000004
1870 #define QUERY_FILE_LAYOUT_INCLUDE_EXTENTS 0x00000008
1871 #define QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO 0x00000010
1872 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED 0x00000020
1874 #define QUERY_FILE_LAYOUT_FILTER_TYPE_NONE 0
1875 #define QUERY_FILE_LAYOUT_FILTER_TYPE_CLUSTERS 1
1876 #define QUERY_FILE_LAYOUT_FILTER_TYPE_FILEID 2
1877 #define QUERY_FILE_LAYOUT_NUM_FILTER_TYPES 3
1881 CLUSTER_RANGE ClusterRanges[1];
1882 FILE_REFERENCE_RANGE FileReferenceRanges[1];
1884 } QUERY_FILE_LAYOUT_INPUT;
1886 /* The header of the buffer returned by FSCTL_QUERY_FILE_LAYOUT */
1889 u32 FirstFileOffset;
1890 #define QUERY_FILE_LAYOUT_SINGLE_INSTANCED 0x00000001
1893 } QUERY_FILE_LAYOUT_OUTPUT;
1895 /* Inode information returned by FSCTL_QUERY_FILE_LAYOUT */
1901 u64 FileReferenceNumber;
1902 u32 FirstNameOffset;
1903 u32 FirstStreamOffset;
1904 u32 ExtraInfoOffset;
1906 } FILE_LAYOUT_ENTRY;
1908 /* Extra inode information returned by FSCTL_QUERY_FILE_LAYOUT */
1920 } FILE_LAYOUT_INFO_ENTRY;
1922 /* Filename (or dentry) information returned by FSCTL_QUERY_FILE_LAYOUT */
1925 #define FILE_LAYOUT_NAME_ENTRY_PRIMARY 0x00000001
1926 #define FILE_LAYOUT_NAME_ENTRY_DOS 0x00000002
1928 u64 ParentFileReferenceNumber;
1931 wchar_t FileName[1];
1932 } FILE_LAYOUT_NAME_ENTRY;
1934 /* Stream information returned by FSCTL_QUERY_FILE_LAYOUT */
1937 u32 NextStreamOffset;
1938 #define STREAM_LAYOUT_ENTRY_IMMOVABLE 0x00000001
1939 #define STREAM_LAYOUT_ENTRY_PINNED 0x00000002
1940 #define STREAM_LAYOUT_ENTRY_RESIDENT 0x00000004
1941 #define STREAM_LAYOUT_ENTRY_NO_CLUSTERS_ALLOCATED 0x00000008
1943 u32 ExtentInformationOffset;
1948 u32 StreamIdentifierLength;
1949 wchar_t StreamIdentifier[1];
1950 } STREAM_LAYOUT_ENTRY;
1954 #define STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS 0x00000001
1955 #define STREAM_EXTENT_ENTRY_ALL_EXTENTS 0x00000002
1958 RETRIEVAL_POINTERS_BUFFER RetrievalPointers;
1959 } ExtentInformation;
1960 } STREAM_EXTENT_ENTRY;
1962 /* Extract the MFT number part of the full inode number */
1963 #define NTFS_MFT_NO(ref) ((ref) & (((u64)1 << 48) - 1))
1965 /* Is the file the root directory of the NTFS volume? The root directory always
1966 * occupies MFT record 5. */
1967 #define NTFS_IS_ROOT_FILE(ino) (NTFS_MFT_NO(ino) == 5)
1969 /* Is the file a special NTFS file, other than the root directory? The special
1970 * files are the first 16 records in the MFT. */
1971 #define NTFS_IS_SPECIAL_FILE(ino) \
1972 (NTFS_MFT_NO(ino) <= 15 && !NTFS_IS_ROOT_FILE(ino))
1974 /* Intermediate inode structure. This is used to temporarily save information
1975 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_inode'. */
1977 struct avl_tree_node index_node;
1980 u64 last_access_time;
1981 u64 last_write_time;
1986 u32 num_streams : 31;
1987 u32 have_object_id : 1;
1988 u32 first_stream_offset;
1989 struct ntfs_dentry *first_child;
1990 wchar_t short_name[13];
1993 /* Intermediate dentry structure. This is used to temporarily save information
1994 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_dentry'. */
1995 struct ntfs_dentry {
1996 u32 offset_from_inode : 31;
1999 /* Note: build_children_lists() replaces 'parent_ino' with
2002 struct ntfs_dentry *next_child;
2007 /* Intermediate stream structure. This is used to temporarily save information
2008 * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct
2009 * wim_inode_stream'. */
2010 struct ntfs_stream {
2015 /* Map of all known NTFS inodes, keyed by inode number */
2016 struct ntfs_inode_map {
2017 struct avl_tree_node *root;
2020 #define NTFS_INODE(node) \
2021 avl_tree_entry((node), struct ntfs_inode, index_node)
2023 #define SKIP_ALIGNED(p, size) ((void *)(p) + ALIGN((size), 8))
2025 /* Get a pointer to the first dentry of the inode. */
2026 #define FIRST_DENTRY(ni) SKIP_ALIGNED((ni), sizeof(struct ntfs_inode))
2028 /* Get a pointer to the first stream of the inode. */
2029 #define FIRST_STREAM(ni) ((const void *)ni + ni->first_stream_offset)
2031 /* Advance to the next dentry of the inode. */
2032 #define NEXT_DENTRY(nd) SKIP_ALIGNED((nd), sizeof(struct ntfs_dentry) + \
2033 (wcslen((nd)->name) + 1) * sizeof(wchar_t))
2035 /* Advance to the next stream of the inode. */
2036 #define NEXT_STREAM(ns) SKIP_ALIGNED((ns), sizeof(struct ntfs_stream) + \
2037 (wcslen((ns)->name) + 1) * sizeof(wchar_t))
2040 _avl_cmp_ntfs_inodes(const struct avl_tree_node *node1,
2041 const struct avl_tree_node *node2)
2043 return cmp_u64(NTFS_INODE(node1)->ino, NTFS_INODE(node2)->ino);
2046 /* Adds an NTFS inode to the map. */
2048 ntfs_inode_map_add_inode(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2050 if (avl_tree_insert(&map->root, &ni->index_node, _avl_cmp_ntfs_inodes)) {
2051 WARNING("Inode 0x%016"PRIx64" is a duplicate!", ni->ino);
2056 /* Find an ntfs_inode in the map by inode number. Returns NULL if not found. */
2057 static struct ntfs_inode *
2058 ntfs_inode_map_lookup(struct ntfs_inode_map *map, u64 ino)
2060 struct ntfs_inode tmp;
2061 struct avl_tree_node *res;
2064 res = avl_tree_lookup_node(map->root, &tmp.index_node, _avl_cmp_ntfs_inodes);
2067 return NTFS_INODE(res);
2070 /* Remove an ntfs_inode from the map and free it. */
2072 ntfs_inode_map_remove(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2074 avl_tree_remove(&map->root, &ni->index_node);
2078 /* Free all ntfs_inodes in the map. */
2080 ntfs_inode_map_destroy(struct ntfs_inode_map *map)
2082 struct ntfs_inode *ni;
2084 avl_tree_for_each_in_postorder(ni, map->root, struct ntfs_inode, index_node)
2089 file_has_streams(const FILE_LAYOUT_ENTRY *file)
2091 return (file->FirstStreamOffset != 0) &&
2092 !(file->FileAttributes & FILE_ATTRIBUTE_ENCRYPTED);
2096 is_valid_name_entry(const FILE_LAYOUT_NAME_ENTRY *name)
2098 return name->FileNameLength > 0 &&
2099 name->FileNameLength % 2 == 0 &&
2100 !wmemchr(name->FileName, L'\0', name->FileNameLength / 2) &&
2101 (!(name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) ||
2102 name->FileNameLength <= 24);
2105 /* Validate the FILE_LAYOUT_NAME_ENTRYs of the specified file and compute the
2106 * total length in bytes of the ntfs_dentry structures needed to hold the name
2109 validate_names_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2110 size_t *total_length_ret)
2112 const FILE_LAYOUT_NAME_ENTRY *name =
2113 (const void *)file + file->FirstNameOffset;
2115 size_t num_long_names = 0;
2118 if (unlikely(!is_valid_name_entry(name))) {
2119 ERROR("Invalid FILE_LAYOUT_NAME_ENTRY! "
2120 "FileReferenceNumber=0x%016"PRIx64", "
2121 "FileNameLength=%"PRIu32", "
2122 "FileName=%.*ls, Flags=0x%08"PRIx32,
2123 file->FileReferenceNumber,
2124 name->FileNameLength,
2125 (int)(name->FileNameLength / 2),
2126 name->FileName, name->Flags);
2127 return WIMLIB_ERR_UNSUPPORTED;
2129 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2131 total += ALIGN(sizeof(struct ntfs_dentry) +
2132 name->FileNameLength + sizeof(wchar_t),
2135 if (name->NextNameOffset == 0)
2137 name = (const void *)name + name->NextNameOffset;
2140 if (unlikely(num_long_names == 0)) {
2141 ERROR("Inode 0x%016"PRIx64" has no long names!",
2142 file->FileReferenceNumber);
2143 return WIMLIB_ERR_UNSUPPORTED;
2146 *total_length_ret = total;
2151 is_valid_stream_entry(const STREAM_LAYOUT_ENTRY *stream)
2153 return stream->StreamIdentifierLength % 2 == 0 &&
2154 !wmemchr(stream->StreamIdentifier , L'\0',
2155 stream->StreamIdentifierLength / 2);
2159 is_object_id_stream(const STREAM_LAYOUT_ENTRY *stream)
2161 return stream->StreamIdentifierLength == 24 &&
2162 !wmemcmp(stream->StreamIdentifier, L"::$OBJECT_ID", 12);
2166 * If the specified STREAM_LAYOUT_ENTRY represents a DATA stream as opposed to
2167 * some other type of NTFS stream such as a STANDARD_INFORMATION stream, return
2168 * true and set *stream_name_ret and *stream_name_nchars_ret to specify just the
2169 * stream name. For example, ":foo:$DATA" would become "foo" with length 3
2170 * characters. Otherwise return false.
2173 use_stream(const FILE_LAYOUT_ENTRY *file, const STREAM_LAYOUT_ENTRY *stream,
2174 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
2176 const wchar_t *stream_name;
2177 size_t stream_name_nchars;
2179 if (stream->StreamIdentifierLength == 0) {
2180 /* The unnamed data stream may be given as an empty string
2181 * rather than as "::$DATA". Handle it both ways. */
2183 stream_name_nchars = 0;
2184 } else if (!get_data_stream_name(stream->StreamIdentifier,
2185 stream->StreamIdentifierLength / 2,
2186 &stream_name, &stream_name_nchars))
2189 /* Skip the unnamed data stream for directories. */
2190 if (stream_name_nchars == 0 &&
2191 (file->FileAttributes & FILE_ATTRIBUTE_DIRECTORY))
2194 *stream_name_ret = stream_name;
2195 *stream_name_nchars_ret = stream_name_nchars;
2199 /* Validate the STREAM_LAYOUT_ENTRYs of the specified file and compute the total
2200 * length in bytes of the ntfs_stream structures needed to hold the stream
2201 * information. In addition, set *have_object_id_ret=true if the file has an
2202 * object ID stream. */
2204 validate_streams_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2205 size_t *total_length_ret,
2206 bool *have_object_id_ret)
2208 const STREAM_LAYOUT_ENTRY *stream =
2209 (const void *)file + file->FirstStreamOffset;
2212 const wchar_t *name;
2215 if (unlikely(!is_valid_stream_entry(stream))) {
2216 WARNING("Invalid STREAM_LAYOUT_ENTRY! "
2217 "FileReferenceNumber=0x%016"PRIx64", "
2218 "StreamIdentifierLength=%"PRIu32", "
2219 "StreamIdentifier=%.*ls",
2220 file->FileReferenceNumber,
2221 stream->StreamIdentifierLength,
2222 (int)(stream->StreamIdentifierLength / 2),
2223 stream->StreamIdentifier);
2224 return WIMLIB_ERR_UNSUPPORTED;
2227 if (use_stream(file, stream, &name, &name_nchars)) {
2228 total += ALIGN(sizeof(struct ntfs_stream) +
2229 (name_nchars + 1) * sizeof(wchar_t), 8);
2230 } else if (is_object_id_stream(stream)) {
2231 *have_object_id_ret = true;
2233 if (stream->NextStreamOffset == 0)
2235 stream = (const void *)stream + stream->NextStreamOffset;
2238 *total_length_ret = total;
2243 load_name_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2246 const FILE_LAYOUT_NAME_ENTRY *name =
2247 (const void *)file + file->FirstNameOffset;
2249 struct ntfs_dentry *nd = p;
2250 /* Note that a name may be just a short (DOS) name, just a long
2251 * name, or both a short name and a long name. If there is a
2252 * short name, one name should also be marked as "primary" to
2253 * indicate which long name the short name is associated with.
2254 * Also, there should be at most one short name per inode. */
2255 if (name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) {
2256 memcpy(ni->short_name,
2257 name->FileName, name->FileNameLength);
2258 ni->short_name[name->FileNameLength / 2] = L'\0';
2260 if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2262 nd->offset_from_inode = (u8 *)nd - (u8 *)ni;
2263 nd->is_primary = ((name->Flags &
2264 FILE_LAYOUT_NAME_ENTRY_PRIMARY) != 0);
2265 nd->parent_ino = name->ParentFileReferenceNumber;
2266 memcpy(nd->name, name->FileName, name->FileNameLength);
2267 nd->name[name->FileNameLength / 2] = L'\0';
2268 p += ALIGN(sizeof(struct ntfs_dentry) +
2269 name->FileNameLength + sizeof(wchar_t), 8);
2271 if (name->NextNameOffset == 0)
2273 name = (const void *)name + name->NextNameOffset;
2279 load_starting_lcn(const STREAM_LAYOUT_ENTRY *stream)
2281 const STREAM_EXTENT_ENTRY *entry;
2283 if (stream->ExtentInformationOffset == 0)
2286 entry = (const void *)stream + stream->ExtentInformationOffset;
2288 if (!(entry->Flags & STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS))
2291 return extract_starting_lcn(&entry->ExtentInformation.RetrievalPointers);
2295 load_stream_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2298 const STREAM_LAYOUT_ENTRY *stream =
2299 (const void *)file + file->FirstStreamOffset;
2300 const u32 first_stream_offset = (const u8 *)p - (const u8 *)ni;
2302 struct ntfs_stream *ns = p;
2303 const wchar_t *name;
2306 if (use_stream(file, stream, &name, &name_nchars)) {
2307 ni->first_stream_offset = first_stream_offset;
2309 if (name_nchars == 0)
2310 ni->starting_lcn = load_starting_lcn(stream);
2311 ns->size = stream->EndOfFile;
2312 wmemcpy(ns->name, name, name_nchars);
2313 ns->name[name_nchars] = L'\0';
2314 p += ALIGN(sizeof(struct ntfs_stream) +
2315 (name_nchars + 1) * sizeof(wchar_t), 8);
2317 if (stream->NextStreamOffset == 0)
2319 stream = (const void *)stream + stream->NextStreamOffset;
2324 /* Process the information for a file given by FSCTL_QUERY_FILE_LAYOUT. */
2326 load_one_file(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode_map *inode_map)
2328 const FILE_LAYOUT_INFO_ENTRY *info =
2329 (const void *)file + file->ExtraInfoOffset;
2331 struct ntfs_inode *ni;
2335 bool have_object_id = false;
2337 inode_size = ALIGN(sizeof(struct ntfs_inode), 8);
2339 /* The root file should have no names, and all other files should have
2340 * at least one name. But just in case, we ignore the names of the root
2341 * file, and we ignore any non-root file with no names. */
2342 if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber)) {
2343 if (file->FirstNameOffset == 0)
2345 ret = validate_names_and_compute_total_length(file, &n);
2351 if (file_has_streams(file)) {
2352 ret = validate_streams_and_compute_total_length(file, &n,
2359 /* To save memory, we allocate the ntfs_dentry's and ntfs_stream's in
2360 * the same memory block as their ntfs_inode. */
2361 ni = CALLOC(1, inode_size);
2363 return WIMLIB_ERR_NOMEM;
2365 ni->ino = file->FileReferenceNumber;
2366 ni->attributes = info->BasicInformation.FileAttributes;
2367 ni->creation_time = info->BasicInformation.CreationTime;
2368 ni->last_write_time = info->BasicInformation.LastWriteTime;
2369 ni->last_access_time = info->BasicInformation.LastAccessTime;
2370 ni->security_id = info->SecurityId;
2371 ni->have_object_id = have_object_id;
2373 p = FIRST_DENTRY(ni);
2375 if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber))
2376 p = load_name_information(file, ni, p);
2378 if (file_has_streams(file))
2379 p = load_stream_information(file, ni, p);
2381 wimlib_assert((u8 *)p - (u8 *)ni == inode_size);
2383 ntfs_inode_map_add_inode(inode_map, ni);
2388 * Quickly find all files on an NTFS volume by using FSCTL_QUERY_FILE_LAYOUT to
2389 * scan the MFT. The NTFS volume is specified by the NT namespace path @path.
2390 * For each file, allocate an 'ntfs_inode' structure for each file and add it to
2391 * 'inode_map' keyed by inode number. Include NTFS special files such as
2392 * $Bitmap (they will be removed later).
2395 load_files_from_mft(const wchar_t *path, struct ntfs_inode_map *inode_map)
2398 QUERY_FILE_LAYOUT_INPUT in = (QUERY_FILE_LAYOUT_INPUT) {
2400 .Flags = QUERY_FILE_LAYOUT_RESTART |
2401 QUERY_FILE_LAYOUT_INCLUDE_NAMES |
2402 QUERY_FILE_LAYOUT_INCLUDE_STREAMS |
2403 QUERY_FILE_LAYOUT_INCLUDE_EXTENTS |
2404 QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO |
2405 QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED,
2406 .FilterType = QUERY_FILE_LAYOUT_FILTER_TYPE_NONE,
2408 size_t outsize = 32768;
2409 QUERY_FILE_LAYOUT_OUTPUT *out = NULL;
2413 status = winnt_open(path, wcslen(path),
2414 FILE_READ_DATA | FILE_READ_ATTRIBUTES, &h);
2415 if (!NT_SUCCESS(status)) {
2416 ret = -1; /* Silently try standard recursive scan instead */
2421 /* Allocate a buffer for the output of the ioctl. */
2422 out = MALLOC(outsize);
2424 ret = WIMLIB_ERR_NOMEM;
2428 /* Execute FSCTL_QUERY_FILE_LAYOUT until it fails. */
2429 while (NT_SUCCESS(status = winnt_fsctl(h,
2430 FSCTL_QUERY_FILE_LAYOUT,
2432 out, outsize, NULL)))
2434 const FILE_LAYOUT_ENTRY *file =
2435 (const void *)out + out->FirstFileOffset;
2437 ret = load_one_file(file, inode_map);
2440 if (file->NextFileOffset == 0)
2442 file = (const void *)file + file->NextFileOffset;
2444 in.Flags &= ~QUERY_FILE_LAYOUT_RESTART;
2447 /* Enlarge the buffer if needed. */
2448 if (status != STATUS_BUFFER_TOO_SMALL)
2454 /* Normally, FSCTL_QUERY_FILE_LAYOUT fails with STATUS_END_OF_FILE after
2455 * all files have been enumerated. */
2456 if (status != STATUS_END_OF_FILE) {
2457 if (status == STATUS_INVALID_DEVICE_REQUEST /* old OS */ ||
2458 status == STATUS_INVALID_PARAMETER /* not root directory */ ) {
2459 /* Silently try standard recursive scan instead */
2463 L"Error enumerating files on volume \"%ls\"",
2465 /* Try standard recursive scan instead */
2466 ret = WIMLIB_ERR_UNSUPPORTED;
2477 /* Build the list of child dentries for each inode in @map. This is done by
2478 * iterating through each name of each inode and adding it to its parent's
2479 * children list. Note that every name should have a parent, i.e. should belong
2480 * to some directory. The root directory does not have any names. */
2482 build_children_lists(struct ntfs_inode_map *map, struct ntfs_inode **root_ret)
2484 struct ntfs_inode *ni;
2486 avl_tree_for_each_in_order(ni, map->root, struct ntfs_inode, index_node)
2488 struct ntfs_dentry *nd;
2491 if (NTFS_IS_ROOT_FILE(ni->ino)) {
2496 n = ni->num_aliases;
2497 nd = FIRST_DENTRY(ni);
2499 struct ntfs_inode *parent;
2501 parent = ntfs_inode_map_lookup(map, nd->parent_ino);
2502 if (unlikely(!parent)) {
2503 ERROR("Parent inode 0x%016"PRIx64" of"
2504 "directory entry \"%ls\" (inode "
2505 "0x%016"PRIx64") was missing from the "
2507 nd->parent_ino, nd->name, ni->ino);
2508 return WIMLIB_ERR_UNSUPPORTED;
2510 nd->next_child = parent->first_child;
2511 parent->first_child = nd;
2514 nd = NEXT_DENTRY(nd);
2520 struct security_map_node {
2521 struct avl_tree_node index_node;
2522 u32 disk_security_id;
2523 u32 wim_security_id;
2526 /* Map from disk security IDs to WIM security IDs */
2527 struct security_map {
2528 struct avl_tree_node *root;
2531 #define SECURITY_MAP_NODE(node) \
2532 avl_tree_entry((node), struct security_map_node, index_node)
2535 _avl_cmp_security_map_nodes(const struct avl_tree_node *node1,
2536 const struct avl_tree_node *node2)
2538 return cmp_u32(SECURITY_MAP_NODE(node1)->disk_security_id,
2539 SECURITY_MAP_NODE(node2)->disk_security_id);
2543 security_map_lookup(struct security_map *map, u32 disk_security_id)
2545 struct security_map_node tmp;
2546 const struct avl_tree_node *res;
2548 if (disk_security_id == 0) /* No on-disk security ID; uncacheable */
2551 tmp.disk_security_id = disk_security_id;
2552 res = avl_tree_lookup_node(map->root, &tmp.index_node,
2553 _avl_cmp_security_map_nodes);
2556 return SECURITY_MAP_NODE(res)->wim_security_id;
2560 security_map_insert(struct security_map *map, u32 disk_security_id,
2561 u32 wim_security_id)
2563 struct security_map_node *node;
2565 if (disk_security_id == 0) /* No on-disk security ID; uncacheable */
2568 node = MALLOC(sizeof(*node));
2570 return WIMLIB_ERR_NOMEM;
2572 node->disk_security_id = disk_security_id;
2573 node->wim_security_id = wim_security_id;
2574 avl_tree_insert(&map->root, &node->index_node,
2575 _avl_cmp_security_map_nodes);
2580 security_map_destroy(struct security_map *map)
2582 struct security_map_node *node;
2584 avl_tree_for_each_in_postorder(node, map->root,
2585 struct security_map_node, index_node)
2590 * Turn our temporary NTFS structures into the final WIM structures:
2592 * ntfs_inode => wim_inode
2593 * ntfs_dentry => wim_dentry
2594 * ntfs_stream => wim_inode_stream
2596 * This also handles things such as exclusions and issuing progress messages.
2597 * It's similar to winnt_build_dentry_tree_recursive(), but this is much faster
2598 * because almost all information we need is already loaded in memory in the
2599 * ntfs_* structures. However, in some cases we still fall back to
2600 * winnt_build_dentry_tree_recursive() and/or opening the file.
2603 generate_wim_structures_recursive(struct wim_dentry **root_ret,
2604 wchar_t *path, size_t path_nchars,
2605 const wchar_t *filename, bool is_primary_name,
2606 struct ntfs_inode *ni,
2607 struct winnt_scan_ctx *ctx,
2608 struct ntfs_inode_map *inode_map,
2609 struct security_map *security_map)
2612 struct wim_dentry *root = NULL;
2613 struct wim_inode *inode = NULL;
2614 const struct ntfs_stream *ns;
2616 /* Completely ignore NTFS special files. */
2617 if (NTFS_IS_SPECIAL_FILE(ni->ino))
2620 /* Fall back to a recursive scan for unhandled cases. Reparse points,
2621 * in particular, can't be properly handled here because a commonly used
2622 * filter driver (WOF) hides reparse points from regular filesystem APIs
2623 * but not from FSCTL_QUERY_FILE_LAYOUT. */
2624 if (ni->attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
2625 FILE_ATTRIBUTE_ENCRYPTED) ||
2628 ret = winnt_build_dentry_tree_recursive(&root,
2639 /* Test for exclusion based on path. */
2640 ret = try_exclude(path, ctx->params);
2641 if (unlikely(ret < 0)) /* Excluded? */
2643 if (unlikely(ret > 0)) /* Error? */
2646 /* Create the WIM dentry and possibly a new WIM inode */
2647 ret = inode_table_new_dentry(ctx->params->inode_table, filename,
2648 ni->ino, ctx->params->capture_root_dev,
2653 inode = root->d_inode;
2655 /* Set the short name if needed. */
2656 if (is_primary_name && *ni->short_name) {
2657 size_t nbytes = wcslen(ni->short_name) * sizeof(wchar_t);
2658 root->d_short_name = memdup(ni->short_name,
2659 nbytes + sizeof(wchar_t));
2660 if (!root->d_short_name) {
2661 ret = WIMLIB_ERR_NOMEM;
2664 root->d_short_name_nbytes = nbytes;
2667 if (inode->i_nlink > 1) { /* Already seen this inode? */
2672 /* The file attributes and timestamps were cached from the MFT. */
2673 inode->i_attributes = ni->attributes;
2674 inode->i_creation_time = ni->creation_time;
2675 inode->i_last_write_time = ni->last_write_time;
2676 inode->i_last_access_time = ni->last_access_time;
2678 /* Set the security descriptor if needed. */
2679 if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)) {
2680 /* Look up the WIM security ID that corresponds to the on-disk
2682 s32 wim_security_id =
2683 security_map_lookup(security_map, ni->security_id);
2684 if (likely(wim_security_id >= 0)) {
2685 /* The mapping for this security ID is already cached.*/
2686 inode->i_security_id = wim_security_id;
2691 /* Create a mapping for this security ID and insert it
2692 * into the security map. */
2694 status = winnt_open(path, path_nchars,
2696 ACCESS_SYSTEM_SECURITY, &h);
2697 if (!NT_SUCCESS(status)) {
2698 winnt_error(status, L"Can't open \"%ls\" to "
2699 "read security descriptor",
2700 printable_path(path));
2701 ret = WIMLIB_ERR_OPEN;
2704 ret = winnt_load_security_descriptor(h, inode, path, ctx);
2709 ret = security_map_insert(security_map, ni->security_id,
2710 inode->i_security_id);
2716 /* Add data streams based on the cached information from the MFT. */
2717 ns = FIRST_STREAM(ni);
2718 for (u32 i = 0; i < ni->num_streams; i++) {
2719 struct windows_file *windows_file;
2721 /* Reference the stream by path if it's a named data stream, or
2722 * if the volume doesn't support "open by file ID", or if the
2723 * application hasn't explicitly opted in to "open by file ID".
2724 * Otherwise, only save the inode number (file ID). */
2726 !(ctx->vol_flags & FILE_SUPPORTS_OPEN_BY_FILE_ID) ||
2727 !(ctx->params->add_flags & WIMLIB_ADD_FLAG_FILE_PATHS_UNNEEDED))
2729 windows_file = alloc_windows_file(path,
2736 windows_file = alloc_windows_file_for_file_id(ni->ino,
2738 ctx->params->capture_root_nchars + 1,
2742 ret = add_stream(inode, windows_file, ns->size,
2743 STREAM_TYPE_DATA, ns->name,
2744 ctx->params->unhashed_blobs);
2747 ns = NEXT_STREAM(ns);
2750 set_sort_key(inode, ni->starting_lcn);
2752 /* If processing a directory, then recurse to its children. In this
2753 * version there is no need to go to disk, as we already have the list
2754 * of children cached from the MFT. */
2755 if (inode_is_directory(inode)) {
2756 const struct ntfs_dentry *nd = ni->first_child;
2758 while (nd != NULL) {
2759 const size_t name_len = wcslen(nd->name);
2760 wchar_t *p = path + path_nchars;
2761 struct wim_dentry *child;
2762 const struct ntfs_dentry *next = nd->next_child;
2764 if (*(p - 1) != L'\\')
2766 p = wmempcpy(p, nd->name, name_len);
2769 ret = generate_wim_structures_recursive(
2775 (void *)nd - nd->offset_from_inode,
2780 path[path_nchars] = L'\0';
2785 attach_scanned_tree(root, child, ctx->params->blob_table);
2791 ctx->params->progress.scan.cur_path = path;
2793 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_OK, inode);
2795 ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
2797 if (--ni->num_aliases == 0) {
2798 /* Memory usage optimization: when we don't need the ntfs_inode
2799 * (and its names and streams) anymore, free it. */
2800 ntfs_inode_map_remove(inode_map, ni);
2802 if (unlikely(ret)) {
2803 free_dentry_tree(root, ctx->params->blob_table);
2811 winnt_build_dentry_tree_fast(struct wim_dentry **root_ret, wchar_t *path,
2812 size_t path_nchars, struct winnt_scan_ctx *ctx)
2814 struct ntfs_inode_map inode_map = { .root = NULL };
2815 struct security_map security_map = { .root = NULL };
2816 struct ntfs_inode *root = NULL;
2820 adjust_path = (path[path_nchars - 1] == L'\\');
2822 path[path_nchars - 1] = L'\0';
2824 ret = load_files_from_mft(path, &inode_map);
2827 path[path_nchars - 1] = L'\\';
2832 ret = build_children_lists(&inode_map, &root);
2837 ERROR("The MFT listing for volume \"%ls\" did not include a "
2838 "root directory!", path);
2839 ret = WIMLIB_ERR_UNSUPPORTED;
2843 root->num_aliases = 1;
2845 ret = generate_wim_structures_recursive(root_ret, path, path_nchars,
2846 L"", false, root, ctx,
2847 &inode_map, &security_map);
2849 ntfs_inode_map_destroy(&inode_map);
2850 security_map_destroy(&security_map);
2854 #endif /* ENABLE_FAST_MFT_SCAN */
2856 /*----------------------------------------------------------------------------*
2857 * Entry point for directory tree scans on Windows *
2858 *----------------------------------------------------------------------------*/
2860 #define WINDOWS_NT_MAX_PATH 32768
2863 win32_build_dentry_tree(struct wim_dentry **root_ret,
2864 const wchar_t *root_disk_path,
2865 struct scan_params *params)
2867 wchar_t *path = NULL;
2868 struct winnt_scan_ctx ctx = { .params = params };
2869 UNICODE_STRING ntpath;
2870 size_t ntpath_nchars;
2875 /* WARNING: There is no check for overflow later when this buffer is
2876 * being used! But it's as long as the maximum path length understood
2877 * by Windows NT (which is NOT the same as MAX_PATH). */
2878 path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
2880 return WIMLIB_ERR_NOMEM;
2882 if (params->add_flags & WIMLIB_ADD_FLAG_SNAPSHOT)
2883 ret = vss_create_snapshot(root_disk_path, &ntpath, &ctx.snapshot);
2885 ret = win32_path_to_nt_path(root_disk_path, &ntpath);
2890 if (ntpath.Length < 4 * sizeof(wchar_t) ||
2891 ntpath.Length > WINDOWS_NT_MAX_PATH * sizeof(wchar_t) ||
2892 wmemcmp(ntpath.Buffer, L"\\??\\", 4))
2894 ERROR("\"%ls\": unrecognized path format", root_disk_path);
2895 ret = WIMLIB_ERR_INVALID_PARAM;
2897 ntpath_nchars = ntpath.Length / sizeof(wchar_t);
2898 wmemcpy(path, ntpath.Buffer, ntpath_nchars);
2899 path[ntpath_nchars] = L'\0';
2901 params->capture_root_nchars = ntpath_nchars;
2902 if (path[ntpath_nchars - 1] == L'\\')
2903 params->capture_root_nchars--;
2906 HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
2910 status = winnt_open(path, ntpath_nchars, FILE_READ_ATTRIBUTES, &h);
2911 if (!NT_SUCCESS(status)) {
2912 winnt_error(status, L"Can't open \"%ls\"", printable_path(path));
2913 if (status == STATUS_FVE_LOCKED_VOLUME)
2914 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
2916 ret = WIMLIB_ERR_OPEN;
2920 get_volume_information(h, path, &ctx);
2924 #ifdef ENABLE_FAST_MFT_SCAN
2925 if (ctx.is_ntfs && !_wgetenv(L"WIMLIB_DISABLE_QUERY_FILE_LAYOUT")) {
2926 ret = winnt_build_dentry_tree_fast(root_ret, path,
2927 ntpath_nchars, &ctx);
2928 if (ret >= 0 && ret != WIMLIB_ERR_UNSUPPORTED)
2931 WARNING("A problem occurred during the fast MFT scan.\n"
2932 " Falling back to the standard "
2933 "recursive directory tree scan.");
2937 ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
2938 path, ntpath_nchars,
2939 path, ntpath_nchars,
2942 vss_put_snapshot(ctx.snapshot);
2945 winnt_do_scan_warnings(root_disk_path, &ctx);
2949 #endif /* __WIN32__ */