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;
48 unsigned long num_long_path_warnings;
51 static inline const wchar_t *
52 printable_path(const wchar_t *full_path)
54 /* Skip over \\?\ or \??\ */
59 * If cur_dir is not NULL, open an existing file relative to the already-open
62 * Otherwise, open the file specified by @path, which must be a Windows NT
66 winnt_openat(HANDLE cur_dir, const wchar_t *path, size_t path_nchars,
67 ACCESS_MASK perms, HANDLE *h_ret)
70 OBJECT_ATTRIBUTES attr;
74 name.Length = path_nchars * sizeof(wchar_t);
75 name.MaximumLength = name.Length + sizeof(wchar_t);
76 name.Buffer = (wchar_t *)path;
78 attr.Length = sizeof(attr);
79 attr.RootDirectory = cur_dir;
80 attr.ObjectName = &name;
82 attr.SecurityDescriptor = NULL;
83 attr.SecurityQualityOfService = NULL;
86 status = (*func_NtOpenFile)(h_ret, perms, &attr, &iosb,
90 FILE_OPEN_REPARSE_POINT |
91 FILE_OPEN_FOR_BACKUP_INTENT |
92 FILE_SYNCHRONOUS_IO_NONALERT |
93 FILE_SEQUENTIAL_ONLY);
94 if (!NT_SUCCESS(status)) {
95 /* Try requesting fewer permissions */
96 if (status == STATUS_ACCESS_DENIED ||
97 status == STATUS_PRIVILEGE_NOT_HELD) {
98 if (perms & ACCESS_SYSTEM_SECURITY) {
99 perms &= ~ACCESS_SYSTEM_SECURITY;
102 if (perms & READ_CONTROL) {
103 perms &= ~READ_CONTROL;
111 /* Read the first @size bytes from the file, or named data stream of a file,
112 * from which the stream entry @lte was created. */
114 read_winnt_file_prefix(const struct wim_lookup_table_entry *lte, u64 size,
115 consume_data_callback_t cb, void *cb_ctx)
124 /* This is an NT namespace path. */
125 path = lte->file_on_disk;
127 status = winnt_openat(NULL, path, wcslen(path),
128 FILE_READ_DATA | SYNCHRONIZE, &h);
129 if (!NT_SUCCESS(status)) {
130 set_errno_from_nt_status(status);
131 ERROR_WITH_ERRNO("\"%ls\": Can't open for reading "
132 "(status=0x%08"PRIx32")",
133 printable_path(path), (u32)status);
134 return WIMLIB_ERR_OPEN;
138 bytes_remaining = size;
139 while (bytes_remaining) {
140 IO_STATUS_BLOCK iosb;
144 count = min(sizeof(buf), bytes_remaining);
146 status = (*func_NtReadFile)(h, NULL, NULL, NULL,
147 &iosb, buf, count, NULL, NULL);
148 if (!NT_SUCCESS(status)) {
149 set_errno_from_nt_status(status);
150 ERROR_WITH_ERRNO("\"%ls\": Error reading data "
151 "(status=0x%08"PRIx32")",
152 printable_path(path), (u32)status);
153 ret = WIMLIB_ERR_READ;
157 bytes_read = iosb.Information;
159 bytes_remaining -= bytes_read;
160 ret = (*cb)(buf, bytes_read, cb_ctx);
168 struct win32_encrypted_read_ctx {
169 consume_data_callback_t read_prefix_cb;
170 void *read_prefix_ctx;
176 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
178 struct win32_encrypted_read_ctx *ctx = _ctx;
180 size_t bytes_to_consume = min(len, ctx->bytes_remaining);
182 if (bytes_to_consume == 0)
183 return ERROR_SUCCESS;
185 ret = (*ctx->read_prefix_cb)(data, bytes_to_consume, ctx->read_prefix_ctx);
187 ctx->wimlib_err_code = ret;
188 /* Shouldn't matter what error code is returned here, as long as
189 * it isn't ERROR_SUCCESS. */
190 return ERROR_READ_FAULT;
192 ctx->bytes_remaining -= bytes_to_consume;
193 return ERROR_SUCCESS;
197 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
199 consume_data_callback_t cb, void *cb_ctx)
201 struct win32_encrypted_read_ctx export_ctx;
206 export_ctx.read_prefix_cb = cb;
207 export_ctx.read_prefix_ctx = cb_ctx;
208 export_ctx.wimlib_err_code = 0;
209 export_ctx.bytes_remaining = size;
211 err = OpenEncryptedFileRaw(lte->file_on_disk, 0, &file_ctx);
212 if (err != ERROR_SUCCESS) {
213 set_errno_from_win32_error(err);
214 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
216 printable_path(lte->file_on_disk));
217 return WIMLIB_ERR_OPEN;
219 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
220 &export_ctx, file_ctx);
221 if (err != ERROR_SUCCESS) {
222 set_errno_from_win32_error(err);
223 ERROR_WITH_ERRNO("Failed to read encrypted file \"%ls\"",
224 printable_path(lte->file_on_disk));
225 ret = export_ctx.wimlib_err_code;
227 ret = WIMLIB_ERR_READ;
228 } else if (export_ctx.bytes_remaining != 0) {
229 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
230 "encryted file \"%ls\"",
231 size - export_ctx.bytes_remaining, size,
232 printable_path(lte->file_on_disk));
233 ret = WIMLIB_ERR_READ;
237 CloseEncryptedFileRaw(file_ctx);
242 * Load the short name of a file into a WIM dentry.
245 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
247 /* It's not any harder to just make the NtQueryInformationFile() system
248 * call ourselves, and it saves a dumb call to FindFirstFile() which of
249 * course has to create its own handle. */
251 IO_STATUS_BLOCK iosb;
252 u8 buf[128] _aligned_attribute(8);
253 const FILE_NAME_INFORMATION *info;
255 status = (*func_NtQueryInformationFile)(h, &iosb, buf, sizeof(buf),
256 FileAlternateNameInformation);
257 info = (const FILE_NAME_INFORMATION *)buf;
258 if (NT_SUCCESS(status) && info->FileNameLength != 0) {
259 dentry->short_name = utf16le_dupz(info->FileName,
260 info->FileNameLength);
261 if (!dentry->short_name)
262 return STATUS_NO_MEMORY;
263 dentry->short_name_nbytes = info->FileNameLength;
269 * Load the security descriptor of a file into the corresponding inode, and the
270 * WIM image's security descriptor set.
273 winnt_get_security_descriptor(HANDLE h, struct wim_inode *inode,
274 struct wim_sd_set *sd_set,
275 struct winnt_scan_stats *stats, int add_flags)
277 SECURITY_INFORMATION requestedInformation;
278 u8 _buf[4096] _aligned_attribute(8);
284 requestedInformation = DACL_SECURITY_INFORMATION |
285 SACL_SECURITY_INFORMATION |
286 OWNER_SECURITY_INFORMATION |
287 GROUP_SECURITY_INFORMATION;
289 bufsize = sizeof(_buf);
292 * We need the file's security descriptor in
293 * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
294 * opened with as many relevant permissions as possible. At this point,
295 * on Windows there are a number of options for reading a file's
296 * security descriptor:
298 * GetFileSecurity(): This takes in a path and returns the
299 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle,
300 * not ours, and the handle created internally doesn't specify
301 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied
302 * errors on some files and directories, even when running as the
305 * GetSecurityInfo(): This takes in a handle and returns the security
306 * descriptor split into a bunch of different parts. This should work,
307 * but it's dumb because we have to put the security descriptor back
310 * BackupRead(): This can read the security descriptor, but this is a
311 * difficult-to-use API, probably only works as the Administrator, and
312 * the format of the returned data is not well documented.
314 * NtQuerySecurityObject(): This is exactly what we need, as it takes
315 * in a handle and returns the security descriptor in
316 * SECURITY_DESCRIPTOR_RELATIVE format. Only problem is that it's a
317 * ntdll function and therefore not officially part of the Win32 API.
320 while (!(NT_SUCCESS(status = (*func_NtQuerySecurityObject)(h,
321 requestedInformation,
322 (PSECURITY_DESCRIPTOR)buf,
327 case STATUS_BUFFER_TOO_SMALL:
328 wimlib_assert(buf == _buf);
329 buf = MALLOC(len_needed);
331 return STATUS_NO_MEMORY;
332 bufsize = len_needed;
334 case STATUS_PRIVILEGE_NOT_HELD:
335 case STATUS_ACCESS_DENIED:
336 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
338 /* Permission denied in STRICT_ACLS mode, or
342 if (requestedInformation & SACL_SECURITY_INFORMATION) {
343 /* Try again without the SACL. */
344 stats->num_get_sacl_priv_notheld++;
345 requestedInformation &= ~SACL_SECURITY_INFORMATION;
348 /* Fake success (useful when capturing as
349 * non-Administrator). */
350 stats->num_get_sd_access_denied++;
351 status = STATUS_SUCCESS;
356 /* Add the security descriptor to the WIM image, and save its ID in
358 inode->i_security_id = sd_set_add_sd(sd_set, buf, len_needed);
359 if (unlikely(inode->i_security_id < 0))
360 status = STATUS_NO_MEMORY;
362 if (unlikely(buf != _buf))
368 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
371 size_t full_path_nchars,
372 const wchar_t *filename,
373 size_t filename_nchars,
374 struct add_image_params *params,
375 struct winnt_scan_stats *stats,
379 winnt_recurse_directory(HANDLE h,
381 size_t full_path_nchars,
382 struct wim_dentry *parent,
383 struct add_image_params *params,
384 struct winnt_scan_stats *stats,
388 const size_t bufsize = 8192;
389 IO_STATUS_BLOCK iosb;
393 buf = MALLOC(bufsize);
395 return WIMLIB_ERR_NOMEM;
397 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
398 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
400 while (NT_SUCCESS(status = (*func_NtQueryDirectoryFile)(h, NULL, NULL, NULL,
402 FileNamesInformation,
403 FALSE, NULL, FALSE)))
405 const FILE_NAMES_INFORMATION *info = buf;
407 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
408 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
409 info->FileName[1] == L'.'))
412 struct wim_dentry *child;
414 p = full_path + full_path_nchars;
416 p = wmempcpy(p, info->FileName,
417 info->FileNameLength / 2);
420 ret = winnt_build_dentry_tree_recursive(
425 full_path + full_path_nchars + 1,
426 info->FileNameLength / 2,
431 full_path[full_path_nchars] = L'\0';
436 dentry_add_child(parent, child);
438 if (info->NextEntryOffset == 0)
440 info = (const FILE_NAMES_INFORMATION *)
441 ((const u8 *)info + info->NextEntryOffset);
445 if (unlikely(status != STATUS_NO_MORE_FILES)) {
446 set_errno_from_nt_status(status);
447 ERROR_WITH_ERRNO("\"%ls\": Can't read directory "
448 "(status=0x%08"PRIx32")",
449 printable_path(full_path), (u32)status);
450 ret = WIMLIB_ERR_READ;
457 /* Reparse point fixup status code */
459 /* Reparse point should be excluded from capture */
462 /* Reparse point will be captured literally (no fixup) */
465 /* Reparse point will be captured with fixup */
470 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
473 IO_STATUS_BLOCK iosb;
474 FILE_INTERNAL_INFORMATION int_info;
475 FILE_FS_VOLUME_INFORMATION vol_info;
477 status = (*func_NtQueryInformationFile)(h, &iosb,
478 &int_info, sizeof(int_info),
479 FileInternalInformation);
480 if (!NT_SUCCESS(status))
483 if (int_info.IndexNumber.QuadPart != ino)
486 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
487 &vol_info, sizeof(vol_info),
488 FileFsVolumeInformation);
489 if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
492 if (iosb.Information <
493 offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
494 sizeof(vol_info.VolumeSerialNumber))
497 return (vol_info.VolumeSerialNumber == dev);
501 * Given an (expected) NT namespace symbolic link or junction target @target of
502 * length @target_nbytes, determine if a prefix of the target points to a file
503 * identified by @capture_root_ino and @capture_root_dev.
505 * If yes, return a pointer to the portion of the link following this prefix.
507 * If no, return NULL.
509 * If the link target does not appear to be a valid NT namespace path, return
512 static const wchar_t *
513 winnt_get_root_relative_target(const wchar_t *target, size_t target_nbytes,
514 u64 capture_root_ino, u64 capture_root_dev)
517 OBJECT_ATTRIBUTES attr;
518 IO_STATUS_BLOCK iosb;
520 const wchar_t *target_end;
523 target_end = target + (target_nbytes / sizeof(wchar_t));
526 if (target_end == target)
529 /* No leading slash??? */
530 if (target[0] != L'\\')
534 if ((target_end - target) >= 2 &&
535 target[0] == L'\\' && target[1] == L'\\')
538 attr.Length = sizeof(attr);
539 attr.RootDirectory = NULL;
540 attr.ObjectName = &name;
542 attr.SecurityDescriptor = NULL;
543 attr.SecurityQualityOfService = NULL;
545 name.Buffer = (wchar_t *)target;
550 const wchar_t *orig_p = p;
552 /* Skip non-backslashes */
553 while (p != target_end && *p != L'\\')
556 /* Skip backslashes */
557 while (p != target_end && *p == L'\\')
560 /* Append path component */
561 name.Length += (p - orig_p) * sizeof(wchar_t);
562 name.MaximumLength = name.Length;
564 /* Try opening the file */
565 status = (*func_NtOpenFile) (&h,
566 FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
569 FILE_SHARE_VALID_FLAGS,
570 FILE_OPEN_FOR_BACKUP_INTENT);
572 if (NT_SUCCESS(status)) {
573 /* Reset root directory */
574 if (attr.RootDirectory)
575 (*func_NtClose)(attr.RootDirectory);
576 attr.RootDirectory = h;
577 name.Buffer = (wchar_t *)p;
580 if (file_has_ino_and_dev(h, capture_root_ino,
582 goto out_close_root_dir;
584 } while (p != target_end);
589 if (attr.RootDirectory)
590 (*func_NtClose)(attr.RootDirectory);
594 static enum rp_status
595 winnt_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
596 u64 capture_root_ino, u64 capture_root_dev,
597 const wchar_t *path, struct add_image_params *params)
599 struct reparse_data rpdata;
600 const wchar_t *rel_target;
602 if (parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata)) {
603 /* Couldn't even understand the reparse data. Don't try the
609 * Don't do reparse point fixups on relative symbolic links.
611 * On Windows, a relative symbolic link is supposed to be identifiable
612 * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
613 * SYMBOLIC_LINK_RELATIVE. We will use this information, although this
614 * may not always do what the user expects, since drive-relative
615 * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
616 * set, in addition to truely relative symbolic links such as "Users" or
617 * "Users\Public". However, WIMGAPI (as of Windows 8.1) has this same
620 * Otherwise, as far as I can tell, the targets of symbolic links that
621 * are NOT relative, as well as junctions (note: a mountpoint is the
622 * sames thing as a junction), must be NT namespace paths, for example:
624 * - \??\e:\Users\Public
625 * - \DosDevices\e:\Users\Public
626 * - \Device\HardDiskVolume4\Users\Public
627 * - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
628 * - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
630 if (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
631 (rpdata.rpflags & SYMBOLIC_LINK_RELATIVE))
634 rel_target = winnt_get_root_relative_target(rpdata.substitute_name,
635 rpdata.substitute_name_nbytes,
639 /* Target points outside of the tree being captured. Exclude
640 * this reparse point from the capture (but inform the library
642 size_t print_name_nchars = rpdata.print_name_nbytes / sizeof(wchar_t);
643 wchar_t print_name0[print_name_nchars + 1];
644 print_name0[print_name_nchars] = L'\0';
645 wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
647 params->progress.scan.cur_path = printable_path(path);
648 params->progress.scan.symlink_target = print_name0;
649 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED_SYMLINK, NULL);
653 if (rel_target == rpdata.substitute_name) {
654 /* Weird target --- keep the reparse point and don't mess with
659 /* We have an absolute target pointing within the directory being
660 * captured, @rel_target is the suffix of the link target that is the
661 * part relative to the directory being captured.
663 * We will cut off the prefix before this part (which is the path to the
664 * directory being captured) and add a dummy prefix. Since the process
665 * will need to be reversed when applying the image, it shouldn't matter
666 * what exactly the prefix is, as long as it looks like an absolute
671 size_t rel_target_nbytes =
672 rpdata.substitute_name_nbytes - ((const u8 *)rel_target -
673 (const u8 *)rpdata.substitute_name);
674 size_t rel_target_nchars = rel_target_nbytes / sizeof(wchar_t);
676 wchar_t tmp[rel_target_nchars + 7];
678 wmemcpy(tmp, L"\\??\\X:\\", 7);
679 wmemcpy(tmp + 7, rel_target, rel_target_nchars);
681 rpdata.substitute_name = tmp;
682 rpdata.substitute_name_nbytes = rel_target_nbytes + (7 * sizeof(wchar_t));
683 rpdata.print_name = tmp + 4;
684 rpdata.print_name_nbytes = rel_target_nbytes + (3 * sizeof(wchar_t));
686 if (make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p))
693 * Loads the reparse point data from a reparse point into memory, optionally
694 * fixing the targets of absolute symbolic links and junction points to be
695 * relative to the root of capture.
698 * Open handle to the reparse point file.
700 * Path to the reparse point file.
702 * Capture parameters. add_flags, capture_root_ino, capture_root_dev,
703 * progress_func, and progress are used.
705 * Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which the
706 * reparse point buffer will be loaded.
708 * On success, the length of the reparse point buffer in bytes is written
711 * On success, returns a nonpositive `enum rp_status' value.
712 * On failure, returns a positive error code.
715 winnt_get_reparse_data(HANDLE h, const wchar_t *path,
716 struct add_image_params *params,
717 u8 *rpbuf, u16 *rpbuflen_ret)
719 DWORD bytes_returned;
724 if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
725 NULL, 0, rpbuf, REPARSE_POINT_MAX_SIZE,
726 &bytes_returned, NULL))
728 set_errno_from_GetLastError();
729 return WIMLIB_ERR_READ;
732 if (unlikely(bytes_returned < 8)) {
734 return WIMLIB_ERR_INVALID_REPARSE_DATA;
737 rpbuflen = bytes_returned;
738 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
740 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
741 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
742 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
744 ret = winnt_try_rpfix(rpbuf, &rpbuflen,
745 params->capture_root_ino,
746 params->capture_root_dev,
749 *rpbuflen_ret = rpbuflen;
754 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
757 *(u64*)_size_ret += len;
758 return ERROR_SUCCESS;
762 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
768 err = OpenEncryptedFileRaw(path, 0, &file_ctx);
769 if (err != ERROR_SUCCESS) {
770 set_errno_from_win32_error(err);
771 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
772 "for raw read", printable_path(path));
773 return WIMLIB_ERR_OPEN;
776 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
778 if (err != ERROR_SUCCESS) {
779 set_errno_from_win32_error(err);
780 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
781 "\"%ls\"", printable_path(path));
782 ret = WIMLIB_ERR_READ;
786 CloseEncryptedFileRaw(file_ctx);
791 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
792 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
794 const wchar_t *sep, *type, *end;
796 /* The stream name should be returned as :NAME:TYPE */
797 if (raw_stream_name_nchars < 1)
799 if (raw_stream_name[0] != L':')
803 raw_stream_name_nchars--;
805 end = raw_stream_name + raw_stream_name_nchars;
807 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
815 if (wmemcmp(type, L"$DATA", 5))
818 *stream_name_ret = raw_stream_name;
819 *stream_name_nchars_ret = sep - raw_stream_name;
824 build_stream_path(const wchar_t *path, size_t path_nchars,
825 const wchar_t *stream_name, size_t stream_name_nchars)
827 size_t stream_path_nchars;
828 wchar_t *stream_path;
831 stream_path_nchars = path_nchars;
832 if (stream_name_nchars)
833 stream_path_nchars += 1 + stream_name_nchars;
835 stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
837 p = wmempcpy(stream_path, path, path_nchars);
838 if (stream_name_nchars) {
840 p = wmempcpy(p, stream_name, stream_name_nchars);
848 winnt_scan_stream(const wchar_t *path, size_t path_nchars,
849 const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
851 struct wim_inode *inode, struct list_head *unhashed_streams)
853 const wchar_t *stream_name;
854 size_t stream_name_nchars;
855 struct wim_ads_entry *ads_entry;
856 wchar_t *stream_path;
857 struct wim_lookup_table_entry *lte;
860 /* Given the raw stream name (which is something like
861 * :streamname:$DATA), extract just the stream name part.
862 * Ignore any non-$DATA streams. */
863 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
864 &stream_name, &stream_name_nchars))
867 /* If this is a named stream, allocate an ADS entry for it. */
868 if (stream_name_nchars) {
869 ads_entry = inode_add_ads_utf16le(inode, stream_name,
873 return WIMLIB_ERR_NOMEM;
878 /* If the stream is empty, no lookup table entry is needed. */
879 if (stream_size == 0)
882 /* Build the path to the stream. For unnamed streams, this is simply
883 * the path to the file. For named streams, this is the path to the
884 * file, followed by a colon, followed by the stream name. */
885 stream_path = build_stream_path(path, path_nchars,
886 stream_name, stream_name_nchars);
888 return WIMLIB_ERR_NOMEM;
890 /* Set up the lookup table entry for the stream. */
891 lte = new_lookup_table_entry();
894 return WIMLIB_ERR_NOMEM;
896 lte->file_on_disk = stream_path;
897 lte->resource_location = RESOURCE_IN_WINNT_FILE_ON_DISK;
898 lte->size = stream_size;
899 if ((inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) && !ads_entry) {
900 /* Special case for encrypted file. */
902 /* OpenEncryptedFileRaw() expects Win32 name, not NT name.
903 * Change \??\ into \\?\ */
904 lte->file_on_disk[1] = L'\\';
905 wimlib_assert(!wmemcmp(lte->file_on_disk, L"\\\\?\\", 4));
910 ret = win32_get_encrypted_file_size(lte->file_on_disk,
913 free_lookup_table_entry(lte);
916 lte->size = encrypted_size;
917 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
921 stream_id = ads_entry->stream_id;
922 ads_entry->lte = lte;
927 add_unhashed_stream(lte, inode, stream_id, unhashed_streams);
932 * Load information about the streams of an open file into a WIM inode.
934 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
935 * and FindNextStream(). This is done for two reasons:
937 * - FindFirstStream() opens its own handle to the file or directory and
938 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
939 * causing access denied errors on certain files (even when running as the
941 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
942 * and later, whereas the stream support in NtQueryInformationFile() was
943 * already present in Windows XP.
946 winnt_scan_streams(HANDLE *hFile_p, const wchar_t *path, size_t path_nchars,
947 struct wim_inode *inode, struct list_head *unhashed_streams,
948 u64 file_size, u32 vol_flags)
951 u8 _buf[1024] _aligned_attribute(8);
954 IO_STATUS_BLOCK iosb;
956 const FILE_STREAM_INFORMATION *info;
959 bufsize = sizeof(_buf);
961 if (!(vol_flags & FILE_NAMED_STREAMS))
964 /* Get a buffer containing the stream information. */
965 while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(*hFile_p,
969 FileStreamInformation)))
973 case STATUS_BUFFER_OVERFLOW:
979 newbuf = MALLOC(bufsize);
981 newbuf = REALLOC(buf, bufsize);
983 ret = WIMLIB_ERR_NOMEM;
989 case STATUS_NOT_IMPLEMENTED:
990 case STATUS_NOT_SUPPORTED:
991 case STATUS_INVALID_INFO_CLASS:
994 set_errno_from_nt_status(status);
995 ERROR_WITH_ERRNO("\"%ls\": Failed to query stream "
996 "information (status=0x%08"PRIx32")",
997 printable_path(path), (u32)status);
998 ret = WIMLIB_ERR_READ;
1003 if (iosb.Information == 0) {
1004 /* No stream information. */
1009 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1010 /* OpenEncryptedFileRaw() seems to fail with
1011 * ERROR_SHARING_VIOLATION if there are any handles opened to
1013 (*func_NtClose)(*hFile_p);
1014 *hFile_p = INVALID_HANDLE_VALUE;
1017 /* Parse one or more stream information structures. */
1018 info = (const FILE_STREAM_INFORMATION *)buf;
1020 /* Load the stream information. */
1021 ret = winnt_scan_stream(path, path_nchars,
1023 info->StreamNameLength / 2,
1024 info->StreamSize.QuadPart,
1025 inode, unhashed_streams);
1029 if (info->NextEntryOffset == 0) {
1030 /* No more stream information. */
1033 /* Advance to next stream information. */
1034 info = (const FILE_STREAM_INFORMATION *)
1035 ((const u8 *)info + info->NextEntryOffset);
1041 /* The volume does not support named streams. Only capture the unnamed
1043 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1044 FILE_ATTRIBUTE_REPARSE_POINT))
1050 ret = winnt_scan_stream(path, path_nchars, L"::$DATA", 7,
1051 file_size, inode, unhashed_streams);
1053 /* Free buffer if allocated on heap. */
1054 if (unlikely(buf != _buf))
1060 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1063 size_t full_path_nchars,
1064 const wchar_t *filename,
1065 size_t filename_nchars,
1066 struct add_image_params *params,
1067 struct winnt_scan_stats *stats,
1070 struct wim_dentry *root = NULL;
1071 struct wim_inode *inode = NULL;
1072 HANDLE h = INVALID_HANDLE_VALUE;
1075 FILE_ALL_INFORMATION file_info;
1080 if (should_exclude_path(full_path + params->capture_root_nchars,
1081 full_path_nchars - params->capture_root_nchars,
1088 /* Open the file. */
1089 status = winnt_openat(cur_dir,
1090 (cur_dir ? filename : full_path),
1091 (cur_dir ? filename_nchars : full_path_nchars),
1093 FILE_READ_ATTRIBUTES |
1095 ACCESS_SYSTEM_SECURITY |
1098 if (unlikely(!NT_SUCCESS(status))) {
1099 set_errno_from_nt_status(status);
1100 ERROR_WITH_ERRNO("\"%ls\": Can't open file "
1101 "(status=0x%08"PRIx32")",
1102 printable_path(full_path), (u32)status);
1103 ret = WIMLIB_ERR_OPEN;
1107 /* Get information about the file. */
1109 IO_STATUS_BLOCK iosb;
1111 status = (*func_NtQueryInformationFile)(h, &iosb,
1114 FileAllInformation);
1116 if (unlikely(!NT_SUCCESS(status) &&
1117 status != STATUS_BUFFER_OVERFLOW))
1119 set_errno_from_nt_status(status);
1120 ERROR_WITH_ERRNO("\"%ls\": Can't get file information "
1121 "(status=0x%08"PRIx32")",
1122 printable_path(full_path), (u32)status);
1123 ret = WIMLIB_ERR_STAT;
1128 if (unlikely(!cur_dir)) {
1130 /* Root of tree being captured; get volume information. */
1132 FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1133 FILE_FS_VOLUME_INFORMATION vol_info;
1134 IO_STATUS_BLOCK iosb;
1136 /* Get volume flags */
1137 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1140 FileFsAttributeInformation);
1141 if (likely((NT_SUCCESS(status) ||
1142 (status == STATUS_BUFFER_OVERFLOW)) &&
1143 (iosb.Information >=
1144 offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1145 FileSystemAttributes) +
1146 sizeof(attr_info.FileSystemAttributes))))
1148 vol_flags = attr_info.FileSystemAttributes;
1150 set_errno_from_nt_status(status);
1151 WARNING_WITH_ERRNO("\"%ls\": Can't get volume attributes "
1152 "(status=0x%08"PRIx32")",
1153 printable_path(full_path),
1158 /* Set inode number of root directory */
1159 params->capture_root_ino =
1160 file_info.InternalInformation.IndexNumber.QuadPart;
1162 /* Get volume ID. */
1163 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1166 FileFsVolumeInformation);
1167 if (likely((NT_SUCCESS(status) ||
1168 (status == STATUS_BUFFER_OVERFLOW)) &&
1169 (iosb.Information >=
1170 offsetof(FILE_FS_VOLUME_INFORMATION,
1171 VolumeSerialNumber) +
1172 sizeof(vol_info.VolumeSerialNumber))))
1174 params->capture_root_dev = vol_info.VolumeSerialNumber;
1176 set_errno_from_nt_status(status);
1177 WARNING_WITH_ERRNO("\"%ls\": Can't get volume ID "
1178 "(status=0x%08"PRIx32")",
1179 printable_path(full_path),
1181 params->capture_root_dev = 0;
1185 /* If this is a reparse point, read the reparse data. */
1186 if (unlikely(file_info.BasicInformation.FileAttributes &
1187 FILE_ATTRIBUTE_REPARSE_POINT))
1189 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1190 ret = winnt_get_reparse_data(h, full_path, params,
1203 ERROR_WITH_ERRNO("\"%ls\": Can't get reparse data",
1204 printable_path(full_path));
1209 /* Create a WIM dentry with an associated inode, which may be shared.
1211 * However, we need to explicitly check for directories and files with
1212 * only 1 link and refuse to hard link them. This is because Windows
1213 * has a bug where it can return duplicate File IDs for files and
1214 * directories on the FAT filesystem. */
1215 ret = inode_table_new_dentry(params->inode_table,
1217 file_info.InternalInformation.IndexNumber.QuadPart,
1218 0, /* We don't follow mount points, so we
1219 currently don't need to get the
1220 volume ID / device number. */
1221 (file_info.StandardInformation.NumberOfLinks <= 1 ||
1222 (file_info.BasicInformation.FileAttributes &
1223 FILE_ATTRIBUTE_DIRECTORY)),
1228 /* Get the short (DOS) name of the file. */
1229 status = winnt_get_short_name(h, root);
1231 /* If we can't read the short filename for any reason other than
1232 * out-of-memory, just ignore the error and assume the file has no short
1233 * name. This shouldn't be an issue, since the short names are
1234 * essentially obsolete anyway. */
1235 if (unlikely(status == STATUS_NO_MEMORY)) {
1236 ret = WIMLIB_ERR_NOMEM;
1240 inode = root->d_inode;
1242 if (inode->i_nlink > 1) {
1243 /* Shared inode (hard link); skip reading per-inode information.
1249 inode->i_attributes = file_info.BasicInformation.FileAttributes;
1250 inode->i_creation_time = file_info.BasicInformation.CreationTime.QuadPart;
1251 inode->i_last_write_time = file_info.BasicInformation.LastWriteTime.QuadPart;
1252 inode->i_last_access_time = file_info.BasicInformation.LastAccessTime.QuadPart;
1253 inode->i_resolved = 1;
1255 /* Get the file's security descriptor, unless we are capturing in
1256 * NO_ACLS mode or the volume does not support security descriptors. */
1257 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1258 && (vol_flags & FILE_PERSISTENT_ACLS))
1260 status = winnt_get_security_descriptor(h, inode,
1261 params->sd_set, stats,
1263 if (!NT_SUCCESS(status)) {
1264 set_errno_from_nt_status(status);
1265 ERROR_WITH_ERRNO("\"%ls\": Can't read security "
1266 "descriptor (status=0x%08"PRIu32")",
1267 printable_path(full_path),
1269 ret = WIMLIB_ERR_STAT;
1274 /* Load information about the unnamed data stream and any named data
1276 ret = winnt_scan_streams(&h,
1280 params->unhashed_streams,
1281 file_info.StandardInformation.EndOfFile.QuadPart,
1286 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1288 /* Reparse point: set the reparse data (already read). */
1290 inode->i_not_rpfixed = not_rpfixed;
1291 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1292 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1293 params->lookup_table);
1296 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1298 /* Directory: recurse to children. */
1300 if (unlikely(h == INVALID_HANDLE_VALUE)) {
1301 /* Re-open handle that was closed to read raw encrypted
1303 status = winnt_openat(cur_dir,
1305 filename : full_path),
1307 filename_nchars : full_path_nchars),
1308 FILE_LIST_DIRECTORY | SYNCHRONIZE,
1310 if (!NT_SUCCESS(status)) {
1311 set_errno_from_nt_status(status);
1312 ERROR_WITH_ERRNO("\"%ls\": Can't re-open file "
1313 "(status=0x%08"PRIx32")",
1314 printable_path(full_path),
1316 ret = WIMLIB_ERR_OPEN;
1320 ret = winnt_recurse_directory(h,
1332 params->progress.scan.cur_path = printable_path(full_path);
1334 do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1336 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1338 if (likely(h != INVALID_HANDLE_VALUE))
1340 if (likely(ret == 0))
1343 free_dentry_tree(root, params->lookup_table);
1348 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_stats *stats)
1350 if (likely(stats->num_get_sacl_priv_notheld == 0 &&
1351 stats->num_get_sd_access_denied == 0))
1354 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1355 if (stats->num_get_sacl_priv_notheld != 0) {
1356 WARNING("- Could not capture SACL (System Access Control List)\n"
1357 " on %lu files or directories.",
1358 stats->num_get_sacl_priv_notheld);
1360 if (stats->num_get_sd_access_denied != 0) {
1361 WARNING("- Could not capture security descriptor at all\n"
1362 " on %lu files or directories.",
1363 stats->num_get_sd_access_denied);
1365 WARNING("To fully capture all security descriptors, run the program\n"
1366 " with Administrator rights.");
1369 #define WINDOWS_NT_MAX_PATH 32768
1371 /* Win32 version of capturing a directory tree. */
1373 win32_build_dentry_tree(struct wim_dentry **root_ret,
1374 const wchar_t *root_disk_path,
1375 struct add_image_params *params)
1381 struct winnt_scan_stats stats;
1383 /* WARNING: There is no check for overflow later when this buffer is
1384 * being used! But it's as long as the maximum path length understood
1385 * by Windows NT (which is NOT the same as MAX_PATH). */
1386 path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1388 return WIMLIB_ERR_NOMEM;
1390 /* Translate into full path. */
1391 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 3,
1394 if (unlikely(dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 3)) {
1395 ERROR("Can't get full path name for \"%ls\"", root_disk_path);
1396 return WIMLIB_ERR_UNSUPPORTED;
1399 /* Add \??\ prefix to form the NT namespace path. */
1400 wmemcpy(path, L"\\??\\", 4);
1401 path_nchars = dret + 4;
1403 /* Strip trailing slashes. If we don't do this, we may create a path
1404 * with multiple consecutive backslashes, which for some reason causes
1405 * Windows to report that the file cannot be found. */
1406 while (unlikely(path[path_nchars - 1] == L'\\' &&
1407 path[path_nchars - 2] != L':'))
1408 path[--path_nchars] = L'\0';
1410 params->capture_root_nchars = path_nchars;
1412 memset(&stats, 0, sizeof(stats));
1414 ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
1415 path, path_nchars, L"", 0,
1419 winnt_do_scan_warnings(root_disk_path, &stats);
1423 #endif /* __WIN32__ */