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 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/.
32 #include "wimlib/win32_common.h"
34 #include "wimlib/assert.h"
35 #include "wimlib/capture.h"
36 #include "wimlib/dentry.h"
37 #include "wimlib/encoding.h"
38 #include "wimlib/endianness.h"
39 #include "wimlib/error.h"
40 #include "wimlib/lookup_table.h"
41 #include "wimlib/paths.h"
42 #include "wimlib/reparse.h"
44 struct winnt_scan_stats {
45 unsigned long num_get_sd_access_denied;
46 unsigned long num_get_sacl_priv_notheld;
49 static inline const wchar_t *
50 printable_path(const wchar_t *full_path)
52 /* Skip over \\?\ or \??\ */
57 * If cur_dir is not NULL, open an existing file relative to the already-open
60 * Otherwise, open the file specified by @path, which must be a Windows NT
64 winnt_openat(HANDLE cur_dir, const wchar_t *path, size_t path_nchars,
65 ACCESS_MASK perms, HANDLE *h_ret)
68 OBJECT_ATTRIBUTES attr;
72 name.Length = path_nchars * sizeof(wchar_t);
73 name.MaximumLength = name.Length + sizeof(wchar_t);
74 name.Buffer = (wchar_t *)path;
76 attr.Length = sizeof(attr);
77 attr.RootDirectory = cur_dir;
78 attr.ObjectName = &name;
80 attr.SecurityDescriptor = NULL;
81 attr.SecurityQualityOfService = NULL;
84 status = (*func_NtOpenFile)(h_ret, perms, &attr, &iosb,
85 FILE_SHARE_VALID_FLAGS,
86 FILE_OPEN_REPARSE_POINT |
87 FILE_OPEN_FOR_BACKUP_INTENT |
88 FILE_SYNCHRONOUS_IO_NONALERT |
89 FILE_SEQUENTIAL_ONLY);
90 if (!NT_SUCCESS(status)) {
91 /* Try requesting fewer permissions */
92 if (status == STATUS_ACCESS_DENIED ||
93 status == STATUS_PRIVILEGE_NOT_HELD) {
94 if (perms & ACCESS_SYSTEM_SECURITY) {
95 perms &= ~ACCESS_SYSTEM_SECURITY;
98 if (perms & READ_CONTROL) {
99 perms &= ~READ_CONTROL;
107 /* Read the first @size bytes from the file, or named data stream of a file,
108 * from which the stream entry @lte was created. */
110 read_winnt_file_prefix(const struct wim_lookup_table_entry *lte, u64 size,
111 consume_data_callback_t cb, void *cb_ctx)
120 /* This is an NT namespace path. */
121 path = lte->file_on_disk;
123 status = winnt_openat(NULL, path, wcslen(path),
124 FILE_READ_DATA | SYNCHRONIZE, &h);
125 if (!NT_SUCCESS(status)) {
126 set_errno_from_nt_status(status);
127 ERROR_WITH_ERRNO("\"%ls\": Can't open for reading "
128 "(status=0x%08"PRIx32")",
129 printable_path(path), (u32)status);
130 return WIMLIB_ERR_OPEN;
134 bytes_remaining = size;
135 while (bytes_remaining) {
136 IO_STATUS_BLOCK iosb;
140 count = min(sizeof(buf), bytes_remaining);
142 status = (*func_NtReadFile)(h, NULL, NULL, NULL,
143 &iosb, buf, count, NULL, NULL);
144 if (!NT_SUCCESS(status)) {
145 set_errno_from_nt_status(status);
146 ERROR_WITH_ERRNO("\"%ls\": Error reading data "
147 "(status=0x%08"PRIx32")",
148 printable_path(path), (u32)status);
149 ret = WIMLIB_ERR_READ;
153 bytes_read = iosb.Information;
155 bytes_remaining -= bytes_read;
156 ret = (*cb)(buf, bytes_read, cb_ctx);
164 struct win32_encrypted_read_ctx {
165 consume_data_callback_t read_prefix_cb;
166 void *read_prefix_ctx;
172 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
174 struct win32_encrypted_read_ctx *ctx = _ctx;
176 size_t bytes_to_consume = min(len, ctx->bytes_remaining);
178 if (bytes_to_consume == 0)
179 return ERROR_SUCCESS;
181 ret = (*ctx->read_prefix_cb)(data, bytes_to_consume, ctx->read_prefix_ctx);
183 ctx->wimlib_err_code = ret;
184 /* Shouldn't matter what error code is returned here, as long as
185 * it isn't ERROR_SUCCESS. */
186 return ERROR_READ_FAULT;
188 ctx->bytes_remaining -= bytes_to_consume;
189 return ERROR_SUCCESS;
193 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
195 consume_data_callback_t cb, void *cb_ctx)
197 struct win32_encrypted_read_ctx export_ctx;
202 export_ctx.read_prefix_cb = cb;
203 export_ctx.read_prefix_ctx = cb_ctx;
204 export_ctx.wimlib_err_code = 0;
205 export_ctx.bytes_remaining = size;
207 err = OpenEncryptedFileRaw(lte->file_on_disk, 0, &file_ctx);
208 if (err != ERROR_SUCCESS) {
209 set_errno_from_win32_error(err);
210 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
212 printable_path(lte->file_on_disk));
213 return WIMLIB_ERR_OPEN;
215 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
216 &export_ctx, file_ctx);
217 if (err != ERROR_SUCCESS) {
218 set_errno_from_win32_error(err);
219 ERROR_WITH_ERRNO("Failed to read encrypted file \"%ls\"",
220 printable_path(lte->file_on_disk));
221 ret = export_ctx.wimlib_err_code;
223 ret = WIMLIB_ERR_READ;
224 } else if (export_ctx.bytes_remaining != 0) {
225 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
226 "encrypted file \"%ls\"",
227 size - export_ctx.bytes_remaining, size,
228 printable_path(lte->file_on_disk));
229 ret = WIMLIB_ERR_READ;
233 CloseEncryptedFileRaw(file_ctx);
238 * Load the short name of a file into a WIM dentry.
241 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
243 /* It's not any harder to just make the NtQueryInformationFile() system
244 * call ourselves, and it saves a dumb call to FindFirstFile() which of
245 * course has to create its own handle. */
247 IO_STATUS_BLOCK iosb;
248 u8 buf[128] _aligned_attribute(8);
249 const FILE_NAME_INFORMATION *info;
251 status = (*func_NtQueryInformationFile)(h, &iosb, buf, sizeof(buf),
252 FileAlternateNameInformation);
253 info = (const FILE_NAME_INFORMATION *)buf;
254 if (NT_SUCCESS(status) && info->FileNameLength != 0) {
255 dentry->short_name = utf16le_dupz(info->FileName,
256 info->FileNameLength);
257 if (!dentry->short_name)
258 return STATUS_NO_MEMORY;
259 dentry->short_name_nbytes = info->FileNameLength;
265 * Load the security descriptor of a file into the corresponding inode and the
266 * WIM image's security descriptor set.
269 winnt_get_security_descriptor(HANDLE h, struct wim_inode *inode,
270 struct wim_sd_set *sd_set,
271 struct winnt_scan_stats *stats, int add_flags)
273 SECURITY_INFORMATION requestedInformation;
274 u8 _buf[4096] _aligned_attribute(8);
281 * LABEL_SECURITY_INFORMATION is needed on Windows Vista and 7 because
282 * Microsoft decided to add mandatory integrity labels to the SACL but
283 * not have them returned by SACL_SECURITY_INFORMATION.
285 * BACKUP_SECURITY_INFORMATION is needed on Windows 8 because Microsoft
286 * decided to add even more stuff to the SACL and still not have it
287 * returned by SACL_SECURITY_INFORMATION; but they did remember that
288 * backup applications exist and simply want to read the stupid thing
289 * once and for all, so they added a flag to read the entire security
292 * Older versions of Windows tolerate these new flags being passed in.
294 requestedInformation = OWNER_SECURITY_INFORMATION |
295 GROUP_SECURITY_INFORMATION |
296 DACL_SECURITY_INFORMATION |
297 SACL_SECURITY_INFORMATION |
298 LABEL_SECURITY_INFORMATION |
299 BACKUP_SECURITY_INFORMATION;
302 bufsize = sizeof(_buf);
305 * We need the file's security descriptor in
306 * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
307 * opened with as many relevant permissions as possible. At this point,
308 * on Windows there are a number of options for reading a file's
309 * security descriptor:
311 * GetFileSecurity(): This takes in a path and returns the
312 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle,
313 * not ours, and the handle created internally doesn't specify
314 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied
315 * errors on some files and directories, even when running as the
318 * GetSecurityInfo(): This takes in a handle and returns the security
319 * descriptor split into a bunch of different parts. This should work,
320 * but it's dumb because we have to put the security descriptor back
323 * BackupRead(): This can read the security descriptor, but this is a
324 * difficult-to-use API, probably only works as the Administrator, and
325 * the format of the returned data is not well documented.
327 * NtQuerySecurityObject(): This is exactly what we need, as it takes
328 * in a handle and returns the security descriptor in
329 * SECURITY_DESCRIPTOR_RELATIVE format. Only problem is that it's a
330 * ntdll function and therefore not officially part of the Win32 API.
333 while (!(NT_SUCCESS(status = (*func_NtQuerySecurityObject)(h,
334 requestedInformation,
335 (PSECURITY_DESCRIPTOR)buf,
340 case STATUS_BUFFER_TOO_SMALL:
341 wimlib_assert(buf == _buf);
342 buf = MALLOC(len_needed);
344 return STATUS_NO_MEMORY;
345 bufsize = len_needed;
347 case STATUS_PRIVILEGE_NOT_HELD:
348 case STATUS_ACCESS_DENIED:
349 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
351 /* Permission denied in STRICT_ACLS mode, or
355 if (requestedInformation & SACL_SECURITY_INFORMATION) {
356 /* Try again without the SACL. */
357 stats->num_get_sacl_priv_notheld++;
358 requestedInformation &= ~(SACL_SECURITY_INFORMATION |
359 LABEL_SECURITY_INFORMATION |
360 BACKUP_SECURITY_INFORMATION);
363 /* Fake success (useful when capturing as
364 * non-Administrator). */
365 stats->num_get_sd_access_denied++;
366 status = STATUS_SUCCESS;
371 /* Add the security descriptor to the WIM image, and save its ID in
373 inode->i_security_id = sd_set_add_sd(sd_set, buf, len_needed);
374 if (unlikely(inode->i_security_id < 0))
375 status = STATUS_NO_MEMORY;
377 if (unlikely(buf != _buf))
383 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
386 size_t full_path_nchars,
387 const wchar_t *filename,
388 size_t filename_nchars,
389 struct capture_params *params,
390 struct winnt_scan_stats *stats,
394 winnt_recurse_directory(HANDLE h,
396 size_t full_path_nchars,
397 struct wim_dentry *parent,
398 struct capture_params *params,
399 struct winnt_scan_stats *stats,
403 const size_t bufsize = 8192;
404 IO_STATUS_BLOCK iosb;
408 buf = MALLOC(bufsize);
410 return WIMLIB_ERR_NOMEM;
412 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
413 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
415 while (NT_SUCCESS(status = (*func_NtQueryDirectoryFile)(h, NULL, NULL, NULL,
417 FileNamesInformation,
418 FALSE, NULL, FALSE)))
420 const FILE_NAMES_INFORMATION *info = buf;
422 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
423 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
424 info->FileName[1] == L'.'))
428 struct wim_dentry *child;
430 p = full_path + full_path_nchars;
431 /* Only add a backslash if we don't already have
432 * one. This prevents a duplicate backslash
433 * from being added when the path to the capture
434 * dir had a trailing backslash. */
435 if (*(p - 1) != L'\\')
438 p = wmempcpy(filename, info->FileName,
439 info->FileNameLength / 2);
442 ret = winnt_build_dentry_tree_recursive(
448 info->FileNameLength / 2,
453 full_path[full_path_nchars] = L'\0';
458 dentry_add_child(parent, child);
460 if (info->NextEntryOffset == 0)
462 info = (const FILE_NAMES_INFORMATION *)
463 ((const u8 *)info + info->NextEntryOffset);
467 if (unlikely(status != STATUS_NO_MORE_FILES)) {
468 set_errno_from_nt_status(status);
469 ERROR_WITH_ERRNO("\"%ls\": Can't read directory "
470 "(status=0x%08"PRIx32")",
471 printable_path(full_path), (u32)status);
472 ret = WIMLIB_ERR_READ;
479 /* Reparse point fixup status code */
481 /* Reparse point will be captured literally (no fixup) */
484 /* Reparse point will be captured with fixup */
489 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
492 IO_STATUS_BLOCK iosb;
493 FILE_INTERNAL_INFORMATION int_info;
494 FILE_FS_VOLUME_INFORMATION vol_info;
496 status = (*func_NtQueryInformationFile)(h, &iosb,
497 &int_info, sizeof(int_info),
498 FileInternalInformation);
499 if (!NT_SUCCESS(status))
502 if (int_info.IndexNumber.QuadPart != ino)
505 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
506 &vol_info, sizeof(vol_info),
507 FileFsVolumeInformation);
508 if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
511 if (iosb.Information <
512 offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
513 sizeof(vol_info.VolumeSerialNumber))
516 return (vol_info.VolumeSerialNumber == dev);
520 * Given an (expected) NT namespace symbolic link or junction target @target of
521 * length @target_nbytes, determine if a prefix of the target points to a file
522 * identified by @capture_root_ino and @capture_root_dev.
524 * If yes, return a pointer to the portion of the link following this prefix.
526 * If no, return NULL.
528 * If the link target does not appear to be a valid NT namespace path, return
531 static const wchar_t *
532 winnt_get_root_relative_target(const wchar_t *target, size_t target_nbytes,
533 u64 capture_root_ino, u64 capture_root_dev)
536 OBJECT_ATTRIBUTES attr;
537 IO_STATUS_BLOCK iosb;
539 const wchar_t *target_end;
542 target_end = target + (target_nbytes / sizeof(wchar_t));
545 if (target_end == target)
548 /* No leading slash??? */
549 if (target[0] != L'\\')
553 if ((target_end - target) >= 2 &&
554 target[0] == L'\\' && target[1] == L'\\')
557 attr.Length = sizeof(attr);
558 attr.RootDirectory = NULL;
559 attr.ObjectName = &name;
561 attr.SecurityDescriptor = NULL;
562 attr.SecurityQualityOfService = NULL;
564 name.Buffer = (wchar_t *)target;
569 const wchar_t *orig_p = p;
571 /* Skip non-backslashes */
572 while (p != target_end && *p != L'\\')
575 /* Skip backslashes */
576 while (p != target_end && *p == L'\\')
579 /* Append path component */
580 name.Length += (p - orig_p) * sizeof(wchar_t);
581 name.MaximumLength = name.Length;
583 /* Try opening the file */
584 status = (*func_NtOpenFile) (&h,
585 FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
588 FILE_SHARE_VALID_FLAGS,
589 FILE_OPEN_FOR_BACKUP_INTENT);
591 if (NT_SUCCESS(status)) {
592 /* Reset root directory */
593 if (attr.RootDirectory)
594 (*func_NtClose)(attr.RootDirectory);
595 attr.RootDirectory = h;
596 name.Buffer = (wchar_t *)p;
599 if (file_has_ino_and_dev(h, capture_root_ino,
601 goto out_close_root_dir;
603 } while (p != target_end);
608 if (attr.RootDirectory)
609 (*func_NtClose)(attr.RootDirectory);
614 winnt_rpfix_progress(struct capture_params *params, const wchar_t *path,
615 const struct reparse_data *rpdata, int scan_status)
617 size_t print_name_nchars = rpdata->print_name_nbytes / sizeof(wchar_t);
618 wchar_t print_name0[print_name_nchars + 1];
620 wmemcpy(print_name0, rpdata->print_name, print_name_nchars);
621 print_name0[print_name_nchars] = L'\0';
623 params->progress.scan.cur_path = printable_path(path);
624 params->progress.scan.symlink_target = print_name0;
625 return do_capture_progress(params, scan_status, NULL);
629 winnt_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
630 u64 capture_root_ino, u64 capture_root_dev,
631 const wchar_t *path, struct capture_params *params)
633 struct reparse_data rpdata;
634 const wchar_t *rel_target;
637 if (parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata)) {
638 /* Couldn't even understand the reparse data. Don't try the
644 * Don't do reparse point fixups on relative symbolic links.
646 * On Windows, a relative symbolic link is supposed to be identifiable
647 * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
648 * SYMBOLIC_LINK_RELATIVE. We will use this information, although this
649 * may not always do what the user expects, since drive-relative
650 * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
651 * set, in addition to truely relative symbolic links such as "Users" or
652 * "Users\Public". However, WIMGAPI (as of Windows 8.1) has this same
655 * Otherwise, as far as I can tell, the targets of symbolic links that
656 * are NOT relative, as well as junctions (note: a mountpoint is the
657 * sames thing as a junction), must be NT namespace paths, for example:
659 * - \??\e:\Users\Public
660 * - \DosDevices\e:\Users\Public
661 * - \Device\HardDiskVolume4\Users\Public
662 * - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
663 * - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
665 if (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
666 (rpdata.rpflags & SYMBOLIC_LINK_RELATIVE))
669 rel_target = winnt_get_root_relative_target(rpdata.substitute_name,
670 rpdata.substitute_name_nbytes,
674 /* Target points outside of the tree being captured. Don't
676 ret = winnt_rpfix_progress(params, path, &rpdata,
677 WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK);
683 if (rel_target == rpdata.substitute_name) {
684 /* Weird target --- keep the reparse point and don't mess with
689 /* We have an absolute target pointing within the directory being
690 * captured. @rel_target is the suffix of the link target that is the
691 * part relative to the directory being captured.
693 * We will cut off the prefix before this part (which is the path to the
694 * directory being captured) and add a dummy prefix. Since the process
695 * will need to be reversed when applying the image, it shouldn't matter
696 * what exactly the prefix is, as long as it looks like an absolute
701 size_t rel_target_nbytes =
702 rpdata.substitute_name_nbytes - ((const u8 *)rel_target -
703 (const u8 *)rpdata.substitute_name);
704 size_t rel_target_nchars = rel_target_nbytes / sizeof(wchar_t);
706 wchar_t tmp[rel_target_nchars + 7];
708 wmemcpy(tmp, L"\\??\\X:\\", 7);
709 wmemcpy(tmp + 7, rel_target, rel_target_nchars);
711 rpdata.substitute_name = tmp;
712 rpdata.substitute_name_nbytes = rel_target_nbytes + (7 * sizeof(wchar_t));
713 rpdata.print_name = tmp + 4;
714 rpdata.print_name_nbytes = rel_target_nbytes + (3 * sizeof(wchar_t));
716 if (make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p))
719 ret = winnt_rpfix_progress(params, path, &rpdata,
720 WIMLIB_SCAN_DENTRY_FIXED_SYMLINK);
727 * Loads the reparse point data from a reparse point into memory, optionally
728 * fixing the targets of absolute symbolic links and junction points to be
729 * relative to the root of capture.
732 * Open handle to the reparse point file.
734 * Path to the reparse point file.
736 * Capture parameters. add_flags, capture_root_ino, capture_root_dev,
737 * progfunc, progctx, and progress are used.
739 * Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which the
740 * reparse point buffer will be loaded.
742 * On success, the length of the reparse point buffer in bytes is written
745 * On success, returns a negative `enum rp_status' value.
746 * On failure, returns a positive error code.
749 winnt_get_reparse_data(HANDLE h, const wchar_t *path,
750 struct capture_params *params,
751 u8 *rpbuf, u16 *rpbuflen_ret)
753 DWORD bytes_returned;
758 if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
759 NULL, 0, rpbuf, REPARSE_POINT_MAX_SIZE,
760 &bytes_returned, NULL))
762 set_errno_from_GetLastError();
763 return WIMLIB_ERR_READ;
766 if (unlikely(bytes_returned < 8)) {
768 return WIMLIB_ERR_INVALID_REPARSE_DATA;
771 rpbuflen = bytes_returned;
772 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
774 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
775 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
776 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
778 ret = winnt_try_rpfix(rpbuf, &rpbuflen,
779 params->capture_root_ino,
780 params->capture_root_dev,
783 *rpbuflen_ret = rpbuflen;
788 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
791 *(u64*)_size_ret += len;
792 return ERROR_SUCCESS;
796 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
802 err = OpenEncryptedFileRaw(path, 0, &file_ctx);
803 if (err != ERROR_SUCCESS) {
804 set_errno_from_win32_error(err);
805 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
806 "for raw read", printable_path(path));
807 return WIMLIB_ERR_OPEN;
810 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
812 if (err != ERROR_SUCCESS) {
813 set_errno_from_win32_error(err);
814 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
815 "\"%ls\"", printable_path(path));
816 ret = WIMLIB_ERR_READ;
820 CloseEncryptedFileRaw(file_ctx);
825 winnt_load_encrypted_stream_info(struct wim_inode *inode, const wchar_t *nt_path,
826 struct list_head *unhashed_streams)
828 struct wim_lookup_table_entry *lte = new_lookup_table_entry();
832 return WIMLIB_ERR_NOMEM;
834 lte->file_on_disk = WCSDUP(nt_path);
835 if (unlikely(!lte->file_on_disk)) {
836 free_lookup_table_entry(lte);
837 return WIMLIB_ERR_NOMEM;
839 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
841 /* OpenEncryptedFileRaw() expects a Win32 name. */
842 wimlib_assert(!wmemcmp(lte->file_on_disk, L"\\??\\", 4));
843 lte->file_on_disk[1] = L'\\';
845 ret = win32_get_encrypted_file_size(lte->file_on_disk, <e->size);
847 free_lookup_table_entry(lte);
851 lte->file_inode = inode;
852 add_unhashed_stream(lte, inode, 0, unhashed_streams);
858 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
859 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
861 const wchar_t *sep, *type, *end;
863 /* The stream name should be returned as :NAME:TYPE */
864 if (raw_stream_name_nchars < 1)
866 if (raw_stream_name[0] != L':')
870 raw_stream_name_nchars--;
872 end = raw_stream_name + raw_stream_name_nchars;
874 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
882 if (wmemcmp(type, L"$DATA", 5))
885 *stream_name_ret = raw_stream_name;
886 *stream_name_nchars_ret = sep - raw_stream_name;
891 build_stream_path(const wchar_t *path, size_t path_nchars,
892 const wchar_t *stream_name, size_t stream_name_nchars)
894 size_t stream_path_nchars;
895 wchar_t *stream_path;
898 stream_path_nchars = path_nchars;
899 if (stream_name_nchars)
900 stream_path_nchars += 1 + stream_name_nchars;
902 stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
904 p = wmempcpy(stream_path, path, path_nchars);
905 if (stream_name_nchars) {
907 p = wmempcpy(p, stream_name, stream_name_nchars);
915 winnt_scan_stream(const wchar_t *path, size_t path_nchars,
916 const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
918 struct wim_inode *inode, struct list_head *unhashed_streams)
920 const wchar_t *stream_name;
921 size_t stream_name_nchars;
922 struct wim_ads_entry *ads_entry;
923 wchar_t *stream_path;
924 struct wim_lookup_table_entry *lte;
927 /* Given the raw stream name (which is something like
928 * :streamname:$DATA), extract just the stream name part.
929 * Ignore any non-$DATA streams. */
930 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
931 &stream_name, &stream_name_nchars))
934 /* If this is a named stream, allocate an ADS entry for it. */
935 if (stream_name_nchars) {
936 ads_entry = inode_add_ads_utf16le(inode, stream_name,
940 return WIMLIB_ERR_NOMEM;
941 } else if (inode->i_attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
942 FILE_ATTRIBUTE_ENCRYPTED))
944 /* Ignore unnamed data stream of reparse point or encrypted file
951 /* If the stream is empty, no lookup table entry is needed. */
952 if (stream_size == 0)
955 /* Build the path to the stream. For unnamed streams, this is simply
956 * the path to the file. For named streams, this is the path to the
957 * file, followed by a colon, followed by the stream name. */
958 stream_path = build_stream_path(path, path_nchars,
959 stream_name, stream_name_nchars);
961 return WIMLIB_ERR_NOMEM;
963 /* Set up the lookup table entry for the stream. */
964 lte = new_lookup_table_entry();
967 return WIMLIB_ERR_NOMEM;
969 lte->file_on_disk = stream_path;
970 lte->resource_location = RESOURCE_IN_WINNT_FILE_ON_DISK;
971 lte->size = stream_size;
973 stream_id = ads_entry->stream_id;
974 ads_entry->lte = lte;
979 lte->file_inode = inode;
980 add_unhashed_stream(lte, inode, stream_id, unhashed_streams);
985 * Load information about the streams of an open file into a WIM inode.
987 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
988 * and FindNextStream(). This is done for two reasons:
990 * - FindFirstStream() opens its own handle to the file or directory and
991 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
992 * causing access denied errors on certain files (even when running as the
994 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
995 * and later, whereas the stream support in NtQueryInformationFile() was
996 * already present in Windows XP.
999 winnt_scan_streams(HANDLE h, const wchar_t *path, size_t path_nchars,
1000 struct wim_inode *inode, struct list_head *unhashed_streams,
1001 u64 file_size, u32 vol_flags)
1004 u8 _buf[1024] _aligned_attribute(8);
1007 IO_STATUS_BLOCK iosb;
1009 const FILE_STREAM_INFORMATION *info;
1012 bufsize = sizeof(_buf);
1014 if (!(vol_flags & FILE_NAMED_STREAMS))
1017 /* Get a buffer containing the stream information. */
1018 while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(h,
1022 FileStreamInformation)))
1026 case STATUS_BUFFER_OVERFLOW:
1032 newbuf = MALLOC(bufsize);
1034 newbuf = REALLOC(buf, bufsize);
1036 ret = WIMLIB_ERR_NOMEM;
1042 case STATUS_NOT_IMPLEMENTED:
1043 case STATUS_NOT_SUPPORTED:
1044 case STATUS_INVALID_INFO_CLASS:
1047 set_errno_from_nt_status(status);
1048 ERROR_WITH_ERRNO("\"%ls\": Failed to query stream "
1049 "information (status=0x%08"PRIx32")",
1050 printable_path(path), (u32)status);
1051 ret = WIMLIB_ERR_READ;
1056 if (iosb.Information == 0) {
1057 /* No stream information. */
1062 /* Parse one or more stream information structures. */
1063 info = (const FILE_STREAM_INFORMATION *)buf;
1065 /* Load the stream information. */
1066 ret = winnt_scan_stream(path, path_nchars,
1068 info->StreamNameLength / 2,
1069 info->StreamSize.QuadPart,
1070 inode, unhashed_streams);
1074 if (info->NextEntryOffset == 0) {
1075 /* No more stream information. */
1078 /* Advance to next stream information. */
1079 info = (const FILE_STREAM_INFORMATION *)
1080 ((const u8 *)info + info->NextEntryOffset);
1086 /* The volume does not support named streams. Only capture the unnamed
1088 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1089 FILE_ATTRIBUTE_REPARSE_POINT))
1095 ret = winnt_scan_stream(path, path_nchars, L"::$DATA", 7,
1096 file_size, inode, unhashed_streams);
1098 /* Free buffer if allocated on heap. */
1099 if (unlikely(buf != _buf))
1105 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1108 size_t full_path_nchars,
1109 const wchar_t *filename,
1110 size_t filename_nchars,
1111 struct capture_params *params,
1112 struct winnt_scan_stats *stats,
1115 struct wim_dentry *root = NULL;
1116 struct wim_inode *inode = NULL;
1120 FILE_ALL_INFORMATION file_info;
1124 ACCESS_MASK requestedPerms;
1126 ret = try_exclude(full_path, full_path_nchars, params);
1127 if (ret < 0) /* Excluded? */
1129 if (ret > 0) /* Error? */
1132 /* Open the file. */
1133 requestedPerms = FILE_READ_DATA |
1134 FILE_READ_ATTRIBUTES |
1136 ACCESS_SYSTEM_SECURITY |
1139 status = winnt_openat(cur_dir,
1140 (cur_dir ? filename : full_path),
1141 (cur_dir ? filename_nchars : full_path_nchars),
1144 if (unlikely(!NT_SUCCESS(status))) {
1145 if (status == STATUS_DELETE_PENDING) {
1146 WARNING("\"%ls\": Deletion pending; skipping file",
1147 printable_path(full_path));
1151 if (status == STATUS_ACCESS_DENIED &&
1152 (requestedPerms & FILE_READ_DATA)) {
1153 /* This happens on encrypted files. */
1154 requestedPerms &= ~FILE_READ_DATA;
1158 if (status == STATUS_FVE_LOCKED_VOLUME) {
1159 ERROR("\"%ls\": Can't open file "
1160 "(encrypted volume has not been unlocked)",
1161 printable_path(full_path));
1162 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1166 set_errno_from_nt_status(status);
1167 ERROR_WITH_ERRNO("\"%ls\": Can't open file "
1168 "(status=0x%08"PRIx32")",
1169 printable_path(full_path), (u32)status);
1170 ret = WIMLIB_ERR_OPEN;
1174 /* Get information about the file. */
1176 IO_STATUS_BLOCK iosb;
1178 status = (*func_NtQueryInformationFile)(h, &iosb,
1181 FileAllInformation);
1183 if (unlikely(!NT_SUCCESS(status) &&
1184 status != STATUS_BUFFER_OVERFLOW))
1186 set_errno_from_nt_status(status);
1187 ERROR_WITH_ERRNO("\"%ls\": Can't get file information "
1188 "(status=0x%08"PRIx32")",
1189 printable_path(full_path), (u32)status);
1190 ret = WIMLIB_ERR_STAT;
1195 if (unlikely(!(requestedPerms & FILE_READ_DATA)) &&
1196 !(file_info.BasicInformation.FileAttributes & FILE_ATTRIBUTE_ENCRYPTED))
1198 ERROR("\"%ls\": Permission to read data was denied",
1199 printable_path(full_path));
1200 ret = WIMLIB_ERR_OPEN;
1204 if (unlikely(!cur_dir)) {
1206 /* Root of tree being captured; get volume information. */
1208 FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1209 FILE_FS_VOLUME_INFORMATION vol_info;
1210 IO_STATUS_BLOCK iosb;
1212 /* Get volume flags */
1213 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1216 FileFsAttributeInformation);
1217 if (likely((NT_SUCCESS(status) ||
1218 (status == STATUS_BUFFER_OVERFLOW)) &&
1219 (iosb.Information >=
1220 offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1221 FileSystemAttributes) +
1222 sizeof(attr_info.FileSystemAttributes))))
1224 vol_flags = attr_info.FileSystemAttributes;
1226 set_errno_from_nt_status(status);
1227 WARNING_WITH_ERRNO("\"%ls\": Can't get volume attributes "
1228 "(status=0x%08"PRIx32")",
1229 printable_path(full_path),
1234 /* Set inode number of root directory */
1235 params->capture_root_ino =
1236 file_info.InternalInformation.IndexNumber.QuadPart;
1238 /* Get volume ID. */
1239 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1242 FileFsVolumeInformation);
1243 if (likely((NT_SUCCESS(status) ||
1244 (status == STATUS_BUFFER_OVERFLOW)) &&
1245 (iosb.Information >=
1246 offsetof(FILE_FS_VOLUME_INFORMATION,
1247 VolumeSerialNumber) +
1248 sizeof(vol_info.VolumeSerialNumber))))
1250 params->capture_root_dev = vol_info.VolumeSerialNumber;
1252 set_errno_from_nt_status(status);
1253 WARNING_WITH_ERRNO("\"%ls\": Can't get volume ID "
1254 "(status=0x%08"PRIx32")",
1255 printable_path(full_path),
1257 params->capture_root_dev = 0;
1261 /* If this is a reparse point, read the reparse data. */
1262 if (unlikely(file_info.BasicInformation.FileAttributes &
1263 FILE_ATTRIBUTE_REPARSE_POINT))
1265 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1266 ret = winnt_get_reparse_data(h, full_path, params,
1276 ERROR_WITH_ERRNO("\"%ls\": Can't get reparse data",
1277 printable_path(full_path));
1282 /* Create a WIM dentry with an associated inode, which may be shared.
1284 * However, we need to explicitly check for directories and files with
1285 * only 1 link and refuse to hard link them. This is because Windows
1286 * has a bug where it can return duplicate File IDs for files and
1287 * directories on the FAT filesystem.
1289 * Since we don't follow mount points on Windows, we don't need to query
1290 * the volume ID per-file. Just once, for the root, is enough. But we
1291 * can't simply pass 0, because then there could be inode collisions
1292 * among multiple calls to win32_build_dentry_tree() that are scanning
1293 * files on different volumes. */
1294 ret = inode_table_new_dentry(params->inode_table,
1296 file_info.InternalInformation.IndexNumber.QuadPart,
1297 params->capture_root_dev,
1298 (file_info.StandardInformation.NumberOfLinks <= 1 ||
1299 (file_info.BasicInformation.FileAttributes &
1300 FILE_ATTRIBUTE_DIRECTORY)),
1305 /* Get the short (DOS) name of the file. */
1306 status = winnt_get_short_name(h, root);
1308 /* If we can't read the short filename for any reason other than
1309 * out-of-memory, just ignore the error and assume the file has no short
1310 * name. This shouldn't be an issue, since the short names are
1311 * essentially obsolete anyway. */
1312 if (unlikely(status == STATUS_NO_MEMORY)) {
1313 ret = WIMLIB_ERR_NOMEM;
1317 inode = root->d_inode;
1319 if (inode->i_nlink > 1) {
1320 /* Shared inode (hard link); skip reading per-inode information.
1325 inode->i_attributes = file_info.BasicInformation.FileAttributes;
1326 inode->i_creation_time = file_info.BasicInformation.CreationTime.QuadPart;
1327 inode->i_last_write_time = file_info.BasicInformation.LastWriteTime.QuadPart;
1328 inode->i_last_access_time = file_info.BasicInformation.LastAccessTime.QuadPart;
1329 inode->i_resolved = 1;
1331 /* Get the file's security descriptor, unless we are capturing in
1332 * NO_ACLS mode or the volume does not support security descriptors. */
1333 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1334 && (vol_flags & FILE_PERSISTENT_ACLS))
1336 status = winnt_get_security_descriptor(h, inode,
1337 params->sd_set, stats,
1339 if (!NT_SUCCESS(status)) {
1340 set_errno_from_nt_status(status);
1341 ERROR_WITH_ERRNO("\"%ls\": Can't read security "
1342 "descriptor (status=0x%08"PRIx32")",
1343 printable_path(full_path),
1345 ret = WIMLIB_ERR_STAT;
1350 /* Load information about the unnamed data stream and any named data
1352 ret = winnt_scan_streams(h,
1356 params->unhashed_streams,
1357 file_info.StandardInformation.EndOfFile.QuadPart,
1362 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1363 /* Load information about the raw encrypted data. This is
1364 * needed for any directory or non-directory that has
1365 * FILE_ATTRIBUTE_ENCRYPTED set.
1367 * Note: since OpenEncryptedFileRaw() fails with
1368 * ERROR_SHARING_VIOLATION if there are any open handles to the
1369 * file, we have to close the file and re-open it later if
1373 ret = winnt_load_encrypted_stream_info(inode, full_path,
1374 params->unhashed_streams);
1379 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1380 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1381 WARNING("Ignoring reparse data of encrypted reparse point file \"%ls\"",
1382 printable_path(full_path));
1384 /* Reparse point: set the reparse data (already read). */
1386 inode->i_not_rpfixed = not_rpfixed;
1387 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1388 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1389 params->lookup_table);
1393 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1395 /* Directory: recurse to children. */
1398 /* Re-open handle that was closed to read raw encrypted
1400 status = winnt_openat(cur_dir,
1402 filename : full_path),
1404 filename_nchars : full_path_nchars),
1405 FILE_LIST_DIRECTORY | SYNCHRONIZE,
1407 if (!NT_SUCCESS(status)) {
1408 set_errno_from_nt_status(status);
1409 ERROR_WITH_ERRNO("\"%ls\": Can't re-open file "
1410 "(status=0x%08"PRIx32")",
1411 printable_path(full_path),
1413 ret = WIMLIB_ERR_OPEN;
1417 ret = winnt_recurse_directory(h,
1429 params->progress.scan.cur_path = printable_path(full_path);
1431 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1433 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1437 if (unlikely(ret)) {
1438 free_dentry_tree(root, params->lookup_table);
1440 ret = report_capture_error(params, ret, full_path);
1447 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_stats *stats)
1449 if (likely(stats->num_get_sacl_priv_notheld == 0 &&
1450 stats->num_get_sd_access_denied == 0))
1453 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1454 if (stats->num_get_sacl_priv_notheld != 0) {
1455 WARNING("- Could not capture SACL (System Access Control List)\n"
1456 " on %lu files or directories.",
1457 stats->num_get_sacl_priv_notheld);
1459 if (stats->num_get_sd_access_denied != 0) {
1460 WARNING("- Could not capture security descriptor at all\n"
1461 " on %lu files or directories.",
1462 stats->num_get_sd_access_denied);
1464 WARNING("To fully capture all security descriptors, run the program\n"
1465 " with Administrator rights.");
1468 #define WINDOWS_NT_MAX_PATH 32768
1470 /* Win32 version of capturing a directory tree. */
1472 win32_build_dentry_tree(struct wim_dentry **root_ret,
1473 const wchar_t *root_disk_path,
1474 struct capture_params *params)
1478 UNICODE_STRING ntpath;
1479 struct winnt_scan_stats stats;
1480 size_t ntpath_nchars;
1482 /* WARNING: There is no check for overflow later when this buffer is
1483 * being used! But it's as long as the maximum path length understood
1484 * by Windows NT (which is NOT the same as MAX_PATH). */
1485 path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1487 return WIMLIB_ERR_NOMEM;
1489 ret = win32_path_to_nt_path(root_disk_path, &ntpath);
1493 if (ntpath.Length < 4 * sizeof(wchar_t) ||
1494 ntpath.Length > WINDOWS_NT_MAX_PATH * sizeof(wchar_t) ||
1495 wmemcmp(ntpath.Buffer, L"\\??\\", 4))
1497 ERROR("\"%ls\": unrecognized path format", root_disk_path);
1498 ret = WIMLIB_ERR_INVALID_PARAM;
1500 ntpath_nchars = ntpath.Length / sizeof(wchar_t);
1501 wmemcpy(path, ntpath.Buffer, ntpath_nchars);
1502 path[ntpath_nchars] = L'\0';
1504 params->capture_root_nchars = ntpath_nchars;
1505 if (path[ntpath_nchars - 1] == L'\\')
1506 params->capture_root_nchars--;
1509 HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
1513 memset(&stats, 0, sizeof(stats));
1515 ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
1516 path, ntpath_nchars,
1517 L"", 0, params, &stats, 0);
1521 winnt_do_scan_warnings(root_disk_path, &stats);
1525 #endif /* __WIN32__ */