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 consume_data_callback_t cb, void *cb_ctx)
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 = (*cb)(buf, bytes_read, cb_ctx);
158 struct win32_encrypted_read_ctx {
159 consume_data_callback_t read_prefix_cb;
160 void *read_prefix_ctx;
166 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
168 struct win32_encrypted_read_ctx *ctx = _ctx;
170 size_t bytes_to_consume = min(len, ctx->bytes_remaining);
172 if (bytes_to_consume == 0)
173 return ERROR_SUCCESS;
175 ret = (*ctx->read_prefix_cb)(data, bytes_to_consume, ctx->read_prefix_ctx);
177 ctx->wimlib_err_code = ret;
178 /* It doesn't matter what error code is returned here, as long
179 * as it isn't ERROR_SUCCESS. */
180 return ERROR_READ_FAULT;
182 ctx->bytes_remaining -= bytes_to_consume;
183 return ERROR_SUCCESS;
187 read_win32_encrypted_file_prefix(const struct blob_descriptor *blob,
189 consume_data_callback_t cb, void *cb_ctx)
191 struct win32_encrypted_read_ctx export_ctx;
197 if (blob->file_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
198 flags |= CREATE_FOR_DIR;
200 export_ctx.read_prefix_cb = cb;
201 export_ctx.read_prefix_ctx = cb_ctx;
202 export_ctx.wimlib_err_code = 0;
203 export_ctx.bytes_remaining = size;
205 err = OpenEncryptedFileRaw(blob->file_on_disk, flags, &file_ctx);
206 if (err != ERROR_SUCCESS) {
208 L"Failed to open encrypted file \"%ls\" for raw read",
209 printable_path(blob->file_on_disk));
210 return WIMLIB_ERR_OPEN;
212 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
213 &export_ctx, file_ctx);
214 if (err != ERROR_SUCCESS) {
215 ret = export_ctx.wimlib_err_code;
218 L"Failed to read encrypted file \"%ls\"",
219 printable_path(blob->file_on_disk));
220 ret = WIMLIB_ERR_READ;
222 } else if (export_ctx.bytes_remaining != 0) {
223 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
224 "encrypted file \"%ls\"",
225 size - export_ctx.bytes_remaining, size,
226 printable_path(blob->file_on_disk));
227 ret = WIMLIB_ERR_READ;
231 CloseEncryptedFileRaw(file_ctx);
236 * Load the short name of a file into a WIM dentry.
239 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
241 /* It's not any harder to just make the NtQueryInformationFile() system
242 * call ourselves, and it saves a dumb call to FindFirstFile() which of
243 * course has to create its own handle. */
245 IO_STATUS_BLOCK iosb;
246 u8 buf[128] _aligned_attribute(8);
247 const FILE_NAME_INFORMATION *info;
249 status = (*func_NtQueryInformationFile)(h, &iosb, buf, sizeof(buf),
250 FileAlternateNameInformation);
251 info = (const FILE_NAME_INFORMATION *)buf;
252 if (NT_SUCCESS(status) && info->FileNameLength != 0) {
253 dentry->short_name = utf16le_dupz(info->FileName,
254 info->FileNameLength);
255 if (!dentry->short_name)
256 return STATUS_NO_MEMORY;
257 dentry->short_name_nbytes = info->FileNameLength;
263 * Load the security descriptor of a file into the corresponding inode and the
264 * WIM image's security descriptor set.
267 winnt_get_security_descriptor(HANDLE h, struct wim_inode *inode,
268 struct wim_sd_set *sd_set,
269 struct winnt_scan_stats *stats, int add_flags)
271 SECURITY_INFORMATION requestedInformation;
272 u8 _buf[4096] _aligned_attribute(8);
279 * LABEL_SECURITY_INFORMATION is needed on Windows Vista and 7 because
280 * Microsoft decided to add mandatory integrity labels to the SACL but
281 * not have them returned by SACL_SECURITY_INFORMATION.
283 * BACKUP_SECURITY_INFORMATION is needed on Windows 8 because Microsoft
284 * decided to add even more stuff to the SACL and still not have it
285 * returned by SACL_SECURITY_INFORMATION; but they did remember that
286 * backup applications exist and simply want to read the stupid thing
287 * once and for all, so they added a flag to read the entire security
290 * Older versions of Windows tolerate these new flags being passed in.
292 requestedInformation = OWNER_SECURITY_INFORMATION |
293 GROUP_SECURITY_INFORMATION |
294 DACL_SECURITY_INFORMATION |
295 SACL_SECURITY_INFORMATION |
296 LABEL_SECURITY_INFORMATION |
297 BACKUP_SECURITY_INFORMATION;
300 bufsize = sizeof(_buf);
303 * We need the file's security descriptor in
304 * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
305 * opened with as many relevant permissions as possible. At this point,
306 * on Windows there are a number of options for reading a file's
307 * security descriptor:
309 * GetFileSecurity(): This takes in a path and returns the
310 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle,
311 * not ours, and the handle created internally doesn't specify
312 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied
313 * errors on some files and directories, even when running as the
316 * GetSecurityInfo(): This takes in a handle and returns the security
317 * descriptor split into a bunch of different parts. This should work,
318 * but it's dumb because we have to put the security descriptor back
321 * BackupRead(): This can read the security descriptor, but this is a
322 * difficult-to-use API, probably only works as the Administrator, and
323 * the format of the returned data is not well documented.
325 * NtQuerySecurityObject(): This is exactly what we need, as it takes
326 * in a handle and returns the security descriptor in
327 * SECURITY_DESCRIPTOR_RELATIVE format. Only problem is that it's a
328 * ntdll function and therefore not officially part of the Win32 API.
331 while (!(NT_SUCCESS(status = (*func_NtQuerySecurityObject)(h,
332 requestedInformation,
333 (PSECURITY_DESCRIPTOR)buf,
338 case STATUS_BUFFER_TOO_SMALL:
339 wimlib_assert(buf == _buf);
340 buf = MALLOC(len_needed);
342 return STATUS_NO_MEMORY;
343 bufsize = len_needed;
345 case STATUS_PRIVILEGE_NOT_HELD:
346 case STATUS_ACCESS_DENIED:
347 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
349 /* Permission denied in STRICT_ACLS mode, or
353 if (requestedInformation & SACL_SECURITY_INFORMATION) {
354 /* Try again without the SACL. */
355 stats->num_get_sacl_priv_notheld++;
356 requestedInformation &= ~(SACL_SECURITY_INFORMATION |
357 LABEL_SECURITY_INFORMATION |
358 BACKUP_SECURITY_INFORMATION);
361 /* Fake success (useful when capturing as
362 * non-Administrator). */
363 stats->num_get_sd_access_denied++;
364 status = STATUS_SUCCESS;
369 /* Add the security descriptor to the WIM image, and save its ID in
371 inode->i_security_id = sd_set_add_sd(sd_set, buf, len_needed);
372 if (unlikely(inode->i_security_id < 0))
373 status = STATUS_NO_MEMORY;
375 if (unlikely(buf != _buf))
381 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
384 size_t full_path_nchars,
385 const wchar_t *filename,
386 size_t filename_nchars,
387 struct capture_params *params,
388 struct winnt_scan_stats *stats,
392 winnt_recurse_directory(HANDLE h,
394 size_t full_path_nchars,
395 struct wim_dentry *parent,
396 struct capture_params *params,
397 struct winnt_scan_stats *stats,
401 const size_t bufsize = 8192;
402 IO_STATUS_BLOCK iosb;
406 buf = MALLOC(bufsize);
408 return WIMLIB_ERR_NOMEM;
410 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
411 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
413 while (NT_SUCCESS(status = (*func_NtQueryDirectoryFile)(h, NULL, NULL, NULL,
415 FileNamesInformation,
416 FALSE, NULL, FALSE)))
418 const FILE_NAMES_INFORMATION *info = buf;
420 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
421 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
422 info->FileName[1] == L'.'))
426 struct wim_dentry *child;
428 p = full_path + full_path_nchars;
429 /* Only add a backslash if we don't already have
430 * one. This prevents a duplicate backslash
431 * from being added when the path to the capture
432 * dir had a trailing backslash. */
433 if (*(p - 1) != L'\\')
436 p = wmempcpy(filename, info->FileName,
437 info->FileNameLength / 2);
440 ret = winnt_build_dentry_tree_recursive(
446 info->FileNameLength / 2,
451 full_path[full_path_nchars] = L'\0';
456 dentry_add_child(parent, child);
458 if (info->NextEntryOffset == 0)
460 info = (const FILE_NAMES_INFORMATION *)
461 ((const u8 *)info + info->NextEntryOffset);
465 if (unlikely(status != STATUS_NO_MORE_FILES)) {
466 winnt_error(status, L"\"%ls\": Can't read directory",
467 printable_path(full_path));
468 ret = WIMLIB_ERR_READ;
475 /* Reparse point fixup status code */
477 /* Reparse point will be captured literally (no fixup) */
480 /* Reparse point will be captured with fixup */
485 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
488 IO_STATUS_BLOCK iosb;
489 FILE_INTERNAL_INFORMATION int_info;
490 FILE_FS_VOLUME_INFORMATION vol_info;
492 status = (*func_NtQueryInformationFile)(h, &iosb,
493 &int_info, sizeof(int_info),
494 FileInternalInformation);
495 if (!NT_SUCCESS(status))
498 if (int_info.IndexNumber.QuadPart != ino)
501 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
502 &vol_info, sizeof(vol_info),
503 FileFsVolumeInformation);
504 if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
507 if (iosb.Information <
508 offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
509 sizeof(vol_info.VolumeSerialNumber))
512 return (vol_info.VolumeSerialNumber == dev);
516 * Given an (expected) NT namespace symbolic link or junction target @target of
517 * length @target_nbytes, determine if a prefix of the target points to a file
518 * identified by @capture_root_ino and @capture_root_dev.
520 * If yes, return a pointer to the portion of the link following this prefix.
522 * If no, return NULL.
524 * If the link target does not appear to be a valid NT namespace path, return
527 static const wchar_t *
528 winnt_get_root_relative_target(const wchar_t *target, size_t target_nbytes,
529 u64 capture_root_ino, u64 capture_root_dev)
532 OBJECT_ATTRIBUTES attr;
533 IO_STATUS_BLOCK iosb;
535 const wchar_t *target_end;
538 target_end = target + (target_nbytes / sizeof(wchar_t));
541 if (target_end == target)
544 /* No leading slash??? */
545 if (target[0] != L'\\')
549 if ((target_end - target) >= 2 &&
550 target[0] == L'\\' && target[1] == L'\\')
553 attr.Length = sizeof(attr);
554 attr.RootDirectory = NULL;
555 attr.ObjectName = &name;
557 attr.SecurityDescriptor = NULL;
558 attr.SecurityQualityOfService = NULL;
560 name.Buffer = (wchar_t *)target;
565 const wchar_t *orig_p = p;
567 /* Skip non-backslashes */
568 while (p != target_end && *p != L'\\')
571 /* Skip backslashes */
572 while (p != target_end && *p == L'\\')
575 /* Append path component */
576 name.Length += (p - orig_p) * sizeof(wchar_t);
577 name.MaximumLength = name.Length;
579 /* Try opening the file */
580 status = (*func_NtOpenFile) (&h,
581 FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
584 FILE_SHARE_VALID_FLAGS,
585 FILE_OPEN_FOR_BACKUP_INTENT);
587 if (NT_SUCCESS(status)) {
588 /* Reset root directory */
589 if (attr.RootDirectory)
590 (*func_NtClose)(attr.RootDirectory);
591 attr.RootDirectory = h;
592 name.Buffer = (wchar_t *)p;
595 if (file_has_ino_and_dev(h, capture_root_ino,
597 goto out_close_root_dir;
599 } while (p != target_end);
604 if (attr.RootDirectory)
605 (*func_NtClose)(attr.RootDirectory);
610 winnt_rpfix_progress(struct capture_params *params, const wchar_t *path,
611 const struct reparse_data *rpdata, int scan_status)
613 size_t print_name_nchars = rpdata->print_name_nbytes / sizeof(wchar_t);
614 wchar_t print_name0[print_name_nchars + 1];
616 wmemcpy(print_name0, rpdata->print_name, print_name_nchars);
617 print_name0[print_name_nchars] = L'\0';
619 params->progress.scan.cur_path = printable_path(path);
620 params->progress.scan.symlink_target = print_name0;
621 return do_capture_progress(params, scan_status, NULL);
625 winnt_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
626 u64 capture_root_ino, u64 capture_root_dev,
627 const wchar_t *path, struct capture_params *params)
629 struct reparse_data rpdata;
630 const wchar_t *rel_target;
633 if (parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata)) {
634 /* Couldn't even understand the reparse data. Don't try the
640 * Don't do reparse point fixups on relative symbolic links.
642 * On Windows, a relative symbolic link is supposed to be identifiable
643 * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
644 * SYMBOLIC_LINK_RELATIVE. We will use this information, although this
645 * may not always do what the user expects, since drive-relative
646 * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
647 * set, in addition to truely relative symbolic links such as "Users" or
648 * "Users\Public". However, WIMGAPI (as of Windows 8.1) has this same
651 * Otherwise, as far as I can tell, the targets of symbolic links that
652 * are NOT relative, as well as junctions (note: a mountpoint is the
653 * sames thing as a junction), must be NT namespace paths, for example:
655 * - \??\e:\Users\Public
656 * - \DosDevices\e:\Users\Public
657 * - \Device\HardDiskVolume4\Users\Public
658 * - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
659 * - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
661 if (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
662 (rpdata.rpflags & SYMBOLIC_LINK_RELATIVE))
665 rel_target = winnt_get_root_relative_target(rpdata.substitute_name,
666 rpdata.substitute_name_nbytes,
670 /* Target points outside of the tree being captured. Don't
672 ret = winnt_rpfix_progress(params, path, &rpdata,
673 WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK);
679 if (rel_target == rpdata.substitute_name) {
680 /* Weird target --- keep the reparse point and don't mess with
685 /* We have an absolute target pointing within the directory being
686 * captured. @rel_target is the suffix of the link target that is the
687 * part relative to the directory being captured.
689 * We will cut off the prefix before this part (which is the path to the
690 * directory being captured) and add a dummy prefix. Since the process
691 * will need to be reversed when applying the image, it shouldn't matter
692 * what exactly the prefix is, as long as it looks like an absolute
697 size_t rel_target_nbytes =
698 rpdata.substitute_name_nbytes - ((const u8 *)rel_target -
699 (const u8 *)rpdata.substitute_name);
700 size_t rel_target_nchars = rel_target_nbytes / sizeof(wchar_t);
702 wchar_t tmp[rel_target_nchars + 7];
704 wmemcpy(tmp, L"\\??\\X:\\", 7);
705 wmemcpy(tmp + 7, rel_target, rel_target_nchars);
707 rpdata.substitute_name = tmp;
708 rpdata.substitute_name_nbytes = rel_target_nbytes + (7 * sizeof(wchar_t));
709 rpdata.print_name = tmp + 4;
710 rpdata.print_name_nbytes = rel_target_nbytes + (3 * sizeof(wchar_t));
712 if (make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p))
715 ret = winnt_rpfix_progress(params, path, &rpdata,
716 WIMLIB_SCAN_DENTRY_FIXED_SYMLINK);
723 * Loads the reparse point data from a reparse point into memory, optionally
724 * fixing the targets of absolute symbolic links and junction points to be
725 * relative to the root of capture.
728 * Open handle to the reparse point file.
730 * Path to the reparse point file.
732 * Capture parameters. add_flags, capture_root_ino, capture_root_dev,
733 * progfunc, progctx, and progress are used.
735 * Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which the
736 * reparse point buffer will be loaded.
738 * On success, the length of the reparse point buffer in bytes is written
741 * On success, returns a negative `enum rp_status' value.
742 * On failure, returns a positive error code.
745 winnt_get_reparse_data(HANDLE h, const wchar_t *path,
746 struct capture_params *params,
747 u8 *rpbuf, u16 *rpbuflen_ret)
749 DWORD bytes_returned;
754 if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
755 NULL, 0, rpbuf, REPARSE_POINT_MAX_SIZE,
756 &bytes_returned, NULL))
758 win32_error(GetLastError(), L"\"%ls\": Can't get reparse data",
759 printable_path(path));
760 return WIMLIB_ERR_READ;
763 if (unlikely(bytes_returned < REPARSE_DATA_OFFSET)) {
764 ERROR("\"%ls\": Reparse point data is invalid",
765 printable_path(path));
766 return WIMLIB_ERR_INVALID_REPARSE_DATA;
769 rpbuflen = bytes_returned;
770 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
772 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
773 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
774 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
776 ret = winnt_try_rpfix(rpbuf, &rpbuflen,
777 params->capture_root_ino,
778 params->capture_root_dev,
781 *rpbuflen_ret = rpbuflen;
786 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
789 *(u64*)_size_ret += len;
790 return ERROR_SUCCESS;
794 win32_get_encrypted_file_size(const wchar_t *path, bool is_dir, u64 *size_ret)
802 flags |= CREATE_FOR_DIR;
804 err = OpenEncryptedFileRaw(path, flags, &file_ctx);
805 if (err != ERROR_SUCCESS) {
807 L"Failed to open encrypted file \"%ls\" for raw read",
808 printable_path(path));
809 return WIMLIB_ERR_OPEN;
812 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
814 if (err != ERROR_SUCCESS) {
816 L"Failed to read raw encrypted data from \"%ls\"",
817 printable_path(path));
818 ret = WIMLIB_ERR_READ;
822 CloseEncryptedFileRaw(file_ctx);
827 winnt_scan_efsrpc_raw_data(struct wim_inode *inode, const wchar_t *nt_path,
828 struct list_head *unhashed_blobs)
830 struct blob_descriptor *blob;
831 struct wim_inode_stream *strm;
834 blob = new_blob_descriptor();
838 blob->file_on_disk = WCSDUP(nt_path);
839 if (!blob->file_on_disk)
841 blob->blob_location = BLOB_WIN32_ENCRYPTED;
843 /* OpenEncryptedFileRaw() expects a Win32 name. */
844 wimlib_assert(!wmemcmp(blob->file_on_disk, L"\\??\\", 4));
845 blob->file_on_disk[1] = L'\\';
847 blob->file_inode = inode;
849 ret = win32_get_encrypted_file_size(blob->file_on_disk,
850 (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY),
855 /* Empty EFSRPC data does not make sense */
856 wimlib_assert(blob->size != 0);
858 strm = inode_add_stream(inode, STREAM_TYPE_EFSRPC_RAW_DATA,
859 NO_STREAM_NAME, blob);
863 prepare_unhashed_blob(blob, inode, strm->stream_id, unhashed_blobs);
867 ret = WIMLIB_ERR_NOMEM;
869 free_blob_descriptor(blob);
874 get_data_stream_name(wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
875 wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
877 const wchar_t *sep, *type, *end;
879 /* The stream name should be returned as :NAME:TYPE */
880 if (raw_stream_name_nchars < 1)
882 if (raw_stream_name[0] != L':')
886 raw_stream_name_nchars--;
888 end = raw_stream_name + raw_stream_name_nchars;
890 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
898 if (wmemcmp(type, L"$DATA", 5))
901 *stream_name_ret = raw_stream_name;
902 *stream_name_nchars_ret = sep - raw_stream_name;
906 /* Build the path to the data stream. For unnamed streams, this is simply the
907 * path to the file. For named streams, this is the path to the file, followed
908 * by a colon, followed by the stream name. */
910 build_data_stream_path(const wchar_t *path, size_t path_nchars,
911 const wchar_t *stream_name, size_t stream_name_nchars)
913 size_t stream_path_nchars;
914 wchar_t *stream_path;
917 stream_path_nchars = path_nchars;
918 if (stream_name_nchars)
919 stream_path_nchars += 1 + stream_name_nchars;
921 stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
923 p = wmempcpy(stream_path, path, path_nchars);
924 if (stream_name_nchars) {
926 p = wmempcpy(p, stream_name, stream_name_nchars);
934 winnt_scan_data_stream(const wchar_t *path, size_t path_nchars,
935 wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
937 struct wim_inode *inode, struct list_head *unhashed_blobs)
939 wchar_t *stream_name;
940 size_t stream_name_nchars;
941 struct blob_descriptor *blob;
942 struct wim_inode_stream *strm;
944 /* Given the raw stream name (which is something like
945 * :streamname:$DATA), extract just the stream name part (streamname).
946 * Ignore any non-$DATA streams. */
947 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
948 &stream_name, &stream_name_nchars))
951 stream_name[stream_name_nchars] = L'\0';
953 /* If the stream is non-empty, set up a blob descriptor for it. */
954 if (stream_size != 0) {
955 blob = new_blob_descriptor();
958 blob->file_on_disk = build_data_stream_path(path,
962 if (!blob->file_on_disk)
964 blob->blob_location = BLOB_IN_WINNT_FILE_ON_DISK;
965 blob->size = stream_size;
966 blob->file_inode = inode;
971 strm = inode_add_stream(inode, STREAM_TYPE_DATA, stream_name, blob);
975 prepare_unhashed_blob(blob, inode, strm->stream_id, unhashed_blobs);
979 free_blob_descriptor(blob);
980 return WIMLIB_ERR_NOMEM;
984 * Load information about the data streams of an open file into a WIM inode.
986 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
987 * and FindNextStream(). This is done for two reasons:
989 * - FindFirstStream() opens its own handle to the file or directory and
990 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
991 * causing access denied errors on certain files (even when running as the
993 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
994 * and later, whereas the stream support in NtQueryInformationFile() was
995 * already present in Windows XP.
998 winnt_scan_data_streams(HANDLE h, const wchar_t *path, size_t path_nchars,
999 struct wim_inode *inode, struct list_head *unhashed_blobs,
1000 u64 file_size, u32 vol_flags)
1003 u8 _buf[1024] _aligned_attribute(8);
1006 IO_STATUS_BLOCK iosb;
1008 FILE_STREAM_INFORMATION *info;
1011 bufsize = sizeof(_buf);
1013 if (!(vol_flags & FILE_NAMED_STREAMS))
1016 /* Get a buffer containing the stream information. */
1017 while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(h,
1021 FileStreamInformation)))
1025 case STATUS_BUFFER_OVERFLOW:
1031 newbuf = MALLOC(bufsize);
1033 newbuf = REALLOC(buf, bufsize);
1035 ret = WIMLIB_ERR_NOMEM;
1041 case STATUS_NOT_IMPLEMENTED:
1042 case STATUS_NOT_SUPPORTED:
1043 case STATUS_INVALID_INFO_CLASS:
1047 L"\"%ls\": Failed to query stream information",
1048 printable_path(path));
1049 ret = WIMLIB_ERR_READ;
1054 if (iosb.Information == 0) {
1055 /* No stream information. */
1060 /* Parse one or more stream information structures. */
1061 info = (FILE_STREAM_INFORMATION *)buf;
1063 /* Load the stream information. */
1064 ret = winnt_scan_data_stream(path, path_nchars,
1066 info->StreamNameLength / 2,
1067 info->StreamSize.QuadPart,
1068 inode, unhashed_blobs);
1072 if (info->NextEntryOffset == 0) {
1073 /* No more stream information. */
1076 /* Advance to next stream information. */
1077 info = (FILE_STREAM_INFORMATION *)
1078 ((u8 *)info + info->NextEntryOffset);
1084 /* The volume does not support named streams. Only capture the unnamed
1086 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1087 FILE_ATTRIBUTE_REPARSE_POINT))
1094 wchar_t stream_name[] = L"::$DATA";
1095 ret = winnt_scan_data_stream(path, path_nchars, stream_name, 7,
1096 file_size, inode, unhashed_blobs);
1099 /* Free buffer if allocated on heap. */
1100 if (unlikely(buf != _buf))
1106 get_sort_key(HANDLE h)
1108 STARTING_VCN_INPUT_BUFFER in = { .StartingVcn.QuadPart = 0 };
1109 RETRIEVAL_POINTERS_BUFFER out;
1110 DWORD bytesReturned;
1112 if (!DeviceIoControl(h, FSCTL_GET_RETRIEVAL_POINTERS,
1115 &bytesReturned, NULL))
1118 if (out.ExtentCount < 1)
1121 return out.Extents[0].Lcn.QuadPart;
1125 set_sort_key(struct wim_inode *inode, u64 sort_key)
1127 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1128 struct wim_inode_stream *strm = &inode->i_streams[i];
1129 struct blob_descriptor *blob = stream_blob_resolved(strm);
1130 if (blob && (blob->blob_location == BLOB_IN_WINNT_FILE_ON_DISK ||
1131 blob->blob_location == BLOB_WIN32_ENCRYPTED))
1132 blob->sort_key = sort_key;
1137 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1140 size_t full_path_nchars,
1141 const wchar_t *filename,
1142 size_t filename_nchars,
1143 struct capture_params *params,
1144 struct winnt_scan_stats *stats,
1147 struct wim_dentry *root = NULL;
1148 struct wim_inode *inode = NULL;
1152 FILE_ALL_INFORMATION file_info;
1153 ACCESS_MASK requestedPerms;
1156 ret = try_exclude(full_path, full_path_nchars, params);
1157 if (ret < 0) /* Excluded? */
1159 if (ret > 0) /* Error? */
1162 /* Open the file. */
1163 requestedPerms = FILE_READ_DATA |
1164 FILE_READ_ATTRIBUTES |
1166 ACCESS_SYSTEM_SECURITY |
1169 status = winnt_openat(cur_dir,
1170 (cur_dir ? filename : full_path),
1171 (cur_dir ? filename_nchars : full_path_nchars),
1174 if (unlikely(!NT_SUCCESS(status))) {
1175 if (status == STATUS_DELETE_PENDING) {
1176 WARNING("\"%ls\": Deletion pending; skipping file",
1177 printable_path(full_path));
1181 if (status == STATUS_ACCESS_DENIED &&
1182 (requestedPerms & FILE_READ_DATA)) {
1183 /* This happens on encrypted files. */
1184 requestedPerms &= ~FILE_READ_DATA;
1188 winnt_error(status, L"\"%ls\": Can't open file",
1189 printable_path(full_path));
1190 if (status == STATUS_FVE_LOCKED_VOLUME)
1191 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1193 ret = WIMLIB_ERR_OPEN;
1197 /* Get information about the file. */
1199 IO_STATUS_BLOCK iosb;
1201 status = (*func_NtQueryInformationFile)(h, &iosb,
1204 FileAllInformation);
1206 if (unlikely(!NT_SUCCESS(status) &&
1207 status != STATUS_BUFFER_OVERFLOW))
1210 L"\"%ls\": Can't get file information",
1211 printable_path(full_path));
1212 ret = WIMLIB_ERR_STAT;
1217 if (unlikely(!(requestedPerms & FILE_READ_DATA)) &&
1218 !(file_info.BasicInformation.FileAttributes & FILE_ATTRIBUTE_ENCRYPTED))
1220 ERROR("\"%ls\": Permission to read data was denied",
1221 printable_path(full_path));
1222 ret = WIMLIB_ERR_OPEN;
1226 if (unlikely(!cur_dir)) {
1228 /* Root of tree being captured; get volume information. */
1230 FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1231 FILE_FS_VOLUME_INFORMATION vol_info;
1232 IO_STATUS_BLOCK iosb;
1234 /* Get volume flags */
1235 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1238 FileFsAttributeInformation);
1239 if (likely((NT_SUCCESS(status) ||
1240 (status == STATUS_BUFFER_OVERFLOW)) &&
1241 (iosb.Information >=
1242 offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1243 FileSystemAttributes) +
1244 sizeof(attr_info.FileSystemAttributes))))
1246 vol_flags = attr_info.FileSystemAttributes;
1248 winnt_warning(status,
1249 L"\"%ls\": Can't get volume attributes",
1250 printable_path(full_path));
1254 /* Set inode number of root directory */
1255 params->capture_root_ino =
1256 file_info.InternalInformation.IndexNumber.QuadPart;
1258 /* Get volume ID. */
1259 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1262 FileFsVolumeInformation);
1263 if (likely((NT_SUCCESS(status) ||
1264 (status == STATUS_BUFFER_OVERFLOW)) &&
1265 (iosb.Information >=
1266 offsetof(FILE_FS_VOLUME_INFORMATION,
1267 VolumeSerialNumber) +
1268 sizeof(vol_info.VolumeSerialNumber))))
1270 params->capture_root_dev = vol_info.VolumeSerialNumber;
1272 winnt_warning(status, L"\"%ls\": Can't get volume ID",
1273 printable_path(full_path));
1274 params->capture_root_dev = 0;
1278 /* Create a WIM dentry with an associated inode, which may be shared.
1280 * However, we need to explicitly check for directories and files with
1281 * only 1 link and refuse to hard link them. This is because Windows
1282 * has a bug where it can return duplicate File IDs for files and
1283 * directories on the FAT filesystem.
1285 * Since we don't follow mount points on Windows, we don't need to query
1286 * the volume ID per-file. Just once, for the root, is enough. But we
1287 * can't simply pass 0, because then there could be inode collisions
1288 * among multiple calls to win32_build_dentry_tree() that are scanning
1289 * files on different volumes. */
1290 ret = inode_table_new_dentry(params->inode_table,
1292 file_info.InternalInformation.IndexNumber.QuadPart,
1293 params->capture_root_dev,
1294 (file_info.StandardInformation.NumberOfLinks <= 1 ||
1295 (file_info.BasicInformation.FileAttributes &
1296 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.BasicInformation.FileAttributes;
1322 inode->i_creation_time = file_info.BasicInformation.CreationTime.QuadPart;
1323 inode->i_last_write_time = file_info.BasicInformation.LastWriteTime.QuadPart;
1324 inode->i_last_access_time = file_info.BasicInformation.LastAccessTime.QuadPart;
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 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1346 /* See comment above assign_stream_types_encrypted() */
1347 WARNING("Ignoring reparse data of encrypted file \"%ls\"",
1348 printable_path(full_path));
1350 u8 rpbuf[REPARSE_POINT_MAX_SIZE] _aligned_attribute(8);
1353 ret = winnt_get_reparse_data(h, full_path, params,
1357 inode->i_not_rpfixed = 0;
1360 inode->i_not_rpfixed = 1;
1365 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1366 if (!inode_add_stream_with_data(inode,
1367 STREAM_TYPE_REPARSE_POINT,
1369 rpbuf + REPARSE_DATA_OFFSET,
1370 rpbuflen - REPARSE_DATA_OFFSET,
1371 params->blob_table))
1373 ret = WIMLIB_ERR_NOMEM;
1379 sort_key = get_sort_key(h);
1381 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1382 /* Load information about the raw encrypted data. This is
1383 * needed for any directory or non-directory that has
1384 * FILE_ATTRIBUTE_ENCRYPTED set.
1386 * Note: since OpenEncryptedFileRaw() fails with
1387 * ERROR_SHARING_VIOLATION if there are any open handles to the
1388 * file, we have to close the file and re-open it later if
1392 ret = winnt_scan_efsrpc_raw_data(inode, full_path,
1393 params->unhashed_blobs);
1398 * Load information about data streams (unnamed and named).
1400 * Skip this step for encrypted files, since the data from
1401 * ReadEncryptedFileRaw() already contains all data streams (and
1402 * they do in fact all get restored by WriteEncryptedFileRaw().)
1404 * Note: WIMGAPI (as of Windows 8.1) gets wrong and stores both
1405 * the EFSRPC data and the named data stream(s)...!
1407 ret = winnt_scan_data_streams(h,
1411 params->unhashed_blobs,
1412 file_info.StandardInformation.EndOfFile.QuadPart,
1418 set_sort_key(inode, sort_key);
1420 if (inode_is_directory(inode)) {
1422 /* Directory: recurse to children. */
1425 /* Re-open handle that was closed to read raw encrypted
1427 status = winnt_openat(cur_dir,
1429 filename : full_path),
1431 filename_nchars : full_path_nchars),
1432 FILE_LIST_DIRECTORY | SYNCHRONIZE,
1434 if (!NT_SUCCESS(status)) {
1436 L"\"%ls\": Can't re-open file",
1437 printable_path(full_path));
1438 ret = WIMLIB_ERR_OPEN;
1442 ret = winnt_recurse_directory(h,
1454 params->progress.scan.cur_path = printable_path(full_path);
1456 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1458 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1462 if (unlikely(ret)) {
1463 free_dentry_tree(root, params->blob_table);
1465 ret = report_capture_error(params, ret, full_path);
1472 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_stats *stats)
1474 if (likely(stats->num_get_sacl_priv_notheld == 0 &&
1475 stats->num_get_sd_access_denied == 0))
1478 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1479 if (stats->num_get_sacl_priv_notheld != 0) {
1480 WARNING("- Could not capture SACL (System Access Control List)\n"
1481 " on %lu files or directories.",
1482 stats->num_get_sacl_priv_notheld);
1484 if (stats->num_get_sd_access_denied != 0) {
1485 WARNING("- Could not capture security descriptor at all\n"
1486 " on %lu files or directories.",
1487 stats->num_get_sd_access_denied);
1489 WARNING("To fully capture all security descriptors, run the program\n"
1490 " with Administrator rights.");
1493 #define WINDOWS_NT_MAX_PATH 32768
1495 /* Win32 version of capturing a directory tree. */
1497 win32_build_dentry_tree(struct wim_dentry **root_ret,
1498 const wchar_t *root_disk_path,
1499 struct capture_params *params)
1503 UNICODE_STRING ntpath;
1504 struct winnt_scan_stats stats;
1505 size_t ntpath_nchars;
1507 /* WARNING: There is no check for overflow later when this buffer is
1508 * being used! But it's as long as the maximum path length understood
1509 * by Windows NT (which is NOT the same as MAX_PATH). */
1510 path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1512 return WIMLIB_ERR_NOMEM;
1514 ret = win32_path_to_nt_path(root_disk_path, &ntpath);
1518 if (ntpath.Length < 4 * sizeof(wchar_t) ||
1519 ntpath.Length > WINDOWS_NT_MAX_PATH * sizeof(wchar_t) ||
1520 wmemcmp(ntpath.Buffer, L"\\??\\", 4))
1522 ERROR("\"%ls\": unrecognized path format", root_disk_path);
1523 ret = WIMLIB_ERR_INVALID_PARAM;
1525 ntpath_nchars = ntpath.Length / sizeof(wchar_t);
1526 wmemcpy(path, ntpath.Buffer, ntpath_nchars);
1527 path[ntpath_nchars] = L'\0';
1529 params->capture_root_nchars = ntpath_nchars;
1530 if (path[ntpath_nchars - 1] == L'\\')
1531 params->capture_root_nchars--;
1534 HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
1538 memset(&stats, 0, sizeof(stats));
1540 ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
1541 path, ntpath_nchars,
1542 L"", 0, params, &stats, 0);
1546 winnt_do_scan_warnings(root_disk_path, &stats);
1550 #endif /* __WIN32__ */