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, 2014, 2015 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/capture.h"
35 #include "wimlib/dentry.h"
36 #include "wimlib/encoding.h"
37 #include "wimlib/endianness.h"
38 #include "wimlib/error.h"
39 #include "wimlib/paths.h"
40 #include "wimlib/reparse.h"
42 struct winnt_scan_stats {
43 unsigned long num_get_sd_access_denied;
44 unsigned long num_get_sacl_priv_notheld;
47 static inline const wchar_t *
48 printable_path(const wchar_t *full_path)
50 /* Skip over \\?\ or \??\ */
55 * If cur_dir is not NULL, open an existing file relative to the already-open
58 * Otherwise, open the file specified by @path, which must be a Windows NT
62 winnt_openat(HANDLE cur_dir, const wchar_t *path, size_t path_nchars,
63 ACCESS_MASK perms, HANDLE *h_ret)
66 OBJECT_ATTRIBUTES attr;
70 name.Length = path_nchars * sizeof(wchar_t);
71 name.MaximumLength = name.Length + sizeof(wchar_t);
72 name.Buffer = (wchar_t *)path;
74 attr.Length = sizeof(attr);
75 attr.RootDirectory = cur_dir;
76 attr.ObjectName = &name;
78 attr.SecurityDescriptor = NULL;
79 attr.SecurityQualityOfService = NULL;
82 status = (*func_NtOpenFile)(h_ret, perms, &attr, &iosb,
83 FILE_SHARE_VALID_FLAGS,
84 FILE_OPEN_REPARSE_POINT |
85 FILE_OPEN_FOR_BACKUP_INTENT |
86 FILE_SYNCHRONOUS_IO_NONALERT |
87 FILE_SEQUENTIAL_ONLY);
88 if (!NT_SUCCESS(status)) {
89 /* Try requesting fewer permissions */
90 if (status == STATUS_ACCESS_DENIED ||
91 status == STATUS_PRIVILEGE_NOT_HELD) {
92 if (perms & ACCESS_SYSTEM_SECURITY) {
93 perms &= ~ACCESS_SYSTEM_SECURITY;
96 if (perms & READ_CONTROL) {
97 perms &= ~READ_CONTROL;
105 /* Read the first @size bytes from the file, or named data stream of a file,
106 * described by @blob. */
108 read_winnt_stream_prefix(const struct blob_descriptor *blob, u64 size,
109 const struct read_blob_callbacks *cbs)
118 /* This is an NT namespace path. */
119 path = blob->file_on_disk;
121 status = winnt_openat(NULL, path, wcslen(path),
122 FILE_READ_DATA | SYNCHRONIZE, &h);
123 if (!NT_SUCCESS(status)) {
124 winnt_error(status, L"\"%ls\": Can't open for reading",
125 printable_path(path));
126 return WIMLIB_ERR_OPEN;
130 bytes_remaining = size;
131 while (bytes_remaining) {
132 IO_STATUS_BLOCK iosb;
136 count = min(sizeof(buf), bytes_remaining);
138 status = (*func_NtReadFile)(h, NULL, NULL, NULL,
139 &iosb, buf, count, NULL, NULL);
140 if (!NT_SUCCESS(status)) {
141 winnt_error(status, L"\"%ls\": Error reading data",
142 printable_path(path));
143 ret = WIMLIB_ERR_READ;
147 bytes_read = iosb.Information;
149 bytes_remaining -= bytes_read;
150 ret = call_consume_chunk(buf, bytes_read, cbs);
158 struct win32_encrypted_read_ctx {
159 const struct read_blob_callbacks *cbs;
165 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
167 struct win32_encrypted_read_ctx *ctx = _ctx;
169 size_t bytes_to_consume = min(len, ctx->bytes_remaining);
171 if (bytes_to_consume == 0)
172 return ERROR_SUCCESS;
174 ret = call_consume_chunk(data, bytes_to_consume, ctx->cbs);
176 ctx->wimlib_err_code = ret;
177 /* It doesn't matter what error code is returned here, as long
178 * as it isn't ERROR_SUCCESS. */
179 return ERROR_READ_FAULT;
181 ctx->bytes_remaining -= bytes_to_consume;
182 return ERROR_SUCCESS;
186 read_win32_encrypted_file_prefix(const struct blob_descriptor *blob,
188 const struct read_blob_callbacks *cbs)
190 struct win32_encrypted_read_ctx export_ctx;
196 if (blob->file_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
197 flags |= CREATE_FOR_DIR;
199 export_ctx.cbs = cbs;
200 export_ctx.wimlib_err_code = 0;
201 export_ctx.bytes_remaining = size;
203 err = OpenEncryptedFileRaw(blob->file_on_disk, flags, &file_ctx);
204 if (err != ERROR_SUCCESS) {
206 L"Failed to open encrypted file \"%ls\" for raw read",
207 printable_path(blob->file_on_disk));
208 return WIMLIB_ERR_OPEN;
210 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
211 &export_ctx, file_ctx);
212 if (err != ERROR_SUCCESS) {
213 ret = export_ctx.wimlib_err_code;
216 L"Failed to read encrypted file \"%ls\"",
217 printable_path(blob->file_on_disk));
218 ret = WIMLIB_ERR_READ;
220 } else if (export_ctx.bytes_remaining != 0) {
221 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
222 "encrypted file \"%ls\"",
223 size - export_ctx.bytes_remaining, size,
224 printable_path(blob->file_on_disk));
225 ret = WIMLIB_ERR_READ;
229 CloseEncryptedFileRaw(file_ctx);
234 * Load the short name of a file into a WIM dentry.
236 static noinline_for_stack NTSTATUS
237 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
239 /* It's not any harder to just make the NtQueryInformationFile() system
240 * call ourselves, and it saves a dumb call to FindFirstFile() which of
241 * course has to create its own handle. */
243 IO_STATUS_BLOCK iosb;
244 u8 buf[128] _aligned_attribute(8);
245 const FILE_NAME_INFORMATION *info;
247 status = (*func_NtQueryInformationFile)(h, &iosb, buf, sizeof(buf),
248 FileAlternateNameInformation);
249 info = (const FILE_NAME_INFORMATION *)buf;
250 if (NT_SUCCESS(status) && info->FileNameLength != 0) {
251 dentry->d_short_name = utf16le_dupz(info->FileName,
252 info->FileNameLength);
253 if (!dentry->d_short_name)
254 return STATUS_NO_MEMORY;
255 dentry->d_short_name_nbytes = info->FileNameLength;
261 * Load the security descriptor of a file into the corresponding inode and the
262 * WIM image's security descriptor set.
264 static noinline_for_stack NTSTATUS
265 winnt_get_security_descriptor(HANDLE h, struct wim_inode *inode,
266 struct wim_sd_set *sd_set,
267 struct winnt_scan_stats *stats, int add_flags)
269 SECURITY_INFORMATION requestedInformation;
270 u8 _buf[4096] _aligned_attribute(8);
277 * LABEL_SECURITY_INFORMATION is needed on Windows Vista and 7 because
278 * Microsoft decided to add mandatory integrity labels to the SACL but
279 * not have them returned by SACL_SECURITY_INFORMATION.
281 * BACKUP_SECURITY_INFORMATION is needed on Windows 8 because Microsoft
282 * decided to add even more stuff to the SACL and still not have it
283 * returned by SACL_SECURITY_INFORMATION; but they did remember that
284 * backup applications exist and simply want to read the stupid thing
285 * once and for all, so they added a flag to read the entire security
288 * Older versions of Windows tolerate these new flags being passed in.
290 requestedInformation = OWNER_SECURITY_INFORMATION |
291 GROUP_SECURITY_INFORMATION |
292 DACL_SECURITY_INFORMATION |
293 SACL_SECURITY_INFORMATION |
294 LABEL_SECURITY_INFORMATION |
295 BACKUP_SECURITY_INFORMATION;
298 bufsize = sizeof(_buf);
301 * We need the file's security descriptor in
302 * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
303 * opened with as many relevant permissions as possible. At this point,
304 * on Windows there are a number of options for reading a file's
305 * security descriptor:
307 * GetFileSecurity(): This takes in a path and returns the
308 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle,
309 * not ours, and the handle created internally doesn't specify
310 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied
311 * errors on some files and directories, even when running as the
314 * GetSecurityInfo(): This takes in a handle and returns the security
315 * descriptor split into a bunch of different parts. This should work,
316 * but it's dumb because we have to put the security descriptor back
319 * BackupRead(): This can read the security descriptor, but this is a
320 * difficult-to-use API, probably only works as the Administrator, and
321 * the format of the returned data is not well documented.
323 * NtQuerySecurityObject(): This is exactly what we need, as it takes
324 * in a handle and returns the security descriptor in
325 * SECURITY_DESCRIPTOR_RELATIVE format. Only problem is that it's a
326 * ntdll function and therefore not officially part of the Win32 API.
329 while (!(NT_SUCCESS(status = (*func_NtQuerySecurityObject)(h,
330 requestedInformation,
331 (PSECURITY_DESCRIPTOR)buf,
336 case STATUS_BUFFER_TOO_SMALL:
337 wimlib_assert(buf == _buf);
338 buf = MALLOC(len_needed);
340 return STATUS_NO_MEMORY;
341 bufsize = len_needed;
343 case STATUS_PRIVILEGE_NOT_HELD:
344 case STATUS_ACCESS_DENIED:
345 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
347 /* Permission denied in STRICT_ACLS mode, or
351 if (requestedInformation & SACL_SECURITY_INFORMATION) {
352 /* Try again without the SACL. */
353 stats->num_get_sacl_priv_notheld++;
354 requestedInformation &= ~(SACL_SECURITY_INFORMATION |
355 LABEL_SECURITY_INFORMATION |
356 BACKUP_SECURITY_INFORMATION);
359 /* Fake success (useful when capturing as
360 * non-Administrator). */
361 stats->num_get_sd_access_denied++;
362 status = STATUS_SUCCESS;
367 /* Add the security descriptor to the WIM image, and save its ID in
369 inode->i_security_id = sd_set_add_sd(sd_set, buf, len_needed);
370 if (unlikely(inode->i_security_id < 0))
371 status = STATUS_NO_MEMORY;
373 if (unlikely(buf != _buf))
379 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
382 size_t full_path_nchars,
383 const wchar_t *filename,
384 size_t filename_nchars,
385 struct capture_params *params,
386 struct winnt_scan_stats *stats,
390 winnt_recurse_directory(HANDLE h,
392 size_t full_path_nchars,
393 struct wim_dentry *parent,
394 struct capture_params *params,
395 struct winnt_scan_stats *stats,
399 const size_t bufsize = 8192;
400 IO_STATUS_BLOCK iosb;
404 buf = MALLOC(bufsize);
406 return WIMLIB_ERR_NOMEM;
408 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
409 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
411 while (NT_SUCCESS(status = (*func_NtQueryDirectoryFile)(h, NULL, NULL, NULL,
413 FileNamesInformation,
414 FALSE, NULL, FALSE)))
416 const FILE_NAMES_INFORMATION *info = buf;
418 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
419 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
420 info->FileName[1] == L'.'))
424 struct wim_dentry *child;
426 p = full_path + full_path_nchars;
427 /* Only add a backslash if we don't already have
428 * one. This prevents a duplicate backslash
429 * from being added when the path to the capture
430 * dir had a trailing backslash. */
431 if (*(p - 1) != L'\\')
434 p = wmempcpy(filename, info->FileName,
435 info->FileNameLength / 2);
438 ret = winnt_build_dentry_tree_recursive(
444 info->FileNameLength / 2,
449 full_path[full_path_nchars] = L'\0';
454 dentry_add_child(parent, child);
456 if (info->NextEntryOffset == 0)
458 info = (const FILE_NAMES_INFORMATION *)
459 ((const u8 *)info + info->NextEntryOffset);
463 if (unlikely(status != STATUS_NO_MORE_FILES)) {
464 winnt_error(status, L"\"%ls\": Can't read directory",
465 printable_path(full_path));
466 ret = WIMLIB_ERR_READ;
473 /* Reparse point fixup status code */
474 #define RP_FIXED (-1)
477 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
480 IO_STATUS_BLOCK iosb;
481 FILE_INTERNAL_INFORMATION int_info;
482 FILE_FS_VOLUME_INFORMATION vol_info;
484 status = (*func_NtQueryInformationFile)(h, &iosb,
485 &int_info, sizeof(int_info),
486 FileInternalInformation);
487 if (!NT_SUCCESS(status))
490 if (int_info.IndexNumber.QuadPart != ino)
493 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
494 &vol_info, sizeof(vol_info),
495 FileFsVolumeInformation);
496 if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
499 if (iosb.Information <
500 offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
501 sizeof(vol_info.VolumeSerialNumber))
504 return (vol_info.VolumeSerialNumber == dev);
508 * This is the Windows equivalent of unix_relativize_link_target(); see there
509 * for general details. This version works with an "absolute" Windows link
510 * target, specified from the root of the Windows kernel object namespace. Note
511 * that we have to open directories with a trailing slash when present because
512 * \??\E: opens the E: device itself and not the filesystem root directory.
514 static const wchar_t *
515 winnt_relativize_link_target(const wchar_t *target, size_t target_nbytes,
519 OBJECT_ATTRIBUTES attr;
520 IO_STATUS_BLOCK iosb;
522 const wchar_t *target_end;
525 target_end = target + (target_nbytes / sizeof(wchar_t));
528 if (target_end == target)
531 /* No leading slash??? */
532 if (target[0] != L'\\')
536 if ((target_end - target) >= 2 &&
537 target[0] == L'\\' && target[1] == L'\\')
540 attr.Length = sizeof(attr);
541 attr.RootDirectory = NULL;
542 attr.ObjectName = &name;
544 attr.SecurityDescriptor = NULL;
545 attr.SecurityQualityOfService = NULL;
547 name.Buffer = (wchar_t *)target;
552 const wchar_t *orig_p = p;
554 /* Skip non-backslashes */
555 while (p != target_end && *p != L'\\')
558 /* Skip backslashes */
559 while (p != target_end && *p == L'\\')
562 /* Append path component */
563 name.Length += (p - orig_p) * sizeof(wchar_t);
564 name.MaximumLength = name.Length;
566 /* Try opening the file */
567 status = (*func_NtOpenFile) (&h,
568 FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
571 FILE_SHARE_VALID_FLAGS,
572 FILE_OPEN_FOR_BACKUP_INTENT);
574 if (NT_SUCCESS(status)) {
575 /* Reset root directory */
576 if (attr.RootDirectory)
577 (*func_NtClose)(attr.RootDirectory);
578 attr.RootDirectory = h;
579 name.Buffer = (wchar_t *)p;
582 if (file_has_ino_and_dev(h, ino, dev))
583 goto out_close_root_dir;
585 } while (p != target_end);
590 if (attr.RootDirectory)
591 (*func_NtClose)(attr.RootDirectory);
592 while (p > target && *(p - 1) == L'\\')
598 winnt_rpfix_progress(struct capture_params *params, const wchar_t *path,
599 const struct link_reparse_point *link, int scan_status)
601 size_t print_name_nchars = link->print_name_nbytes / sizeof(wchar_t);
602 wchar_t print_name0[print_name_nchars + 1];
604 wmemcpy(print_name0, link->print_name, print_name_nchars);
605 print_name0[print_name_nchars] = L'\0';
607 params->progress.scan.cur_path = printable_path(path);
608 params->progress.scan.symlink_target = print_name0;
609 return do_capture_progress(params, scan_status, NULL);
613 winnt_try_rpfix(struct reparse_buffer_disk *rpbuf, u16 *rpbuflen_p,
614 const wchar_t *path, struct capture_params *params)
616 struct link_reparse_point link;
617 const wchar_t *rel_target;
620 if (parse_link_reparse_point(rpbuf, *rpbuflen_p, &link)) {
621 /* Couldn't understand the reparse data; don't do the fixup. */
626 * Don't do reparse point fixups on relative symbolic links.
628 * On Windows, a relative symbolic link is supposed to be identifiable
629 * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
630 * SYMBOLIC_LINK_RELATIVE. We will use this information, although this
631 * may not always do what the user expects, since drive-relative
632 * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
633 * set, in addition to truely relative symbolic links such as "Users" or
634 * "Users\Public". However, WIMGAPI (as of Windows 8.1) has this same
637 * Otherwise, as far as I can tell, the targets of symbolic links that
638 * are NOT relative, as well as junctions (note: a mountpoint is the
639 * sames thing as a junction), must be NT namespace paths, for example:
641 * - \??\e:\Users\Public
642 * - \DosDevices\e:\Users\Public
643 * - \Device\HardDiskVolume4\Users\Public
644 * - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
645 * - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
647 if (link_is_relative_symlink(&link))
650 rel_target = winnt_relativize_link_target(link.substitute_name,
651 link.substitute_name_nbytes,
652 params->capture_root_ino,
653 params->capture_root_dev);
655 if (rel_target == link.substitute_name) {
656 /* Target points outside of the tree being captured or had an
657 * unrecognized path format. Don't adjust it. */
658 return winnt_rpfix_progress(params, path, &link,
659 WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK);
662 /* We have an absolute target pointing within the directory being
663 * captured. @rel_target is the suffix of the link target that is the
664 * part relative to the directory being captured.
666 * We will cut off the prefix before this part (which is the path to the
667 * directory being captured) and add a dummy prefix. Since the process
668 * will need to be reversed when applying the image, it doesn't matter
669 * what exactly the prefix is, as long as it looks like an absolute
672 static const wchar_t prefix[6] = L"\\??\\X:";
673 static const size_t num_unprintable_chars = 4;
675 size_t rel_target_nbytes =
676 link.substitute_name_nbytes - ((const u8 *)rel_target -
677 (const u8 *)link.substitute_name);
679 wchar_t tmp[(sizeof(prefix) + rel_target_nbytes) / sizeof(wchar_t)];
681 memcpy(tmp, prefix, sizeof(prefix));
682 memcpy(tmp + ARRAY_LEN(prefix), rel_target, rel_target_nbytes);
684 link.substitute_name = tmp;
685 link.substitute_name_nbytes = sizeof(tmp);
687 link.print_name = link.substitute_name + num_unprintable_chars;
688 link.print_name_nbytes = link.substitute_name_nbytes -
689 (num_unprintable_chars * sizeof(wchar_t));
691 if (make_link_reparse_point(&link, rpbuf, rpbuflen_p))
694 ret = winnt_rpfix_progress(params, path, &link,
695 WIMLIB_SCAN_DENTRY_FIXED_SYMLINK);
701 /* Load the reparse data of a file into the corresponding WIM inode. If the
702 * reparse point is a symbolic link or junction with an absolute target and
703 * RPFIX mode is enabled, then also rewrite its target to be relative to the
705 static noinline_for_stack int
706 winnt_load_reparse_data(HANDLE h, struct wim_inode *inode,
707 const wchar_t *full_path, struct capture_params *params)
709 struct reparse_buffer_disk rpbuf;
710 DWORD bytes_returned;
714 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
715 /* See comment above assign_stream_types_encrypted() */
716 WARNING("Ignoring reparse data of encrypted file \"%ls\"",
717 printable_path(full_path));
721 if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
722 NULL, 0, &rpbuf, REPARSE_POINT_MAX_SIZE,
723 &bytes_returned, NULL))
725 win32_error(GetLastError(), L"\"%ls\": Can't get reparse point",
726 printable_path(full_path));
727 return WIMLIB_ERR_READLINK;
730 rpbuflen = bytes_returned;
732 if (unlikely(rpbuflen < REPARSE_DATA_OFFSET)) {
733 ERROR("\"%ls\": reparse point buffer is too short",
734 printable_path(full_path));
735 return WIMLIB_ERR_INVALID_REPARSE_DATA;
738 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX) {
739 ret = winnt_try_rpfix(&rpbuf, &rpbuflen, full_path, params);
741 inode->i_rp_flags &= ~WIM_RP_FLAG_NOT_FIXED;
746 inode->i_reparse_tag = le32_to_cpu(rpbuf.rptag);
747 inode->i_rp_reserved = le16_to_cpu(rpbuf.rpreserved);
749 if (!inode_add_stream_with_data(inode,
750 STREAM_TYPE_REPARSE_POINT,
753 rpbuflen - REPARSE_DATA_OFFSET,
755 return WIMLIB_ERR_NOMEM;
761 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
764 *(u64*)_size_ret += len;
765 return ERROR_SUCCESS;
769 win32_get_encrypted_file_size(const wchar_t *path, bool is_dir, u64 *size_ret)
777 flags |= CREATE_FOR_DIR;
779 err = OpenEncryptedFileRaw(path, flags, &file_ctx);
780 if (err != ERROR_SUCCESS) {
782 L"Failed to open encrypted file \"%ls\" for raw read",
783 printable_path(path));
784 return WIMLIB_ERR_OPEN;
787 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
789 if (err != ERROR_SUCCESS) {
791 L"Failed to read raw encrypted data from \"%ls\"",
792 printable_path(path));
793 ret = WIMLIB_ERR_READ;
797 CloseEncryptedFileRaw(file_ctx);
802 winnt_scan_efsrpc_raw_data(struct wim_inode *inode, const wchar_t *nt_path,
803 struct list_head *unhashed_blobs)
805 struct blob_descriptor *blob;
806 struct wim_inode_stream *strm;
809 blob = new_blob_descriptor();
813 blob->file_on_disk = WCSDUP(nt_path);
814 if (!blob->file_on_disk)
816 blob->blob_location = BLOB_WIN32_ENCRYPTED;
818 /* OpenEncryptedFileRaw() expects a Win32 name. */
819 wimlib_assert(!wmemcmp(blob->file_on_disk, L"\\??\\", 4));
820 blob->file_on_disk[1] = L'\\';
822 blob->file_inode = inode;
824 ret = win32_get_encrypted_file_size(blob->file_on_disk,
825 (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY),
830 /* Empty EFSRPC data does not make sense */
831 wimlib_assert(blob->size != 0);
833 strm = inode_add_stream(inode, STREAM_TYPE_EFSRPC_RAW_DATA,
834 NO_STREAM_NAME, blob);
838 prepare_unhashed_blob(blob, inode, strm->stream_id, unhashed_blobs);
842 ret = WIMLIB_ERR_NOMEM;
844 free_blob_descriptor(blob);
849 get_data_stream_name(wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
850 wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
852 const wchar_t *sep, *type, *end;
854 /* The stream name should be returned as :NAME:TYPE */
855 if (raw_stream_name_nchars < 1)
857 if (raw_stream_name[0] != L':')
861 raw_stream_name_nchars--;
863 end = raw_stream_name + raw_stream_name_nchars;
865 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
873 if (wmemcmp(type, L"$DATA", 5))
876 *stream_name_ret = raw_stream_name;
877 *stream_name_nchars_ret = sep - raw_stream_name;
881 /* Build the path to the data stream. For unnamed streams, this is simply the
882 * path to the file. For named streams, this is the path to the file, followed
883 * by a colon, followed by the stream name. */
885 build_data_stream_path(const wchar_t *path, size_t path_nchars,
886 const wchar_t *stream_name, size_t stream_name_nchars)
888 size_t stream_path_nchars;
889 wchar_t *stream_path;
892 stream_path_nchars = path_nchars;
893 if (stream_name_nchars)
894 stream_path_nchars += 1 + stream_name_nchars;
896 stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
898 p = wmempcpy(stream_path, path, path_nchars);
899 if (stream_name_nchars) {
901 p = wmempcpy(p, stream_name, stream_name_nchars);
909 winnt_scan_data_stream(const wchar_t *path, size_t path_nchars,
910 wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
912 struct wim_inode *inode, struct list_head *unhashed_blobs)
914 wchar_t *stream_name;
915 size_t stream_name_nchars;
916 struct blob_descriptor *blob;
917 struct wim_inode_stream *strm;
919 /* Given the raw stream name (which is something like
920 * :streamname:$DATA), extract just the stream name part (streamname).
921 * Ignore any non-$DATA streams. */
922 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
923 &stream_name, &stream_name_nchars))
926 stream_name[stream_name_nchars] = L'\0';
928 /* If the stream is non-empty, set up a blob descriptor for it. */
929 if (stream_size != 0) {
930 blob = new_blob_descriptor();
933 blob->file_on_disk = build_data_stream_path(path,
937 if (!blob->file_on_disk)
939 blob->blob_location = BLOB_IN_WINNT_FILE_ON_DISK;
940 blob->size = stream_size;
941 blob->file_inode = inode;
946 strm = inode_add_stream(inode, STREAM_TYPE_DATA, stream_name, blob);
950 prepare_unhashed_blob(blob, inode, strm->stream_id, unhashed_blobs);
954 free_blob_descriptor(blob);
955 return WIMLIB_ERR_NOMEM;
959 * Load information about the data streams of an open file into a WIM inode.
961 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
962 * and FindNextStream(). This is done for two reasons:
964 * - FindFirstStream() opens its own handle to the file or directory and
965 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
966 * causing access denied errors on certain files (even when running as the
968 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
969 * and later, whereas the stream support in NtQueryInformationFile() was
970 * already present in Windows XP.
972 static noinline_for_stack int
973 winnt_scan_data_streams(HANDLE h, const wchar_t *path, size_t path_nchars,
974 struct wim_inode *inode, struct list_head *unhashed_blobs,
975 u64 file_size, u32 vol_flags)
978 u8 _buf[4096] _aligned_attribute(8);
981 IO_STATUS_BLOCK iosb;
983 FILE_STREAM_INFORMATION *info;
986 bufsize = sizeof(_buf);
988 if (!(vol_flags & FILE_NAMED_STREAMS))
991 /* Get a buffer containing the stream information. */
992 while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(h,
996 FileStreamInformation)))
1000 case STATUS_BUFFER_OVERFLOW:
1006 newbuf = MALLOC(bufsize);
1008 newbuf = REALLOC(buf, bufsize);
1010 ret = WIMLIB_ERR_NOMEM;
1016 case STATUS_NOT_IMPLEMENTED:
1017 case STATUS_NOT_SUPPORTED:
1018 case STATUS_INVALID_INFO_CLASS:
1022 L"\"%ls\": Failed to query stream information",
1023 printable_path(path));
1024 ret = WIMLIB_ERR_READ;
1029 if (iosb.Information == 0) {
1030 /* No stream information. */
1035 /* Parse one or more stream information structures. */
1036 info = (FILE_STREAM_INFORMATION *)buf;
1038 /* Load the stream information. */
1039 ret = winnt_scan_data_stream(path, path_nchars,
1041 info->StreamNameLength / 2,
1042 info->StreamSize.QuadPart,
1043 inode, unhashed_blobs);
1047 if (info->NextEntryOffset == 0) {
1048 /* No more stream information. */
1051 /* Advance to next stream information. */
1052 info = (FILE_STREAM_INFORMATION *)
1053 ((u8 *)info + info->NextEntryOffset);
1059 /* The volume does not support named streams. Only capture the unnamed
1061 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1062 FILE_ATTRIBUTE_REPARSE_POINT))
1069 wchar_t stream_name[] = L"::$DATA";
1070 ret = winnt_scan_data_stream(path, path_nchars, stream_name, 7,
1071 file_size, inode, unhashed_blobs);
1074 /* Free buffer if allocated on heap. */
1075 if (unlikely(buf != _buf))
1080 static noinline_for_stack u64
1081 get_sort_key(HANDLE h)
1083 STARTING_VCN_INPUT_BUFFER in = { .StartingVcn.QuadPart = 0 };
1084 RETRIEVAL_POINTERS_BUFFER out;
1085 DWORD bytesReturned;
1087 if (!DeviceIoControl(h, FSCTL_GET_RETRIEVAL_POINTERS,
1090 &bytesReturned, NULL))
1093 if (out.ExtentCount < 1)
1096 return out.Extents[0].Lcn.QuadPart;
1100 set_sort_key(struct wim_inode *inode, u64 sort_key)
1102 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1103 struct wim_inode_stream *strm = &inode->i_streams[i];
1104 struct blob_descriptor *blob = stream_blob_resolved(strm);
1105 if (blob && (blob->blob_location == BLOB_IN_WINNT_FILE_ON_DISK ||
1106 blob->blob_location == BLOB_WIN32_ENCRYPTED))
1107 blob->sort_key = sort_key;
1111 static noinline_for_stack u32
1112 get_volume_information(HANDLE h, const wchar_t *full_path,
1113 struct capture_params *params)
1115 FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1116 FILE_FS_VOLUME_INFORMATION vol_info;
1117 IO_STATUS_BLOCK iosb;
1121 /* Get volume flags */
1122 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1125 FileFsAttributeInformation);
1126 if (likely((NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW) &&
1127 (iosb.Information >=
1128 offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1129 FileSystemAttributes) +
1130 sizeof(attr_info.FileSystemAttributes))))
1132 vol_flags = attr_info.FileSystemAttributes;
1134 winnt_warning(status, L"\"%ls\": Can't get volume attributes",
1135 printable_path(full_path));
1139 /* Get volume ID. */
1140 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1143 FileFsVolumeInformation);
1144 if (likely((NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW) &&
1145 (iosb.Information >=
1146 offsetof(FILE_FS_VOLUME_INFORMATION,
1147 VolumeSerialNumber) +
1148 sizeof(vol_info.VolumeSerialNumber))))
1150 params->capture_root_dev = vol_info.VolumeSerialNumber;
1152 winnt_warning(status, L"\"%ls\": Can't get volume ID",
1153 printable_path(full_path));
1154 params->capture_root_dev = 0;
1163 u64 last_write_time;
1164 u64 last_access_time;
1169 static noinline_for_stack NTSTATUS
1170 get_file_info(HANDLE h, struct file_info *info)
1172 IO_STATUS_BLOCK iosb;
1174 FILE_ALL_INFORMATION all_info;
1176 status = (*func_NtQueryInformationFile)(h, &iosb, &all_info,
1178 FileAllInformation);
1180 if (unlikely(!NT_SUCCESS(status) && status != STATUS_BUFFER_OVERFLOW))
1183 info->attributes = all_info.BasicInformation.FileAttributes;
1184 info->num_links = all_info.StandardInformation.NumberOfLinks;
1185 info->creation_time = all_info.BasicInformation.CreationTime.QuadPart;
1186 info->last_write_time = all_info.BasicInformation.LastWriteTime.QuadPart;
1187 info->last_access_time = all_info.BasicInformation.LastAccessTime.QuadPart;
1188 info->ino = all_info.InternalInformation.IndexNumber.QuadPart;
1189 info->end_of_file = all_info.StandardInformation.EndOfFile.QuadPart;
1190 return STATUS_SUCCESS;
1194 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1197 size_t full_path_nchars,
1198 const wchar_t *filename,
1199 size_t filename_nchars,
1200 struct capture_params *params,
1201 struct winnt_scan_stats *stats,
1204 struct wim_dentry *root = NULL;
1205 struct wim_inode *inode = NULL;
1209 struct file_info file_info;
1210 ACCESS_MASK requestedPerms;
1213 ret = try_exclude(full_path, params);
1214 if (unlikely(ret < 0)) /* Excluded? */
1216 if (unlikely(ret > 0)) /* Error? */
1219 /* Open the file. */
1220 requestedPerms = FILE_READ_DATA |
1221 FILE_READ_ATTRIBUTES |
1223 ACCESS_SYSTEM_SECURITY |
1226 status = winnt_openat(cur_dir,
1227 (cur_dir ? filename : full_path),
1228 (cur_dir ? filename_nchars : full_path_nchars),
1231 if (unlikely(!NT_SUCCESS(status))) {
1232 if (status == STATUS_DELETE_PENDING) {
1233 WARNING("\"%ls\": Deletion pending; skipping file",
1234 printable_path(full_path));
1238 if (status == STATUS_ACCESS_DENIED &&
1239 (requestedPerms & FILE_READ_DATA)) {
1240 /* This happens on encrypted files. */
1241 requestedPerms &= ~FILE_READ_DATA;
1245 winnt_error(status, L"\"%ls\": Can't open file",
1246 printable_path(full_path));
1247 if (status == STATUS_FVE_LOCKED_VOLUME)
1248 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1250 ret = WIMLIB_ERR_OPEN;
1254 /* Get information about the file. */
1255 status = get_file_info(h, &file_info);
1256 if (!NT_SUCCESS(status)) {
1257 winnt_error(status, L"\"%ls\": Can't get file information",
1258 printable_path(full_path));
1259 ret = WIMLIB_ERR_STAT;
1263 if (unlikely(!(requestedPerms & FILE_READ_DATA)) &&
1264 !(file_info.attributes & FILE_ATTRIBUTE_ENCRYPTED))
1266 ERROR("\"%ls\": Permission to read data was denied",
1267 printable_path(full_path));
1268 ret = WIMLIB_ERR_OPEN;
1272 if (unlikely(!cur_dir)) {
1273 /* Root of tree being captured; get volume information. */
1274 vol_flags = get_volume_information(h, full_path, params);
1275 params->capture_root_ino = file_info.ino;
1279 /* Create a WIM dentry with an associated inode, which may be shared.
1281 * However, we need to explicitly check for directories and files with
1282 * only 1 link and refuse to hard link them. This is because Windows
1283 * has a bug where it can return duplicate File IDs for files and
1284 * directories on the FAT filesystem.
1286 * Since we don't follow mount points on Windows, we don't need to query
1287 * the volume ID per-file. Just once, for the root, is enough. But we
1288 * can't simply pass 0, because then there could be inode collisions
1289 * among multiple calls to win32_build_dentry_tree() that are scanning
1290 * files on different volumes. */
1291 ret = inode_table_new_dentry(params->inode_table,
1294 params->capture_root_dev,
1295 (file_info.num_links <= 1 ||
1296 (file_info.attributes & FILE_ATTRIBUTE_DIRECTORY)),
1301 /* Get the short (DOS) name of the file. */
1302 status = winnt_get_short_name(h, root);
1304 /* If we can't read the short filename for any reason other than
1305 * out-of-memory, just ignore the error and assume the file has no short
1306 * name. This shouldn't be an issue, since the short names are
1307 * essentially obsolete anyway. */
1308 if (unlikely(status == STATUS_NO_MEMORY)) {
1309 ret = WIMLIB_ERR_NOMEM;
1313 inode = root->d_inode;
1315 if (inode->i_nlink > 1) {
1316 /* Shared inode (hard link); skip reading per-inode information.
1321 inode->i_attributes = file_info.attributes;
1322 inode->i_creation_time = file_info.creation_time;
1323 inode->i_last_write_time = file_info.last_write_time;
1324 inode->i_last_access_time = file_info.last_access_time;
1326 /* Get the file's security descriptor, unless we are capturing in
1327 * NO_ACLS mode or the volume does not support security descriptors. */
1328 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1329 && (vol_flags & FILE_PERSISTENT_ACLS))
1331 status = winnt_get_security_descriptor(h, inode,
1332 params->sd_set, stats,
1334 if (!NT_SUCCESS(status)) {
1336 L"\"%ls\": Can't read security descriptor",
1337 printable_path(full_path));
1338 ret = WIMLIB_ERR_STAT;
1343 /* If this is a reparse point, load the reparse data. */
1344 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1345 ret = winnt_load_reparse_data(h, inode, full_path, params);
1350 sort_key = get_sort_key(h);
1352 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1353 /* Load information about the raw encrypted data. This is
1354 * needed for any directory or non-directory that has
1355 * FILE_ATTRIBUTE_ENCRYPTED set.
1357 * Note: since OpenEncryptedFileRaw() fails with
1358 * ERROR_SHARING_VIOLATION if there are any open handles to the
1359 * file, we have to close the file and re-open it later if
1363 ret = winnt_scan_efsrpc_raw_data(inode, full_path,
1364 params->unhashed_blobs);
1369 * Load information about data streams (unnamed and named).
1371 * Skip this step for encrypted files, since the data from
1372 * ReadEncryptedFileRaw() already contains all data streams (and
1373 * they do in fact all get restored by WriteEncryptedFileRaw().)
1375 * Note: WIMGAPI (as of Windows 8.1) gets wrong and stores both
1376 * the EFSRPC data and the named data stream(s)...!
1378 ret = winnt_scan_data_streams(h,
1382 params->unhashed_blobs,
1383 file_info.end_of_file,
1389 set_sort_key(inode, sort_key);
1391 if (inode_is_directory(inode)) {
1393 /* Directory: recurse to children. */
1396 /* Re-open handle that was closed to read raw encrypted
1398 status = winnt_openat(cur_dir,
1400 filename : full_path),
1402 filename_nchars : full_path_nchars),
1403 FILE_LIST_DIRECTORY | SYNCHRONIZE,
1405 if (!NT_SUCCESS(status)) {
1407 L"\"%ls\": Can't re-open file",
1408 printable_path(full_path));
1409 ret = WIMLIB_ERR_OPEN;
1413 ret = winnt_recurse_directory(h,
1425 params->progress.scan.cur_path = printable_path(full_path);
1427 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1429 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1433 if (unlikely(ret)) {
1434 free_dentry_tree(root, params->blob_table);
1436 ret = report_capture_error(params, ret, full_path);
1443 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_stats *stats)
1445 if (likely(stats->num_get_sacl_priv_notheld == 0 &&
1446 stats->num_get_sd_access_denied == 0))
1449 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1450 if (stats->num_get_sacl_priv_notheld != 0) {
1451 WARNING("- Could not capture SACL (System Access Control List)\n"
1452 " on %lu files or directories.",
1453 stats->num_get_sacl_priv_notheld);
1455 if (stats->num_get_sd_access_denied != 0) {
1456 WARNING("- Could not capture security descriptor at all\n"
1457 " on %lu files or directories.",
1458 stats->num_get_sd_access_denied);
1460 WARNING("To fully capture all security descriptors, run the program\n"
1461 " with Administrator rights.");
1464 #define WINDOWS_NT_MAX_PATH 32768
1466 /* Win32 version of capturing a directory tree. */
1468 win32_build_dentry_tree(struct wim_dentry **root_ret,
1469 const wchar_t *root_disk_path,
1470 struct capture_params *params)
1474 UNICODE_STRING ntpath;
1475 struct winnt_scan_stats stats;
1476 size_t ntpath_nchars;
1478 /* WARNING: There is no check for overflow later when this buffer is
1479 * being used! But it's as long as the maximum path length understood
1480 * by Windows NT (which is NOT the same as MAX_PATH). */
1481 path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1483 return WIMLIB_ERR_NOMEM;
1485 ret = win32_path_to_nt_path(root_disk_path, &ntpath);
1489 if (ntpath.Length < 4 * sizeof(wchar_t) ||
1490 ntpath.Length > WINDOWS_NT_MAX_PATH * sizeof(wchar_t) ||
1491 wmemcmp(ntpath.Buffer, L"\\??\\", 4))
1493 ERROR("\"%ls\": unrecognized path format", root_disk_path);
1494 ret = WIMLIB_ERR_INVALID_PARAM;
1496 ntpath_nchars = ntpath.Length / sizeof(wchar_t);
1497 wmemcpy(path, ntpath.Buffer, ntpath_nchars);
1498 path[ntpath_nchars] = L'\0';
1500 params->capture_root_nchars = ntpath_nchars;
1501 if (path[ntpath_nchars - 1] == L'\\')
1502 params->capture_root_nchars--;
1505 HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
1509 memset(&stats, 0, sizeof(stats));
1511 ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
1512 path, ntpath_nchars,
1513 L"", 0, params, &stats, 0);
1517 winnt_do_scan_warnings(root_disk_path, &stats);
1521 #endif /* __WIN32__ */