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 Eric Biggers
10 * This file is part of wimlib, a library for working with WIM files.
12 * wimlib is free software; you can redistribute it and/or modify it under the
13 * terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 3 of the License, or (at your option)
17 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 * A PARTICULAR PURPOSE. See the GNU General Public License for more
22 * You should have received a copy of the GNU General Public License
23 * along with wimlib; if not, see http://www.gnu.org/licenses/.
32 #include "wimlib/win32_common.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/lookup_table.h"
40 #include "wimlib/paths.h"
41 #include "wimlib/reparse.h"
45 struct winnt_scan_stats {
46 unsigned long num_get_sd_access_denied;
47 unsigned long num_get_sacl_priv_notheld;
50 static inline const wchar_t *
51 printable_path(const wchar_t *full_path)
53 /* Skip over \\?\ or \??\ */
58 * If cur_dir is not NULL, open an existing file relative to the already-open
61 * Otherwise, open the file specified by @path, which must be a Windows NT
65 winnt_openat(HANDLE cur_dir, const wchar_t *path, size_t path_nchars,
66 ACCESS_MASK perms, HANDLE *h_ret)
69 OBJECT_ATTRIBUTES attr;
73 name.Length = path_nchars * sizeof(wchar_t);
74 name.MaximumLength = name.Length + sizeof(wchar_t);
75 name.Buffer = (wchar_t *)path;
77 attr.Length = sizeof(attr);
78 attr.RootDirectory = cur_dir;
79 attr.ObjectName = &name;
81 attr.SecurityDescriptor = NULL;
82 attr.SecurityQualityOfService = NULL;
85 status = (*func_NtOpenFile)(h_ret, perms, &attr, &iosb,
86 FILE_SHARE_VALID_FLAGS,
87 FILE_OPEN_REPARSE_POINT |
88 FILE_OPEN_FOR_BACKUP_INTENT |
89 FILE_SYNCHRONOUS_IO_NONALERT |
90 FILE_SEQUENTIAL_ONLY);
91 if (!NT_SUCCESS(status)) {
92 /* Try requesting fewer permissions */
93 if (status == STATUS_ACCESS_DENIED ||
94 status == STATUS_PRIVILEGE_NOT_HELD) {
95 if (perms & ACCESS_SYSTEM_SECURITY) {
96 perms &= ~ACCESS_SYSTEM_SECURITY;
99 if (perms & READ_CONTROL) {
100 perms &= ~READ_CONTROL;
108 /* Read the first @size bytes from the file, or named data stream of a file,
109 * from which the stream entry @lte was created. */
111 read_winnt_file_prefix(const struct wim_lookup_table_entry *lte, u64 size,
112 consume_data_callback_t cb, void *cb_ctx)
121 /* This is an NT namespace path. */
122 path = lte->file_on_disk;
124 status = winnt_openat(NULL, path, wcslen(path),
125 FILE_READ_DATA | SYNCHRONIZE, &h);
126 if (!NT_SUCCESS(status)) {
127 set_errno_from_nt_status(status);
128 ERROR_WITH_ERRNO("\"%ls\": Can't open for reading "
129 "(status=0x%08"PRIx32")",
130 printable_path(path), (u32)status);
131 return WIMLIB_ERR_OPEN;
135 bytes_remaining = size;
136 while (bytes_remaining) {
137 IO_STATUS_BLOCK iosb;
141 count = min(sizeof(buf), bytes_remaining);
143 status = (*func_NtReadFile)(h, NULL, NULL, NULL,
144 &iosb, buf, count, NULL, NULL);
145 if (!NT_SUCCESS(status)) {
146 set_errno_from_nt_status(status);
147 ERROR_WITH_ERRNO("\"%ls\": Error reading data "
148 "(status=0x%08"PRIx32")",
149 printable_path(path), (u32)status);
150 ret = WIMLIB_ERR_READ;
154 bytes_read = iosb.Information;
156 bytes_remaining -= bytes_read;
157 ret = (*cb)(buf, bytes_read, cb_ctx);
165 struct win32_encrypted_read_ctx {
166 consume_data_callback_t read_prefix_cb;
167 void *read_prefix_ctx;
173 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
175 struct win32_encrypted_read_ctx *ctx = _ctx;
177 size_t bytes_to_consume = min(len, ctx->bytes_remaining);
179 if (bytes_to_consume == 0)
180 return ERROR_SUCCESS;
182 ret = (*ctx->read_prefix_cb)(data, bytes_to_consume, ctx->read_prefix_ctx);
184 ctx->wimlib_err_code = ret;
185 /* Shouldn't matter what error code is returned here, as long as
186 * it isn't ERROR_SUCCESS. */
187 return ERROR_READ_FAULT;
189 ctx->bytes_remaining -= bytes_to_consume;
190 return ERROR_SUCCESS;
194 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
196 consume_data_callback_t cb, void *cb_ctx)
198 struct win32_encrypted_read_ctx export_ctx;
203 export_ctx.read_prefix_cb = cb;
204 export_ctx.read_prefix_ctx = cb_ctx;
205 export_ctx.wimlib_err_code = 0;
206 export_ctx.bytes_remaining = size;
208 err = OpenEncryptedFileRaw(lte->file_on_disk, 0, &file_ctx);
209 if (err != ERROR_SUCCESS) {
210 set_errno_from_win32_error(err);
211 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
213 printable_path(lte->file_on_disk));
214 return WIMLIB_ERR_OPEN;
216 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
217 &export_ctx, file_ctx);
218 if (err != ERROR_SUCCESS) {
219 set_errno_from_win32_error(err);
220 ERROR_WITH_ERRNO("Failed to read encrypted file \"%ls\"",
221 printable_path(lte->file_on_disk));
222 ret = export_ctx.wimlib_err_code;
224 ret = WIMLIB_ERR_READ;
225 } else if (export_ctx.bytes_remaining != 0) {
226 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
227 "encryted file \"%ls\"",
228 size - export_ctx.bytes_remaining, size,
229 printable_path(lte->file_on_disk));
230 ret = WIMLIB_ERR_READ;
234 CloseEncryptedFileRaw(file_ctx);
239 * Load the short name of a file into a WIM dentry.
242 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
244 /* It's not any harder to just make the NtQueryInformationFile() system
245 * call ourselves, and it saves a dumb call to FindFirstFile() which of
246 * course has to create its own handle. */
248 IO_STATUS_BLOCK iosb;
249 u8 buf[128] _aligned_attribute(8);
250 const FILE_NAME_INFORMATION *info;
252 status = (*func_NtQueryInformationFile)(h, &iosb, buf, sizeof(buf),
253 FileAlternateNameInformation);
254 info = (const FILE_NAME_INFORMATION *)buf;
255 if (NT_SUCCESS(status) && info->FileNameLength != 0) {
256 dentry->short_name = utf16le_dupz(info->FileName,
257 info->FileNameLength);
258 if (!dentry->short_name)
259 return STATUS_NO_MEMORY;
260 dentry->short_name_nbytes = info->FileNameLength;
266 * Load the security descriptor of a file into the corresponding inode, and the
267 * WIM image's security descriptor set.
270 winnt_get_security_descriptor(HANDLE h, struct wim_inode *inode,
271 struct wim_sd_set *sd_set,
272 struct winnt_scan_stats *stats, int add_flags)
274 SECURITY_INFORMATION requestedInformation;
275 u8 _buf[4096] _aligned_attribute(8);
281 requestedInformation = DACL_SECURITY_INFORMATION |
282 SACL_SECURITY_INFORMATION |
283 OWNER_SECURITY_INFORMATION |
284 GROUP_SECURITY_INFORMATION;
286 bufsize = sizeof(_buf);
289 * We need the file's security descriptor in
290 * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
291 * opened with as many relevant permissions as possible. At this point,
292 * on Windows there are a number of options for reading a file's
293 * security descriptor:
295 * GetFileSecurity(): This takes in a path and returns the
296 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle,
297 * not ours, and the handle created internally doesn't specify
298 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied
299 * errors on some files and directories, even when running as the
302 * GetSecurityInfo(): This takes in a handle and returns the security
303 * descriptor split into a bunch of different parts. This should work,
304 * but it's dumb because we have to put the security descriptor back
307 * BackupRead(): This can read the security descriptor, but this is a
308 * difficult-to-use API, probably only works as the Administrator, and
309 * the format of the returned data is not well documented.
311 * NtQuerySecurityObject(): This is exactly what we need, as it takes
312 * in a handle and returns the security descriptor in
313 * SECURITY_DESCRIPTOR_RELATIVE format. Only problem is that it's a
314 * ntdll function and therefore not officially part of the Win32 API.
317 while (!(NT_SUCCESS(status = (*func_NtQuerySecurityObject)(h,
318 requestedInformation,
319 (PSECURITY_DESCRIPTOR)buf,
324 case STATUS_BUFFER_TOO_SMALL:
325 wimlib_assert(buf == _buf);
326 buf = MALLOC(len_needed);
328 return STATUS_NO_MEMORY;
329 bufsize = len_needed;
331 case STATUS_PRIVILEGE_NOT_HELD:
332 case STATUS_ACCESS_DENIED:
333 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
335 /* Permission denied in STRICT_ACLS mode, or
339 if (requestedInformation & SACL_SECURITY_INFORMATION) {
340 /* Try again without the SACL. */
341 stats->num_get_sacl_priv_notheld++;
342 requestedInformation &= ~SACL_SECURITY_INFORMATION;
345 /* Fake success (useful when capturing as
346 * non-Administrator). */
347 stats->num_get_sd_access_denied++;
348 status = STATUS_SUCCESS;
353 /* Add the security descriptor to the WIM image, and save its ID in
355 inode->i_security_id = sd_set_add_sd(sd_set, buf, len_needed);
356 if (unlikely(inode->i_security_id < 0))
357 status = STATUS_NO_MEMORY;
359 if (unlikely(buf != _buf))
365 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
368 size_t full_path_nchars,
369 const wchar_t *filename,
370 size_t filename_nchars,
371 struct add_image_params *params,
372 struct winnt_scan_stats *stats,
376 winnt_recurse_directory(HANDLE h,
378 size_t full_path_nchars,
379 struct wim_dentry *parent,
380 struct add_image_params *params,
381 struct winnt_scan_stats *stats,
385 const size_t bufsize = 8192;
386 IO_STATUS_BLOCK iosb;
390 buf = MALLOC(bufsize);
392 return WIMLIB_ERR_NOMEM;
394 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
395 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
397 while (NT_SUCCESS(status = (*func_NtQueryDirectoryFile)(h, NULL, NULL, NULL,
399 FileNamesInformation,
400 FALSE, NULL, FALSE)))
402 const FILE_NAMES_INFORMATION *info = buf;
404 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
405 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
406 info->FileName[1] == L'.'))
409 struct wim_dentry *child;
411 p = full_path + full_path_nchars;
413 p = wmempcpy(p, info->FileName,
414 info->FileNameLength / 2);
417 ret = winnt_build_dentry_tree_recursive(
422 full_path + full_path_nchars + 1,
423 info->FileNameLength / 2,
428 full_path[full_path_nchars] = L'\0';
433 dentry_add_child(parent, child);
435 if (info->NextEntryOffset == 0)
437 info = (const FILE_NAMES_INFORMATION *)
438 ((const u8 *)info + info->NextEntryOffset);
442 if (unlikely(status != STATUS_NO_MORE_FILES)) {
443 set_errno_from_nt_status(status);
444 ERROR_WITH_ERRNO("\"%ls\": Can't read directory "
445 "(status=0x%08"PRIx32")",
446 printable_path(full_path), (u32)status);
447 ret = WIMLIB_ERR_READ;
454 /* Reparse point fixup status code */
456 /* Reparse point will be captured literally (no fixup) */
459 /* Reparse point will be captured with fixup */
464 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
467 IO_STATUS_BLOCK iosb;
468 FILE_INTERNAL_INFORMATION int_info;
469 FILE_FS_VOLUME_INFORMATION vol_info;
471 status = (*func_NtQueryInformationFile)(h, &iosb,
472 &int_info, sizeof(int_info),
473 FileInternalInformation);
474 if (!NT_SUCCESS(status))
477 if (int_info.IndexNumber.QuadPart != ino)
480 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
481 &vol_info, sizeof(vol_info),
482 FileFsVolumeInformation);
483 if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
486 if (iosb.Information <
487 offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
488 sizeof(vol_info.VolumeSerialNumber))
491 return (vol_info.VolumeSerialNumber == dev);
495 * Given an (expected) NT namespace symbolic link or junction target @target of
496 * length @target_nbytes, determine if a prefix of the target points to a file
497 * identified by @capture_root_ino and @capture_root_dev.
499 * If yes, return a pointer to the portion of the link following this prefix.
501 * If no, return NULL.
503 * If the link target does not appear to be a valid NT namespace path, return
506 static const wchar_t *
507 winnt_get_root_relative_target(const wchar_t *target, size_t target_nbytes,
508 u64 capture_root_ino, u64 capture_root_dev)
511 OBJECT_ATTRIBUTES attr;
512 IO_STATUS_BLOCK iosb;
514 const wchar_t *target_end;
517 target_end = target + (target_nbytes / sizeof(wchar_t));
520 if (target_end == target)
523 /* No leading slash??? */
524 if (target[0] != L'\\')
528 if ((target_end - target) >= 2 &&
529 target[0] == L'\\' && target[1] == L'\\')
532 attr.Length = sizeof(attr);
533 attr.RootDirectory = NULL;
534 attr.ObjectName = &name;
536 attr.SecurityDescriptor = NULL;
537 attr.SecurityQualityOfService = NULL;
539 name.Buffer = (wchar_t *)target;
544 const wchar_t *orig_p = p;
546 /* Skip non-backslashes */
547 while (p != target_end && *p != L'\\')
550 /* Skip backslashes */
551 while (p != target_end && *p == L'\\')
554 /* Append path component */
555 name.Length += (p - orig_p) * sizeof(wchar_t);
556 name.MaximumLength = name.Length;
558 /* Try opening the file */
559 status = (*func_NtOpenFile) (&h,
560 FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
563 FILE_SHARE_VALID_FLAGS,
564 FILE_OPEN_FOR_BACKUP_INTENT);
566 if (NT_SUCCESS(status)) {
567 /* Reset root directory */
568 if (attr.RootDirectory)
569 (*func_NtClose)(attr.RootDirectory);
570 attr.RootDirectory = h;
571 name.Buffer = (wchar_t *)p;
574 if (file_has_ino_and_dev(h, capture_root_ino,
576 goto out_close_root_dir;
578 } while (p != target_end);
583 if (attr.RootDirectory)
584 (*func_NtClose)(attr.RootDirectory);
589 winnt_rpfix_progress(struct add_image_params *params, const wchar_t *path,
590 const struct reparse_data *rpdata,
591 enum wimlib_progress_msg msg)
593 size_t print_name_nchars = rpdata->print_name_nbytes / sizeof(wchar_t);
594 wchar_t print_name0[print_name_nchars + 1];
596 wmemcpy(print_name0, rpdata->print_name, print_name_nchars);
597 print_name0[print_name_nchars] = L'\0';
599 params->progress.scan.cur_path = printable_path(path);
600 params->progress.scan.symlink_target = print_name0;
601 return do_capture_progress(params, msg, NULL);
605 winnt_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
606 u64 capture_root_ino, u64 capture_root_dev,
607 const wchar_t *path, struct add_image_params *params)
609 struct reparse_data rpdata;
610 const wchar_t *rel_target;
613 if (parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata)) {
614 /* Couldn't even understand the reparse data. Don't try the
620 * Don't do reparse point fixups on relative symbolic links.
622 * On Windows, a relative symbolic link is supposed to be identifiable
623 * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
624 * SYMBOLIC_LINK_RELATIVE. We will use this information, although this
625 * may not always do what the user expects, since drive-relative
626 * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
627 * set, in addition to truely relative symbolic links such as "Users" or
628 * "Users\Public". However, WIMGAPI (as of Windows 8.1) has this same
631 * Otherwise, as far as I can tell, the targets of symbolic links that
632 * are NOT relative, as well as junctions (note: a mountpoint is the
633 * sames thing as a junction), must be NT namespace paths, for example:
635 * - \??\e:\Users\Public
636 * - \DosDevices\e:\Users\Public
637 * - \Device\HardDiskVolume4\Users\Public
638 * - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
639 * - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
641 if (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
642 (rpdata.rpflags & SYMBOLIC_LINK_RELATIVE))
645 rel_target = winnt_get_root_relative_target(rpdata.substitute_name,
646 rpdata.substitute_name_nbytes,
650 /* Target points outside of the tree being captured. Don't
652 ret = winnt_rpfix_progress(params, path, &rpdata,
653 WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK);
659 if (rel_target == rpdata.substitute_name) {
660 /* Weird target --- keep the reparse point and don't mess with
665 /* We have an absolute target pointing within the directory being
666 * captured, @rel_target is the suffix of the link target that is the
667 * part relative to the directory being captured.
669 * We will cut off the prefix before this part (which is the path to the
670 * directory being captured) and add a dummy prefix. Since the process
671 * will need to be reversed when applying the image, it shouldn't matter
672 * what exactly the prefix is, as long as it looks like an absolute
677 size_t rel_target_nbytes =
678 rpdata.substitute_name_nbytes - ((const u8 *)rel_target -
679 (const u8 *)rpdata.substitute_name);
680 size_t rel_target_nchars = rel_target_nbytes / sizeof(wchar_t);
682 wchar_t tmp[rel_target_nchars + 7];
684 wmemcpy(tmp, L"\\??\\X:\\", 7);
685 wmemcpy(tmp + 7, rel_target, rel_target_nchars);
687 rpdata.substitute_name = tmp;
688 rpdata.substitute_name_nbytes = rel_target_nbytes + (7 * sizeof(wchar_t));
689 rpdata.print_name = tmp + 4;
690 rpdata.print_name_nbytes = rel_target_nbytes + (3 * sizeof(wchar_t));
692 if (make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p))
695 ret = winnt_rpfix_progress(params, path, &rpdata,
696 WIMLIB_SCAN_DENTRY_FIXED_SYMLINK);
703 * Loads the reparse point data from a reparse point into memory, optionally
704 * fixing the targets of absolute symbolic links and junction points to be
705 * relative to the root of capture.
708 * Open handle to the reparse point file.
710 * Path to the reparse point file.
712 * Capture parameters. add_flags, capture_root_ino, capture_root_dev,
713 * progfunc, progctx, and progress are used.
715 * Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which the
716 * reparse point buffer will be loaded.
718 * On success, the length of the reparse point buffer in bytes is written
721 * On success, returns a negative `enum rp_status' value.
722 * On failure, returns a positive error code.
725 winnt_get_reparse_data(HANDLE h, const wchar_t *path,
726 struct add_image_params *params,
727 u8 *rpbuf, u16 *rpbuflen_ret)
729 DWORD bytes_returned;
734 if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
735 NULL, 0, rpbuf, REPARSE_POINT_MAX_SIZE,
736 &bytes_returned, NULL))
738 set_errno_from_GetLastError();
739 return WIMLIB_ERR_READ;
742 if (unlikely(bytes_returned < 8)) {
744 return WIMLIB_ERR_INVALID_REPARSE_DATA;
747 rpbuflen = bytes_returned;
748 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
750 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
751 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
752 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
754 ret = winnt_try_rpfix(rpbuf, &rpbuflen,
755 params->capture_root_ino,
756 params->capture_root_dev,
759 *rpbuflen_ret = rpbuflen;
764 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
767 *(u64*)_size_ret += len;
768 return ERROR_SUCCESS;
772 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
778 err = OpenEncryptedFileRaw(path, 0, &file_ctx);
779 if (err != ERROR_SUCCESS) {
780 set_errno_from_win32_error(err);
781 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
782 "for raw read", printable_path(path));
783 return WIMLIB_ERR_OPEN;
786 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
788 if (err != ERROR_SUCCESS) {
789 set_errno_from_win32_error(err);
790 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
791 "\"%ls\"", printable_path(path));
792 ret = WIMLIB_ERR_READ;
796 CloseEncryptedFileRaw(file_ctx);
801 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
802 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
804 const wchar_t *sep, *type, *end;
806 /* The stream name should be returned as :NAME:TYPE */
807 if (raw_stream_name_nchars < 1)
809 if (raw_stream_name[0] != L':')
813 raw_stream_name_nchars--;
815 end = raw_stream_name + raw_stream_name_nchars;
817 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
825 if (wmemcmp(type, L"$DATA", 5))
828 *stream_name_ret = raw_stream_name;
829 *stream_name_nchars_ret = sep - raw_stream_name;
834 build_stream_path(const wchar_t *path, size_t path_nchars,
835 const wchar_t *stream_name, size_t stream_name_nchars)
837 size_t stream_path_nchars;
838 wchar_t *stream_path;
841 stream_path_nchars = path_nchars;
842 if (stream_name_nchars)
843 stream_path_nchars += 1 + stream_name_nchars;
845 stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
847 p = wmempcpy(stream_path, path, path_nchars);
848 if (stream_name_nchars) {
850 p = wmempcpy(p, stream_name, stream_name_nchars);
858 winnt_scan_stream(const wchar_t *path, size_t path_nchars,
859 const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
861 struct wim_inode *inode, struct list_head *unhashed_streams)
863 const wchar_t *stream_name;
864 size_t stream_name_nchars;
865 struct wim_ads_entry *ads_entry;
866 wchar_t *stream_path;
867 struct wim_lookup_table_entry *lte;
870 /* Given the raw stream name (which is something like
871 * :streamname:$DATA), extract just the stream name part.
872 * Ignore any non-$DATA streams. */
873 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
874 &stream_name, &stream_name_nchars))
877 /* If this is a named stream, allocate an ADS entry for it. */
878 if (stream_name_nchars) {
879 ads_entry = inode_add_ads_utf16le(inode, stream_name,
883 return WIMLIB_ERR_NOMEM;
888 /* If the stream is empty, no lookup table entry is needed. */
889 if (stream_size == 0)
892 /* Build the path to the stream. For unnamed streams, this is simply
893 * the path to the file. For named streams, this is the path to the
894 * file, followed by a colon, followed by the stream name. */
895 stream_path = build_stream_path(path, path_nchars,
896 stream_name, stream_name_nchars);
898 return WIMLIB_ERR_NOMEM;
900 /* Set up the lookup table entry for the stream. */
901 lte = new_lookup_table_entry();
904 return WIMLIB_ERR_NOMEM;
906 lte->file_on_disk = stream_path;
907 lte->resource_location = RESOURCE_IN_WINNT_FILE_ON_DISK;
908 lte->size = stream_size;
909 if ((inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) && !ads_entry) {
910 /* Special case for encrypted file. */
912 /* OpenEncryptedFileRaw() expects Win32 name, not NT name.
913 * Change \??\ into \\?\ */
914 lte->file_on_disk[1] = L'\\';
915 wimlib_assert(!wmemcmp(lte->file_on_disk, L"\\\\?\\", 4));
920 ret = win32_get_encrypted_file_size(lte->file_on_disk,
923 free_lookup_table_entry(lte);
926 lte->size = encrypted_size;
927 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
931 stream_id = ads_entry->stream_id;
932 ads_entry->lte = lte;
937 add_unhashed_stream(lte, inode, stream_id, unhashed_streams);
942 * Load information about the streams of an open file into a WIM inode.
944 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
945 * and FindNextStream(). This is done for two reasons:
947 * - FindFirstStream() opens its own handle to the file or directory and
948 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
949 * causing access denied errors on certain files (even when running as the
951 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
952 * and later, whereas the stream support in NtQueryInformationFile() was
953 * already present in Windows XP.
956 winnt_scan_streams(HANDLE *hFile_p, const wchar_t *path, size_t path_nchars,
957 struct wim_inode *inode, struct list_head *unhashed_streams,
958 u64 file_size, u32 vol_flags)
961 u8 _buf[1024] _aligned_attribute(8);
964 IO_STATUS_BLOCK iosb;
966 const FILE_STREAM_INFORMATION *info;
969 bufsize = sizeof(_buf);
971 if (!(vol_flags & FILE_NAMED_STREAMS))
974 /* Get a buffer containing the stream information. */
975 while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(*hFile_p,
979 FileStreamInformation)))
983 case STATUS_BUFFER_OVERFLOW:
989 newbuf = MALLOC(bufsize);
991 newbuf = REALLOC(buf, bufsize);
993 ret = WIMLIB_ERR_NOMEM;
999 case STATUS_NOT_IMPLEMENTED:
1000 case STATUS_NOT_SUPPORTED:
1001 case STATUS_INVALID_INFO_CLASS:
1004 set_errno_from_nt_status(status);
1005 ERROR_WITH_ERRNO("\"%ls\": Failed to query stream "
1006 "information (status=0x%08"PRIx32")",
1007 printable_path(path), (u32)status);
1008 ret = WIMLIB_ERR_READ;
1013 if (iosb.Information == 0) {
1014 /* No stream information. */
1019 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1020 /* OpenEncryptedFileRaw() seems to fail with
1021 * ERROR_SHARING_VIOLATION if there are any handles opened to
1023 (*func_NtClose)(*hFile_p);
1024 *hFile_p = INVALID_HANDLE_VALUE;
1027 /* Parse one or more stream information structures. */
1028 info = (const FILE_STREAM_INFORMATION *)buf;
1030 /* Load the stream information. */
1031 ret = winnt_scan_stream(path, path_nchars,
1033 info->StreamNameLength / 2,
1034 info->StreamSize.QuadPart,
1035 inode, unhashed_streams);
1039 if (info->NextEntryOffset == 0) {
1040 /* No more stream information. */
1043 /* Advance to next stream information. */
1044 info = (const FILE_STREAM_INFORMATION *)
1045 ((const u8 *)info + info->NextEntryOffset);
1051 /* The volume does not support named streams. Only capture the unnamed
1053 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1054 FILE_ATTRIBUTE_REPARSE_POINT))
1060 ret = winnt_scan_stream(path, path_nchars, L"::$DATA", 7,
1061 file_size, inode, unhashed_streams);
1063 /* Free buffer if allocated on heap. */
1064 if (unlikely(buf != _buf))
1070 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1073 size_t full_path_nchars,
1074 const wchar_t *filename,
1075 size_t filename_nchars,
1076 struct add_image_params *params,
1077 struct winnt_scan_stats *stats,
1080 struct wim_dentry *root = NULL;
1081 struct wim_inode *inode = NULL;
1082 HANDLE h = INVALID_HANDLE_VALUE;
1085 FILE_ALL_INFORMATION file_info;
1090 if (should_exclude_path(full_path + params->capture_root_nchars,
1091 full_path_nchars - params->capture_root_nchars,
1095 /* Open the file. */
1096 status = winnt_openat(cur_dir,
1097 (cur_dir ? filename : full_path),
1098 (cur_dir ? filename_nchars : full_path_nchars),
1100 FILE_READ_ATTRIBUTES |
1102 ACCESS_SYSTEM_SECURITY |
1105 if (unlikely(!NT_SUCCESS(status))) {
1106 set_errno_from_nt_status(status);
1107 ERROR_WITH_ERRNO("\"%ls\": Can't open file "
1108 "(status=0x%08"PRIx32")",
1109 printable_path(full_path), (u32)status);
1110 ret = WIMLIB_ERR_OPEN;
1114 /* Get information about the file. */
1116 IO_STATUS_BLOCK iosb;
1118 status = (*func_NtQueryInformationFile)(h, &iosb,
1121 FileAllInformation);
1123 if (unlikely(!NT_SUCCESS(status) &&
1124 status != STATUS_BUFFER_OVERFLOW))
1126 set_errno_from_nt_status(status);
1127 ERROR_WITH_ERRNO("\"%ls\": Can't get file information "
1128 "(status=0x%08"PRIx32")",
1129 printable_path(full_path), (u32)status);
1130 ret = WIMLIB_ERR_STAT;
1135 if (unlikely(!cur_dir)) {
1137 /* Root of tree being captured; get volume information. */
1139 FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1140 FILE_FS_VOLUME_INFORMATION vol_info;
1141 IO_STATUS_BLOCK iosb;
1143 /* Get volume flags */
1144 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1147 FileFsAttributeInformation);
1148 if (likely((NT_SUCCESS(status) ||
1149 (status == STATUS_BUFFER_OVERFLOW)) &&
1150 (iosb.Information >=
1151 offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1152 FileSystemAttributes) +
1153 sizeof(attr_info.FileSystemAttributes))))
1155 vol_flags = attr_info.FileSystemAttributes;
1157 set_errno_from_nt_status(status);
1158 WARNING_WITH_ERRNO("\"%ls\": Can't get volume attributes "
1159 "(status=0x%08"PRIx32")",
1160 printable_path(full_path),
1165 /* Set inode number of root directory */
1166 params->capture_root_ino =
1167 file_info.InternalInformation.IndexNumber.QuadPart;
1169 /* Get volume ID. */
1170 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1173 FileFsVolumeInformation);
1174 if (likely((NT_SUCCESS(status) ||
1175 (status == STATUS_BUFFER_OVERFLOW)) &&
1176 (iosb.Information >=
1177 offsetof(FILE_FS_VOLUME_INFORMATION,
1178 VolumeSerialNumber) +
1179 sizeof(vol_info.VolumeSerialNumber))))
1181 params->capture_root_dev = vol_info.VolumeSerialNumber;
1183 set_errno_from_nt_status(status);
1184 WARNING_WITH_ERRNO("\"%ls\": Can't get volume ID "
1185 "(status=0x%08"PRIx32")",
1186 printable_path(full_path),
1188 params->capture_root_dev = 0;
1192 /* If this is a reparse point, read the reparse data. */
1193 if (unlikely(file_info.BasicInformation.FileAttributes &
1194 FILE_ATTRIBUTE_REPARSE_POINT))
1196 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1197 ret = winnt_get_reparse_data(h, full_path, params,
1207 ERROR_WITH_ERRNO("\"%ls\": Can't get reparse data",
1208 printable_path(full_path));
1213 /* Create a WIM dentry with an associated inode, which may be shared.
1215 * However, we need to explicitly check for directories and files with
1216 * only 1 link and refuse to hard link them. This is because Windows
1217 * has a bug where it can return duplicate File IDs for files and
1218 * directories on the FAT filesystem. */
1219 ret = inode_table_new_dentry(params->inode_table,
1221 file_info.InternalInformation.IndexNumber.QuadPart,
1222 0, /* We don't follow mount points, so we
1223 currently don't need to get the
1224 volume ID / device number. */
1225 (file_info.StandardInformation.NumberOfLinks <= 1 ||
1226 (file_info.BasicInformation.FileAttributes &
1227 FILE_ATTRIBUTE_DIRECTORY)),
1232 /* Get the short (DOS) name of the file. */
1233 status = winnt_get_short_name(h, root);
1235 /* If we can't read the short filename for any reason other than
1236 * out-of-memory, just ignore the error and assume the file has no short
1237 * name. This shouldn't be an issue, since the short names are
1238 * essentially obsolete anyway. */
1239 if (unlikely(status == STATUS_NO_MEMORY)) {
1240 ret = WIMLIB_ERR_NOMEM;
1244 inode = root->d_inode;
1246 if (inode->i_nlink > 1) {
1247 /* Shared inode (hard link); skip reading per-inode information.
1252 inode->i_attributes = file_info.BasicInformation.FileAttributes;
1253 inode->i_creation_time = file_info.BasicInformation.CreationTime.QuadPart;
1254 inode->i_last_write_time = file_info.BasicInformation.LastWriteTime.QuadPart;
1255 inode->i_last_access_time = file_info.BasicInformation.LastAccessTime.QuadPart;
1256 inode->i_resolved = 1;
1258 /* Get the file's security descriptor, unless we are capturing in
1259 * NO_ACLS mode or the volume does not support security descriptors. */
1260 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1261 && (vol_flags & FILE_PERSISTENT_ACLS))
1263 status = winnt_get_security_descriptor(h, inode,
1264 params->sd_set, stats,
1266 if (!NT_SUCCESS(status)) {
1267 set_errno_from_nt_status(status);
1268 ERROR_WITH_ERRNO("\"%ls\": Can't read security "
1269 "descriptor (status=0x%08"PRIu32")",
1270 printable_path(full_path),
1272 ret = WIMLIB_ERR_STAT;
1277 /* Load information about the unnamed data stream and any named data
1279 ret = winnt_scan_streams(&h,
1283 params->unhashed_streams,
1284 file_info.StandardInformation.EndOfFile.QuadPart,
1289 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1291 /* Reparse point: set the reparse data (already read). */
1293 inode->i_not_rpfixed = not_rpfixed;
1294 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1295 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1296 params->lookup_table);
1299 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1301 /* Directory: recurse to children. */
1303 if (unlikely(h == INVALID_HANDLE_VALUE)) {
1304 /* Re-open handle that was closed to read raw encrypted
1306 status = winnt_openat(cur_dir,
1308 filename : full_path),
1310 filename_nchars : full_path_nchars),
1311 FILE_LIST_DIRECTORY | SYNCHRONIZE,
1313 if (!NT_SUCCESS(status)) {
1314 set_errno_from_nt_status(status);
1315 ERROR_WITH_ERRNO("\"%ls\": Can't re-open file "
1316 "(status=0x%08"PRIx32")",
1317 printable_path(full_path),
1319 ret = WIMLIB_ERR_OPEN;
1323 ret = winnt_recurse_directory(h,
1335 params->progress.scan.cur_path = printable_path(full_path);
1337 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1339 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1341 if (likely(h != INVALID_HANDLE_VALUE))
1343 if (likely(ret == 0))
1346 free_dentry_tree(root, params->lookup_table);
1351 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_stats *stats)
1353 if (likely(stats->num_get_sacl_priv_notheld == 0 &&
1354 stats->num_get_sd_access_denied == 0))
1357 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1358 if (stats->num_get_sacl_priv_notheld != 0) {
1359 WARNING("- Could not capture SACL (System Access Control List)\n"
1360 " on %lu files or directories.",
1361 stats->num_get_sacl_priv_notheld);
1363 if (stats->num_get_sd_access_denied != 0) {
1364 WARNING("- Could not capture security descriptor at all\n"
1365 " on %lu files or directories.",
1366 stats->num_get_sd_access_denied);
1368 WARNING("To fully capture all security descriptors, run the program\n"
1369 " with Administrator rights.");
1372 #define WINDOWS_NT_MAX_PATH 32768
1374 /* Win32 version of capturing a directory tree. */
1376 win32_build_dentry_tree(struct wim_dentry **root_ret,
1377 const wchar_t *root_disk_path,
1378 struct add_image_params *params)
1384 struct winnt_scan_stats stats;
1386 /* WARNING: There is no check for overflow later when this buffer is
1387 * being used! But it's as long as the maximum path length understood
1388 * by Windows NT (which is NOT the same as MAX_PATH). */
1389 path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1391 return WIMLIB_ERR_NOMEM;
1393 /* Translate into full path. */
1394 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 3,
1397 if (unlikely(dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 3)) {
1398 ERROR("Can't get full path name for \"%ls\"", root_disk_path);
1399 return WIMLIB_ERR_UNSUPPORTED;
1402 /* Add \??\ prefix to form the NT namespace path. */
1403 wmemcpy(path, L"\\??\\", 4);
1404 path_nchars = dret + 4;
1406 /* Strip trailing slashes. If we don't do this, we may create a path
1407 * with multiple consecutive backslashes, which for some reason causes
1408 * Windows to report that the file cannot be found. */
1409 while (unlikely(path[path_nchars - 1] == L'\\' &&
1410 path[path_nchars - 2] != L':'))
1411 path[--path_nchars] = L'\0';
1413 params->capture_root_nchars = path_nchars;
1415 memset(&stats, 0, sizeof(stats));
1417 ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
1418 path, path_nchars, L"", 0,
1422 winnt_do_scan_warnings(root_disk_path, &stats);
1426 #endif /* __WIN32__ */