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/capture.h"
34 #include "wimlib/dentry.h"
35 #include "wimlib/encoding.h"
36 #include "wimlib/endianness.h"
37 #include "wimlib/error.h"
38 #include "wimlib/lookup_table.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 * from which the stream entry @lte was created. */
108 read_winnt_file_prefix(const struct wim_lookup_table_entry *lte, u64 size,
109 consume_data_callback_t cb, void *cb_ctx)
118 /* This is an NT namespace path. */
119 path = lte->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 wim_lookup_table_entry *lte,
189 consume_data_callback_t cb, void *cb_ctx)
191 struct win32_encrypted_read_ctx export_ctx;
196 export_ctx.read_prefix_cb = cb;
197 export_ctx.read_prefix_ctx = cb_ctx;
198 export_ctx.wimlib_err_code = 0;
199 export_ctx.bytes_remaining = size;
201 err = OpenEncryptedFileRaw(lte->file_on_disk, 0, &file_ctx);
202 if (err != ERROR_SUCCESS) {
204 L"Failed to open encrypted file \"%ls\" for raw read",
205 printable_path(lte->file_on_disk));
206 return WIMLIB_ERR_OPEN;
208 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
209 &export_ctx, file_ctx);
210 if (err != ERROR_SUCCESS) {
211 ret = export_ctx.wimlib_err_code;
214 L"Failed to read encrypted file \"%ls\"",
215 printable_path(lte->file_on_disk));
216 ret = WIMLIB_ERR_READ;
218 } else if (export_ctx.bytes_remaining != 0) {
219 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
220 "encrypted file \"%ls\"",
221 size - export_ctx.bytes_remaining, size,
222 printable_path(lte->file_on_disk));
223 ret = WIMLIB_ERR_READ;
227 CloseEncryptedFileRaw(file_ctx);
232 * Load the short name of a file into a WIM dentry.
235 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
237 /* It's not any harder to just make the NtQueryInformationFile() system
238 * call ourselves, and it saves a dumb call to FindFirstFile() which of
239 * course has to create its own handle. */
241 IO_STATUS_BLOCK iosb;
242 u8 buf[128] _aligned_attribute(8);
243 const FILE_NAME_INFORMATION *info;
245 status = (*func_NtQueryInformationFile)(h, &iosb, buf, sizeof(buf),
246 FileAlternateNameInformation);
247 info = (const FILE_NAME_INFORMATION *)buf;
248 if (NT_SUCCESS(status) && info->FileNameLength != 0) {
249 dentry->short_name = utf16le_dupz(info->FileName,
250 info->FileNameLength);
251 if (!dentry->short_name)
252 return STATUS_NO_MEMORY;
253 dentry->short_name_nbytes = info->FileNameLength;
259 * Load the security descriptor of a file into the corresponding inode and the
260 * WIM image's security descriptor set.
263 winnt_get_security_descriptor(HANDLE h, struct wim_inode *inode,
264 struct wim_sd_set *sd_set,
265 struct winnt_scan_stats *stats, int add_flags)
267 SECURITY_INFORMATION requestedInformation;
268 u8 _buf[4096] _aligned_attribute(8);
275 * LABEL_SECURITY_INFORMATION is needed on Windows Vista and 7 because
276 * Microsoft decided to add mandatory integrity labels to the SACL but
277 * not have them returned by SACL_SECURITY_INFORMATION.
279 * BACKUP_SECURITY_INFORMATION is needed on Windows 8 because Microsoft
280 * decided to add even more stuff to the SACL and still not have it
281 * returned by SACL_SECURITY_INFORMATION; but they did remember that
282 * backup applications exist and simply want to read the stupid thing
283 * once and for all, so they added a flag to read the entire security
286 * Older versions of Windows tolerate these new flags being passed in.
288 requestedInformation = OWNER_SECURITY_INFORMATION |
289 GROUP_SECURITY_INFORMATION |
290 DACL_SECURITY_INFORMATION |
291 SACL_SECURITY_INFORMATION |
292 LABEL_SECURITY_INFORMATION |
293 BACKUP_SECURITY_INFORMATION;
296 bufsize = sizeof(_buf);
299 * We need the file's security descriptor in
300 * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
301 * opened with as many relevant permissions as possible. At this point,
302 * on Windows there are a number of options for reading a file's
303 * security descriptor:
305 * GetFileSecurity(): This takes in a path and returns the
306 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle,
307 * not ours, and the handle created internally doesn't specify
308 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied
309 * errors on some files and directories, even when running as the
312 * GetSecurityInfo(): This takes in a handle and returns the security
313 * descriptor split into a bunch of different parts. This should work,
314 * but it's dumb because we have to put the security descriptor back
317 * BackupRead(): This can read the security descriptor, but this is a
318 * difficult-to-use API, probably only works as the Administrator, and
319 * the format of the returned data is not well documented.
321 * NtQuerySecurityObject(): This is exactly what we need, as it takes
322 * in a handle and returns the security descriptor in
323 * SECURITY_DESCRIPTOR_RELATIVE format. Only problem is that it's a
324 * ntdll function and therefore not officially part of the Win32 API.
327 while (!(NT_SUCCESS(status = (*func_NtQuerySecurityObject)(h,
328 requestedInformation,
329 (PSECURITY_DESCRIPTOR)buf,
334 case STATUS_BUFFER_TOO_SMALL:
335 wimlib_assert(buf == _buf);
336 buf = MALLOC(len_needed);
338 return STATUS_NO_MEMORY;
339 bufsize = len_needed;
341 case STATUS_PRIVILEGE_NOT_HELD:
342 case STATUS_ACCESS_DENIED:
343 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
345 /* Permission denied in STRICT_ACLS mode, or
349 if (requestedInformation & SACL_SECURITY_INFORMATION) {
350 /* Try again without the SACL. */
351 stats->num_get_sacl_priv_notheld++;
352 requestedInformation &= ~(SACL_SECURITY_INFORMATION |
353 LABEL_SECURITY_INFORMATION |
354 BACKUP_SECURITY_INFORMATION);
357 /* Fake success (useful when capturing as
358 * non-Administrator). */
359 stats->num_get_sd_access_denied++;
360 status = STATUS_SUCCESS;
365 /* Add the security descriptor to the WIM image, and save its ID in
367 inode->i_security_id = sd_set_add_sd(sd_set, buf, len_needed);
368 if (unlikely(inode->i_security_id < 0))
369 status = STATUS_NO_MEMORY;
371 if (unlikely(buf != _buf))
377 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
380 size_t full_path_nchars,
381 const wchar_t *filename,
382 size_t filename_nchars,
383 struct capture_params *params,
384 struct winnt_scan_stats *stats,
388 winnt_recurse_directory(HANDLE h,
390 size_t full_path_nchars,
391 struct wim_dentry *parent,
392 struct capture_params *params,
393 struct winnt_scan_stats *stats,
397 const size_t bufsize = 8192;
398 IO_STATUS_BLOCK iosb;
402 buf = MALLOC(bufsize);
404 return WIMLIB_ERR_NOMEM;
406 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
407 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
409 while (NT_SUCCESS(status = (*func_NtQueryDirectoryFile)(h, NULL, NULL, NULL,
411 FileNamesInformation,
412 FALSE, NULL, FALSE)))
414 const FILE_NAMES_INFORMATION *info = buf;
416 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
417 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
418 info->FileName[1] == L'.'))
422 struct wim_dentry *child;
424 p = full_path + full_path_nchars;
425 /* Only add a backslash if we don't already have
426 * one. This prevents a duplicate backslash
427 * from being added when the path to the capture
428 * dir had a trailing backslash. */
429 if (*(p - 1) != L'\\')
432 p = wmempcpy(filename, info->FileName,
433 info->FileNameLength / 2);
436 ret = winnt_build_dentry_tree_recursive(
442 info->FileNameLength / 2,
447 full_path[full_path_nchars] = L'\0';
452 dentry_add_child(parent, child);
454 if (info->NextEntryOffset == 0)
456 info = (const FILE_NAMES_INFORMATION *)
457 ((const u8 *)info + info->NextEntryOffset);
461 if (unlikely(status != STATUS_NO_MORE_FILES)) {
462 winnt_error(status, L"\"%ls\": Can't read directory",
463 printable_path(full_path));
464 ret = WIMLIB_ERR_READ;
471 /* Reparse point fixup status code */
473 /* Reparse point will be captured literally (no fixup) */
476 /* Reparse point will be captured with fixup */
481 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
484 IO_STATUS_BLOCK iosb;
485 FILE_INTERNAL_INFORMATION int_info;
486 FILE_FS_VOLUME_INFORMATION vol_info;
488 status = (*func_NtQueryInformationFile)(h, &iosb,
489 &int_info, sizeof(int_info),
490 FileInternalInformation);
491 if (!NT_SUCCESS(status))
494 if (int_info.IndexNumber.QuadPart != ino)
497 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
498 &vol_info, sizeof(vol_info),
499 FileFsVolumeInformation);
500 if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
503 if (iosb.Information <
504 offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
505 sizeof(vol_info.VolumeSerialNumber))
508 return (vol_info.VolumeSerialNumber == dev);
512 * Given an (expected) NT namespace symbolic link or junction target @target of
513 * length @target_nbytes, determine if a prefix of the target points to a file
514 * identified by @capture_root_ino and @capture_root_dev.
516 * If yes, return a pointer to the portion of the link following this prefix.
518 * If no, return NULL.
520 * If the link target does not appear to be a valid NT namespace path, return
523 static const wchar_t *
524 winnt_get_root_relative_target(const wchar_t *target, size_t target_nbytes,
525 u64 capture_root_ino, u64 capture_root_dev)
528 OBJECT_ATTRIBUTES attr;
529 IO_STATUS_BLOCK iosb;
531 const wchar_t *target_end;
534 target_end = target + (target_nbytes / sizeof(wchar_t));
537 if (target_end == target)
540 /* No leading slash??? */
541 if (target[0] != L'\\')
545 if ((target_end - target) >= 2 &&
546 target[0] == L'\\' && target[1] == L'\\')
549 attr.Length = sizeof(attr);
550 attr.RootDirectory = NULL;
551 attr.ObjectName = &name;
553 attr.SecurityDescriptor = NULL;
554 attr.SecurityQualityOfService = NULL;
556 name.Buffer = (wchar_t *)target;
561 const wchar_t *orig_p = p;
563 /* Skip non-backslashes */
564 while (p != target_end && *p != L'\\')
567 /* Skip backslashes */
568 while (p != target_end && *p == L'\\')
571 /* Append path component */
572 name.Length += (p - orig_p) * sizeof(wchar_t);
573 name.MaximumLength = name.Length;
575 /* Try opening the file */
576 status = (*func_NtOpenFile) (&h,
577 FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
580 FILE_SHARE_VALID_FLAGS,
581 FILE_OPEN_FOR_BACKUP_INTENT);
583 if (NT_SUCCESS(status)) {
584 /* Reset root directory */
585 if (attr.RootDirectory)
586 (*func_NtClose)(attr.RootDirectory);
587 attr.RootDirectory = h;
588 name.Buffer = (wchar_t *)p;
591 if (file_has_ino_and_dev(h, capture_root_ino,
593 goto out_close_root_dir;
595 } while (p != target_end);
600 if (attr.RootDirectory)
601 (*func_NtClose)(attr.RootDirectory);
606 winnt_rpfix_progress(struct capture_params *params, const wchar_t *path,
607 const struct reparse_data *rpdata, int scan_status)
609 size_t print_name_nchars = rpdata->print_name_nbytes / sizeof(wchar_t);
610 wchar_t print_name0[print_name_nchars + 1];
612 wmemcpy(print_name0, rpdata->print_name, print_name_nchars);
613 print_name0[print_name_nchars] = L'\0';
615 params->progress.scan.cur_path = printable_path(path);
616 params->progress.scan.symlink_target = print_name0;
617 return do_capture_progress(params, scan_status, NULL);
621 winnt_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
622 u64 capture_root_ino, u64 capture_root_dev,
623 const wchar_t *path, struct capture_params *params)
625 struct reparse_data rpdata;
626 const wchar_t *rel_target;
629 if (parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata)) {
630 /* Couldn't even understand the reparse data. Don't try the
636 * Don't do reparse point fixups on relative symbolic links.
638 * On Windows, a relative symbolic link is supposed to be identifiable
639 * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
640 * SYMBOLIC_LINK_RELATIVE. We will use this information, although this
641 * may not always do what the user expects, since drive-relative
642 * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
643 * set, in addition to truely relative symbolic links such as "Users" or
644 * "Users\Public". However, WIMGAPI (as of Windows 8.1) has this same
647 * Otherwise, as far as I can tell, the targets of symbolic links that
648 * are NOT relative, as well as junctions (note: a mountpoint is the
649 * sames thing as a junction), must be NT namespace paths, for example:
651 * - \??\e:\Users\Public
652 * - \DosDevices\e:\Users\Public
653 * - \Device\HardDiskVolume4\Users\Public
654 * - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
655 * - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
657 if (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
658 (rpdata.rpflags & SYMBOLIC_LINK_RELATIVE))
661 rel_target = winnt_get_root_relative_target(rpdata.substitute_name,
662 rpdata.substitute_name_nbytes,
666 /* Target points outside of the tree being captured. Don't
668 ret = winnt_rpfix_progress(params, path, &rpdata,
669 WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK);
675 if (rel_target == rpdata.substitute_name) {
676 /* Weird target --- keep the reparse point and don't mess with
681 /* We have an absolute target pointing within the directory being
682 * captured. @rel_target is the suffix of the link target that is the
683 * part relative to the directory being captured.
685 * We will cut off the prefix before this part (which is the path to the
686 * directory being captured) and add a dummy prefix. Since the process
687 * will need to be reversed when applying the image, it shouldn't matter
688 * what exactly the prefix is, as long as it looks like an absolute
693 size_t rel_target_nbytes =
694 rpdata.substitute_name_nbytes - ((const u8 *)rel_target -
695 (const u8 *)rpdata.substitute_name);
696 size_t rel_target_nchars = rel_target_nbytes / sizeof(wchar_t);
698 wchar_t tmp[rel_target_nchars + 7];
700 wmemcpy(tmp, L"\\??\\X:\\", 7);
701 wmemcpy(tmp + 7, rel_target, rel_target_nchars);
703 rpdata.substitute_name = tmp;
704 rpdata.substitute_name_nbytes = rel_target_nbytes + (7 * sizeof(wchar_t));
705 rpdata.print_name = tmp + 4;
706 rpdata.print_name_nbytes = rel_target_nbytes + (3 * sizeof(wchar_t));
708 if (make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p))
711 ret = winnt_rpfix_progress(params, path, &rpdata,
712 WIMLIB_SCAN_DENTRY_FIXED_SYMLINK);
719 * Loads the reparse point data from a reparse point into memory, optionally
720 * fixing the targets of absolute symbolic links and junction points to be
721 * relative to the root of capture.
724 * Open handle to the reparse point file.
726 * Path to the reparse point file.
728 * Capture parameters. add_flags, capture_root_ino, capture_root_dev,
729 * progfunc, progctx, and progress are used.
731 * Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which the
732 * reparse point buffer will be loaded.
734 * On success, the length of the reparse point buffer in bytes is written
737 * On success, returns a negative `enum rp_status' value.
738 * On failure, returns a positive error code.
741 winnt_get_reparse_data(HANDLE h, const wchar_t *path,
742 struct capture_params *params,
743 u8 *rpbuf, u16 *rpbuflen_ret)
745 DWORD bytes_returned;
750 if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
751 NULL, 0, rpbuf, REPARSE_POINT_MAX_SIZE,
752 &bytes_returned, NULL))
754 win32_error(GetLastError(), L"\"%ls\": Can't get reparse data",
755 printable_path(path));
756 return WIMLIB_ERR_READ;
759 if (unlikely(bytes_returned < 8)) {
760 ERROR("\"%ls\": Reparse point data is invalid",
761 printable_path(path));
762 return WIMLIB_ERR_INVALID_REPARSE_DATA;
765 rpbuflen = bytes_returned;
766 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
768 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
769 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
770 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
772 ret = winnt_try_rpfix(rpbuf, &rpbuflen,
773 params->capture_root_ino,
774 params->capture_root_dev,
777 *rpbuflen_ret = rpbuflen;
782 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
785 *(u64*)_size_ret += len;
786 return ERROR_SUCCESS;
790 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
796 err = OpenEncryptedFileRaw(path, 0, &file_ctx);
797 if (err != ERROR_SUCCESS) {
799 L"Failed to open encrypted file \"%ls\" for raw read",
800 printable_path(path));
801 return WIMLIB_ERR_OPEN;
804 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
806 if (err != ERROR_SUCCESS) {
808 L"Failed to read raw encrypted data from \"%ls\"",
809 printable_path(path));
810 ret = WIMLIB_ERR_READ;
814 CloseEncryptedFileRaw(file_ctx);
819 winnt_load_encrypted_stream_info(struct wim_inode *inode, const wchar_t *nt_path,
820 struct list_head *unhashed_streams)
822 struct wim_lookup_table_entry *lte = new_lookup_table_entry();
826 return WIMLIB_ERR_NOMEM;
828 lte->file_on_disk = WCSDUP(nt_path);
829 if (unlikely(!lte->file_on_disk)) {
830 free_lookup_table_entry(lte);
831 return WIMLIB_ERR_NOMEM;
833 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
835 /* OpenEncryptedFileRaw() expects a Win32 name. */
836 wimlib_assert(!wmemcmp(lte->file_on_disk, L"\\??\\", 4));
837 lte->file_on_disk[1] = L'\\';
839 ret = win32_get_encrypted_file_size(lte->file_on_disk, <e->size);
841 free_lookup_table_entry(lte);
845 lte->file_inode = inode;
846 add_unhashed_stream(lte, inode, 0, unhashed_streams);
852 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
853 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
855 const wchar_t *sep, *type, *end;
857 /* The stream name should be returned as :NAME:TYPE */
858 if (raw_stream_name_nchars < 1)
860 if (raw_stream_name[0] != L':')
864 raw_stream_name_nchars--;
866 end = raw_stream_name + raw_stream_name_nchars;
868 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
876 if (wmemcmp(type, L"$DATA", 5))
879 *stream_name_ret = raw_stream_name;
880 *stream_name_nchars_ret = sep - raw_stream_name;
885 build_stream_path(const wchar_t *path, size_t path_nchars,
886 const wchar_t *stream_name, size_t stream_name_nchars)
888 size_t stream_path_nchars;
889 wchar_t *stream_path;
892 stream_path_nchars = path_nchars;
893 if (stream_name_nchars)
894 stream_path_nchars += 1 + stream_name_nchars;
896 stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
898 p = wmempcpy(stream_path, path, path_nchars);
899 if (stream_name_nchars) {
901 p = wmempcpy(p, stream_name, stream_name_nchars);
909 winnt_scan_stream(const wchar_t *path, size_t path_nchars,
910 const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
912 struct wim_inode *inode, struct list_head *unhashed_streams)
914 const wchar_t *stream_name;
915 size_t stream_name_nchars;
916 struct wim_ads_entry *ads_entry;
917 wchar_t *stream_path;
918 struct wim_lookup_table_entry *lte;
921 /* Given the raw stream name (which is something like
922 * :streamname:$DATA), extract just the stream name part.
923 * Ignore any non-$DATA streams. */
924 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
925 &stream_name, &stream_name_nchars))
928 /* If this is a named stream, allocate an ADS entry for it. */
929 if (stream_name_nchars) {
930 ads_entry = inode_add_ads_utf16le(inode, stream_name,
934 return WIMLIB_ERR_NOMEM;
935 } else if (inode->i_attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
936 FILE_ATTRIBUTE_ENCRYPTED))
938 /* Ignore unnamed data stream of reparse point or encrypted file
945 /* If the stream is empty, no lookup table entry is needed. */
946 if (stream_size == 0)
949 /* Build the path to the stream. For unnamed streams, this is simply
950 * the path to the file. For named streams, this is the path to the
951 * file, followed by a colon, followed by the stream name. */
952 stream_path = build_stream_path(path, path_nchars,
953 stream_name, stream_name_nchars);
955 return WIMLIB_ERR_NOMEM;
957 /* Set up the lookup table entry for the stream. */
958 lte = new_lookup_table_entry();
961 return WIMLIB_ERR_NOMEM;
963 lte->file_on_disk = stream_path;
964 lte->resource_location = RESOURCE_IN_WINNT_FILE_ON_DISK;
965 lte->size = stream_size;
967 stream_id = ads_entry->stream_id;
968 ads_entry->lte = lte;
973 lte->file_inode = inode;
974 add_unhashed_stream(lte, inode, stream_id, unhashed_streams);
979 * Load information about the streams of an open file into a WIM inode.
981 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
982 * and FindNextStream(). This is done for two reasons:
984 * - FindFirstStream() opens its own handle to the file or directory and
985 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
986 * causing access denied errors on certain files (even when running as the
988 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
989 * and later, whereas the stream support in NtQueryInformationFile() was
990 * already present in Windows XP.
993 winnt_scan_streams(HANDLE h, const wchar_t *path, size_t path_nchars,
994 struct wim_inode *inode, struct list_head *unhashed_streams,
995 u64 file_size, u32 vol_flags)
998 u8 _buf[1024] _aligned_attribute(8);
1001 IO_STATUS_BLOCK iosb;
1003 const FILE_STREAM_INFORMATION *info;
1006 bufsize = sizeof(_buf);
1008 if (!(vol_flags & FILE_NAMED_STREAMS))
1011 /* Get a buffer containing the stream information. */
1012 while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(h,
1016 FileStreamInformation)))
1020 case STATUS_BUFFER_OVERFLOW:
1026 newbuf = MALLOC(bufsize);
1028 newbuf = REALLOC(buf, bufsize);
1030 ret = WIMLIB_ERR_NOMEM;
1036 case STATUS_NOT_IMPLEMENTED:
1037 case STATUS_NOT_SUPPORTED:
1038 case STATUS_INVALID_INFO_CLASS:
1042 L"\"%ls\": Failed to query stream information",
1043 printable_path(path));
1044 ret = WIMLIB_ERR_READ;
1049 if (iosb.Information == 0) {
1050 /* No stream information. */
1055 /* Parse one or more stream information structures. */
1056 info = (const FILE_STREAM_INFORMATION *)buf;
1058 /* Load the stream information. */
1059 ret = winnt_scan_stream(path, path_nchars,
1061 info->StreamNameLength / 2,
1062 info->StreamSize.QuadPart,
1063 inode, unhashed_streams);
1067 if (info->NextEntryOffset == 0) {
1068 /* No more stream information. */
1071 /* Advance to next stream information. */
1072 info = (const FILE_STREAM_INFORMATION *)
1073 ((const u8 *)info + info->NextEntryOffset);
1079 /* The volume does not support named streams. Only capture the unnamed
1081 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1082 FILE_ATTRIBUTE_REPARSE_POINT))
1088 ret = winnt_scan_stream(path, path_nchars, L"::$DATA", 7,
1089 file_size, inode, unhashed_streams);
1091 /* Free buffer if allocated on heap. */
1092 if (unlikely(buf != _buf))
1098 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1101 size_t full_path_nchars,
1102 const wchar_t *filename,
1103 size_t filename_nchars,
1104 struct capture_params *params,
1105 struct winnt_scan_stats *stats,
1108 struct wim_dentry *root = NULL;
1109 struct wim_inode *inode = NULL;
1113 FILE_ALL_INFORMATION file_info;
1117 ACCESS_MASK requestedPerms;
1119 ret = try_exclude(full_path, full_path_nchars, params);
1120 if (ret < 0) /* Excluded? */
1122 if (ret > 0) /* Error? */
1125 /* Open the file. */
1126 requestedPerms = FILE_READ_DATA |
1127 FILE_READ_ATTRIBUTES |
1129 ACCESS_SYSTEM_SECURITY |
1132 status = winnt_openat(cur_dir,
1133 (cur_dir ? filename : full_path),
1134 (cur_dir ? filename_nchars : full_path_nchars),
1137 if (unlikely(!NT_SUCCESS(status))) {
1138 if (status == STATUS_DELETE_PENDING) {
1139 WARNING("\"%ls\": Deletion pending; skipping file",
1140 printable_path(full_path));
1144 if (status == STATUS_ACCESS_DENIED &&
1145 (requestedPerms & FILE_READ_DATA)) {
1146 /* This happens on encrypted files. */
1147 requestedPerms &= ~FILE_READ_DATA;
1151 winnt_error(status, L"\"%ls\": Can't open file",
1152 printable_path(full_path));
1153 if (status == STATUS_FVE_LOCKED_VOLUME)
1154 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1156 ret = WIMLIB_ERR_OPEN;
1160 /* Get information about the file. */
1162 IO_STATUS_BLOCK iosb;
1164 status = (*func_NtQueryInformationFile)(h, &iosb,
1167 FileAllInformation);
1169 if (unlikely(!NT_SUCCESS(status) &&
1170 status != STATUS_BUFFER_OVERFLOW))
1173 L"\"%ls\": Can't get file information",
1174 printable_path(full_path));
1175 ret = WIMLIB_ERR_STAT;
1180 if (unlikely(!(requestedPerms & FILE_READ_DATA)) &&
1181 !(file_info.BasicInformation.FileAttributes & FILE_ATTRIBUTE_ENCRYPTED))
1183 ERROR("\"%ls\": Permission to read data was denied",
1184 printable_path(full_path));
1185 ret = WIMLIB_ERR_OPEN;
1189 if (unlikely(!cur_dir)) {
1191 /* Root of tree being captured; get volume information. */
1193 FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1194 FILE_FS_VOLUME_INFORMATION vol_info;
1195 IO_STATUS_BLOCK iosb;
1197 /* Get volume flags */
1198 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1201 FileFsAttributeInformation);
1202 if (likely((NT_SUCCESS(status) ||
1203 (status == STATUS_BUFFER_OVERFLOW)) &&
1204 (iosb.Information >=
1205 offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1206 FileSystemAttributes) +
1207 sizeof(attr_info.FileSystemAttributes))))
1209 vol_flags = attr_info.FileSystemAttributes;
1211 winnt_warning(status,
1212 L"\"%ls\": Can't get volume attributes",
1213 printable_path(full_path));
1217 /* Set inode number of root directory */
1218 params->capture_root_ino =
1219 file_info.InternalInformation.IndexNumber.QuadPart;
1221 /* Get volume ID. */
1222 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1225 FileFsVolumeInformation);
1226 if (likely((NT_SUCCESS(status) ||
1227 (status == STATUS_BUFFER_OVERFLOW)) &&
1228 (iosb.Information >=
1229 offsetof(FILE_FS_VOLUME_INFORMATION,
1230 VolumeSerialNumber) +
1231 sizeof(vol_info.VolumeSerialNumber))))
1233 params->capture_root_dev = vol_info.VolumeSerialNumber;
1235 winnt_warning(status, L"\"%ls\": Can't get volume ID",
1236 printable_path(full_path));
1237 params->capture_root_dev = 0;
1241 /* If this is a reparse point, read the reparse data. */
1242 if (unlikely(file_info.BasicInformation.FileAttributes &
1243 FILE_ATTRIBUTE_REPARSE_POINT))
1245 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1246 ret = winnt_get_reparse_data(h, full_path, params,
1260 /* Create a WIM dentry with an associated inode, which may be shared.
1262 * However, we need to explicitly check for directories and files with
1263 * only 1 link and refuse to hard link them. This is because Windows
1264 * has a bug where it can return duplicate File IDs for files and
1265 * directories on the FAT filesystem.
1267 * Since we don't follow mount points on Windows, we don't need to query
1268 * the volume ID per-file. Just once, for the root, is enough. But we
1269 * can't simply pass 0, because then there could be inode collisions
1270 * among multiple calls to win32_build_dentry_tree() that are scanning
1271 * files on different volumes. */
1272 ret = inode_table_new_dentry(params->inode_table,
1274 file_info.InternalInformation.IndexNumber.QuadPart,
1275 params->capture_root_dev,
1276 (file_info.StandardInformation.NumberOfLinks <= 1 ||
1277 (file_info.BasicInformation.FileAttributes &
1278 FILE_ATTRIBUTE_DIRECTORY)),
1283 /* Get the short (DOS) name of the file. */
1284 status = winnt_get_short_name(h, root);
1286 /* If we can't read the short filename for any reason other than
1287 * out-of-memory, just ignore the error and assume the file has no short
1288 * name. This shouldn't be an issue, since the short names are
1289 * essentially obsolete anyway. */
1290 if (unlikely(status == STATUS_NO_MEMORY)) {
1291 ret = WIMLIB_ERR_NOMEM;
1295 inode = root->d_inode;
1297 if (inode->i_nlink > 1) {
1298 /* Shared inode (hard link); skip reading per-inode information.
1303 inode->i_attributes = file_info.BasicInformation.FileAttributes;
1304 inode->i_creation_time = file_info.BasicInformation.CreationTime.QuadPart;
1305 inode->i_last_write_time = file_info.BasicInformation.LastWriteTime.QuadPart;
1306 inode->i_last_access_time = file_info.BasicInformation.LastAccessTime.QuadPart;
1307 inode->i_resolved = 1;
1309 /* Get the file's security descriptor, unless we are capturing in
1310 * NO_ACLS mode or the volume does not support security descriptors. */
1311 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1312 && (vol_flags & FILE_PERSISTENT_ACLS))
1314 status = winnt_get_security_descriptor(h, inode,
1315 params->sd_set, stats,
1317 if (!NT_SUCCESS(status)) {
1319 L"\"%ls\": Can't read security descriptor",
1320 printable_path(full_path));
1321 ret = WIMLIB_ERR_STAT;
1326 /* Load information about the unnamed data stream and any named data
1328 ret = winnt_scan_streams(h,
1332 params->unhashed_streams,
1333 file_info.StandardInformation.EndOfFile.QuadPart,
1338 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1339 /* Load information about the raw encrypted data. This is
1340 * needed for any directory or non-directory that has
1341 * FILE_ATTRIBUTE_ENCRYPTED set.
1343 * Note: since OpenEncryptedFileRaw() fails with
1344 * ERROR_SHARING_VIOLATION if there are any open handles to the
1345 * file, we have to close the file and re-open it later if
1349 ret = winnt_load_encrypted_stream_info(inode, full_path,
1350 params->unhashed_streams);
1355 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1356 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1357 WARNING("Ignoring reparse data of encrypted reparse point file \"%ls\"",
1358 printable_path(full_path));
1360 /* Reparse point: set the reparse data (already read). */
1362 inode->i_not_rpfixed = not_rpfixed;
1363 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1364 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1365 params->lookup_table);
1369 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1371 /* Directory: recurse to children. */
1374 /* Re-open handle that was closed to read raw encrypted
1376 status = winnt_openat(cur_dir,
1378 filename : full_path),
1380 filename_nchars : full_path_nchars),
1381 FILE_LIST_DIRECTORY | SYNCHRONIZE,
1383 if (!NT_SUCCESS(status)) {
1385 L"\"%ls\": Can't re-open file",
1386 printable_path(full_path));
1387 ret = WIMLIB_ERR_OPEN;
1391 ret = winnt_recurse_directory(h,
1403 params->progress.scan.cur_path = printable_path(full_path);
1405 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1407 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1411 if (unlikely(ret)) {
1412 free_dentry_tree(root, params->lookup_table);
1414 ret = report_capture_error(params, ret, full_path);
1421 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_stats *stats)
1423 if (likely(stats->num_get_sacl_priv_notheld == 0 &&
1424 stats->num_get_sd_access_denied == 0))
1427 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1428 if (stats->num_get_sacl_priv_notheld != 0) {
1429 WARNING("- Could not capture SACL (System Access Control List)\n"
1430 " on %lu files or directories.",
1431 stats->num_get_sacl_priv_notheld);
1433 if (stats->num_get_sd_access_denied != 0) {
1434 WARNING("- Could not capture security descriptor at all\n"
1435 " on %lu files or directories.",
1436 stats->num_get_sd_access_denied);
1438 WARNING("To fully capture all security descriptors, run the program\n"
1439 " with Administrator rights.");
1442 #define WINDOWS_NT_MAX_PATH 32768
1444 /* Win32 version of capturing a directory tree. */
1446 win32_build_dentry_tree(struct wim_dentry **root_ret,
1447 const wchar_t *root_disk_path,
1448 struct capture_params *params)
1452 UNICODE_STRING ntpath;
1453 struct winnt_scan_stats stats;
1454 size_t ntpath_nchars;
1456 /* WARNING: There is no check for overflow later when this buffer is
1457 * being used! But it's as long as the maximum path length understood
1458 * by Windows NT (which is NOT the same as MAX_PATH). */
1459 path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1461 return WIMLIB_ERR_NOMEM;
1463 ret = win32_path_to_nt_path(root_disk_path, &ntpath);
1467 if (ntpath.Length < 4 * sizeof(wchar_t) ||
1468 ntpath.Length > WINDOWS_NT_MAX_PATH * sizeof(wchar_t) ||
1469 wmemcmp(ntpath.Buffer, L"\\??\\", 4))
1471 ERROR("\"%ls\": unrecognized path format", root_disk_path);
1472 ret = WIMLIB_ERR_INVALID_PARAM;
1474 ntpath_nchars = ntpath.Length / sizeof(wchar_t);
1475 wmemcpy(path, ntpath.Buffer, ntpath_nchars);
1476 path[ntpath_nchars] = L'\0';
1478 params->capture_root_nchars = ntpath_nchars;
1479 if (path[ntpath_nchars - 1] == L'\\')
1480 params->capture_root_nchars--;
1483 HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
1487 memset(&stats, 0, sizeof(stats));
1489 ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
1490 path, ntpath_nchars,
1491 L"", 0, params, &stats, 0);
1495 winnt_do_scan_warnings(root_disk_path, &stats);
1499 #endif /* __WIN32__ */