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/.
30 #include "wimlib/win32_common.h"
32 #include "wimlib/capture.h"
33 #include "wimlib/dentry.h"
34 #include "wimlib/encoding.h"
35 #include "wimlib/endianness.h"
36 #include "wimlib/error.h"
37 #include "wimlib/lookup_table.h"
38 #include "wimlib/paths.h"
39 #include "wimlib/reparse.h"
43 struct winnt_scan_stats {
44 unsigned long num_get_sd_access_denied;
45 unsigned long num_get_sacl_priv_notheld;
48 static inline const wchar_t *
49 printable_path(const wchar_t *full_path)
51 /* Skip over \\?\ or \??\ */
56 * If cur_dir is not NULL, open an existing file relative to the already-open
59 * Otherwise, open the file specified by @path, which must be a Windows NT
63 winnt_openat(HANDLE cur_dir, const wchar_t *path, size_t path_nchars,
64 ACCESS_MASK perms, HANDLE *h_ret)
67 OBJECT_ATTRIBUTES attr;
71 name.Length = path_nchars * sizeof(wchar_t);
72 name.MaximumLength = name.Length + sizeof(wchar_t);
73 name.Buffer = (wchar_t *)path;
75 attr.Length = sizeof(attr);
76 attr.RootDirectory = cur_dir;
77 attr.ObjectName = &name;
79 attr.SecurityDescriptor = NULL;
80 attr.SecurityQualityOfService = NULL;
83 status = (*func_NtOpenFile)(h_ret, perms, &attr, &iosb,
84 FILE_SHARE_VALID_FLAGS,
85 FILE_OPEN_REPARSE_POINT |
86 FILE_OPEN_FOR_BACKUP_INTENT |
87 FILE_SYNCHRONOUS_IO_NONALERT |
88 FILE_SEQUENTIAL_ONLY);
89 if (!NT_SUCCESS(status)) {
90 /* Try requesting fewer permissions */
91 if (status == STATUS_ACCESS_DENIED ||
92 status == STATUS_PRIVILEGE_NOT_HELD) {
93 if (perms & ACCESS_SYSTEM_SECURITY) {
94 perms &= ~ACCESS_SYSTEM_SECURITY;
97 if (perms & READ_CONTROL) {
98 perms &= ~READ_CONTROL;
106 /* Read the first @size bytes from the file, or named data stream of a file,
107 * from which the stream entry @lte was created. */
109 read_winnt_file_prefix(const struct wim_lookup_table_entry *lte, u64 size,
110 consume_data_callback_t cb, void *cb_ctx)
119 /* This is an NT namespace path. */
120 path = lte->file_on_disk;
122 status = winnt_openat(NULL, path, wcslen(path),
123 FILE_READ_DATA | SYNCHRONIZE, &h);
124 if (!NT_SUCCESS(status)) {
125 set_errno_from_nt_status(status);
126 ERROR_WITH_ERRNO("\"%ls\": Can't open for reading "
127 "(status=0x%08"PRIx32")",
128 printable_path(path), (u32)status);
129 return WIMLIB_ERR_OPEN;
133 bytes_remaining = size;
134 while (bytes_remaining) {
135 IO_STATUS_BLOCK iosb;
139 count = min(sizeof(buf), bytes_remaining);
141 status = (*func_NtReadFile)(h, NULL, NULL, NULL,
142 &iosb, buf, count, NULL, NULL);
143 if (!NT_SUCCESS(status)) {
144 set_errno_from_nt_status(status);
145 ERROR_WITH_ERRNO("\"%ls\": Error reading data "
146 "(status=0x%08"PRIx32")",
147 printable_path(path), (u32)status);
148 ret = WIMLIB_ERR_READ;
152 bytes_read = iosb.Information;
154 bytes_remaining -= bytes_read;
155 ret = (*cb)(buf, bytes_read, cb_ctx);
163 struct win32_encrypted_read_ctx {
164 consume_data_callback_t read_prefix_cb;
165 void *read_prefix_ctx;
171 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
173 struct win32_encrypted_read_ctx *ctx = _ctx;
175 size_t bytes_to_consume = min(len, ctx->bytes_remaining);
177 if (bytes_to_consume == 0)
178 return ERROR_SUCCESS;
180 ret = (*ctx->read_prefix_cb)(data, bytes_to_consume, ctx->read_prefix_ctx);
182 ctx->wimlib_err_code = ret;
183 /* Shouldn't matter what error code is returned here, as long as
184 * it isn't ERROR_SUCCESS. */
185 return ERROR_READ_FAULT;
187 ctx->bytes_remaining -= bytes_to_consume;
188 return ERROR_SUCCESS;
192 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
194 consume_data_callback_t cb, void *cb_ctx)
196 struct win32_encrypted_read_ctx export_ctx;
201 export_ctx.read_prefix_cb = cb;
202 export_ctx.read_prefix_ctx = cb_ctx;
203 export_ctx.wimlib_err_code = 0;
204 export_ctx.bytes_remaining = size;
206 err = OpenEncryptedFileRaw(lte->file_on_disk, 0, &file_ctx);
207 if (err != ERROR_SUCCESS) {
208 set_errno_from_win32_error(err);
209 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
211 printable_path(lte->file_on_disk));
212 return WIMLIB_ERR_OPEN;
214 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
215 &export_ctx, file_ctx);
216 if (err != ERROR_SUCCESS) {
217 set_errno_from_win32_error(err);
218 ERROR_WITH_ERRNO("Failed to read encrypted file \"%ls\"",
219 printable_path(lte->file_on_disk));
220 ret = export_ctx.wimlib_err_code;
222 ret = WIMLIB_ERR_READ;
223 } else if (export_ctx.bytes_remaining != 0) {
224 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
225 "encrypted file \"%ls\"",
226 size - export_ctx.bytes_remaining, size,
227 printable_path(lte->file_on_disk));
228 ret = WIMLIB_ERR_READ;
232 CloseEncryptedFileRaw(file_ctx);
237 * Load the short name of a file into a WIM dentry.
240 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
242 /* It's not any harder to just make the NtQueryInformationFile() system
243 * call ourselves, and it saves a dumb call to FindFirstFile() which of
244 * course has to create its own handle. */
246 IO_STATUS_BLOCK iosb;
247 u8 buf[128] _aligned_attribute(8);
248 const FILE_NAME_INFORMATION *info;
250 status = (*func_NtQueryInformationFile)(h, &iosb, buf, sizeof(buf),
251 FileAlternateNameInformation);
252 info = (const FILE_NAME_INFORMATION *)buf;
253 if (NT_SUCCESS(status) && info->FileNameLength != 0) {
254 dentry->short_name = utf16le_dupz(info->FileName,
255 info->FileNameLength);
256 if (!dentry->short_name)
257 return STATUS_NO_MEMORY;
258 dentry->short_name_nbytes = info->FileNameLength;
264 * Load the security descriptor of a file into the corresponding inode and the
265 * WIM image's security descriptor set.
268 winnt_get_security_descriptor(HANDLE h, struct wim_inode *inode,
269 struct wim_sd_set *sd_set,
270 struct winnt_scan_stats *stats, int add_flags)
272 SECURITY_INFORMATION requestedInformation;
273 u8 _buf[4096] _aligned_attribute(8);
280 * LABEL_SECURITY_INFORMATION is needed on Windows Vista and 7 because
281 * Microsoft decided to add mandatory integrity labels to the SACL but
282 * not have them returned by SACL_SECURITY_INFORMATION.
284 * BACKUP_SECURITY_INFORMATION is needed on Windows 8 because Microsoft
285 * decided to add even more stuff to the SACL and still not have it
286 * returned by SACL_SECURITY_INFORMATION; but they did remember that
287 * backup applications exist and simply want to read the stupid thing
288 * once and for all, so they added a flag to read the entire security
291 * Older versions of Windows tolerate these new flags being passed in.
293 requestedInformation = OWNER_SECURITY_INFORMATION |
294 GROUP_SECURITY_INFORMATION |
295 DACL_SECURITY_INFORMATION |
296 SACL_SECURITY_INFORMATION |
297 LABEL_SECURITY_INFORMATION |
298 BACKUP_SECURITY_INFORMATION;
301 bufsize = sizeof(_buf);
304 * We need the file's security descriptor in
305 * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
306 * opened with as many relevant permissions as possible. At this point,
307 * on Windows there are a number of options for reading a file's
308 * security descriptor:
310 * GetFileSecurity(): This takes in a path and returns the
311 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle,
312 * not ours, and the handle created internally doesn't specify
313 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied
314 * errors on some files and directories, even when running as the
317 * GetSecurityInfo(): This takes in a handle and returns the security
318 * descriptor split into a bunch of different parts. This should work,
319 * but it's dumb because we have to put the security descriptor back
322 * BackupRead(): This can read the security descriptor, but this is a
323 * difficult-to-use API, probably only works as the Administrator, and
324 * the format of the returned data is not well documented.
326 * NtQuerySecurityObject(): This is exactly what we need, as it takes
327 * in a handle and returns the security descriptor in
328 * SECURITY_DESCRIPTOR_RELATIVE format. Only problem is that it's a
329 * ntdll function and therefore not officially part of the Win32 API.
332 while (!(NT_SUCCESS(status = (*func_NtQuerySecurityObject)(h,
333 requestedInformation,
334 (PSECURITY_DESCRIPTOR)buf,
339 case STATUS_BUFFER_TOO_SMALL:
340 wimlib_assert(buf == _buf);
341 buf = MALLOC(len_needed);
343 return STATUS_NO_MEMORY;
344 bufsize = len_needed;
346 case STATUS_PRIVILEGE_NOT_HELD:
347 case STATUS_ACCESS_DENIED:
348 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
350 /* Permission denied in STRICT_ACLS mode, or
354 if (requestedInformation & SACL_SECURITY_INFORMATION) {
355 /* Try again without the SACL. */
356 stats->num_get_sacl_priv_notheld++;
357 requestedInformation &= ~(SACL_SECURITY_INFORMATION |
358 LABEL_SECURITY_INFORMATION |
359 BACKUP_SECURITY_INFORMATION);
362 /* Fake success (useful when capturing as
363 * non-Administrator). */
364 stats->num_get_sd_access_denied++;
365 status = STATUS_SUCCESS;
370 /* Add the security descriptor to the WIM image, and save its ID in
372 inode->i_security_id = sd_set_add_sd(sd_set, buf, len_needed);
373 if (unlikely(inode->i_security_id < 0))
374 status = STATUS_NO_MEMORY;
376 if (unlikely(buf != _buf))
382 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
385 size_t full_path_nchars,
386 const wchar_t *filename,
387 size_t filename_nchars,
388 struct add_image_params *params,
389 struct winnt_scan_stats *stats,
393 winnt_recurse_directory(HANDLE h,
395 size_t full_path_nchars,
396 struct wim_dentry *parent,
397 struct add_image_params *params,
398 struct winnt_scan_stats *stats,
402 const size_t bufsize = 8192;
403 IO_STATUS_BLOCK iosb;
407 buf = MALLOC(bufsize);
409 return WIMLIB_ERR_NOMEM;
411 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
412 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
414 while (NT_SUCCESS(status = (*func_NtQueryDirectoryFile)(h, NULL, NULL, NULL,
416 FileNamesInformation,
417 FALSE, NULL, FALSE)))
419 const FILE_NAMES_INFORMATION *info = buf;
421 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
422 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
423 info->FileName[1] == L'.'))
427 struct wim_dentry *child;
429 p = full_path + full_path_nchars;
430 /* Only add a backslash if we don't already have
431 * one. This prevents a duplicate backslash
432 * from being added when the path to the capture
433 * dir had a trailing backslash. */
434 if (*(p - 1) != L'\\')
437 p = wmempcpy(filename, info->FileName,
438 info->FileNameLength / 2);
441 ret = winnt_build_dentry_tree_recursive(
447 info->FileNameLength / 2,
452 full_path[full_path_nchars] = L'\0';
457 dentry_add_child(parent, child);
459 if (info->NextEntryOffset == 0)
461 info = (const FILE_NAMES_INFORMATION *)
462 ((const u8 *)info + info->NextEntryOffset);
466 if (unlikely(status != STATUS_NO_MORE_FILES)) {
467 set_errno_from_nt_status(status);
468 ERROR_WITH_ERRNO("\"%ls\": Can't read directory "
469 "(status=0x%08"PRIx32")",
470 printable_path(full_path), (u32)status);
471 ret = WIMLIB_ERR_READ;
478 /* Reparse point fixup status code */
480 /* Reparse point will be captured literally (no fixup) */
483 /* Reparse point will be captured with fixup */
488 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
491 IO_STATUS_BLOCK iosb;
492 FILE_INTERNAL_INFORMATION int_info;
493 FILE_FS_VOLUME_INFORMATION vol_info;
495 status = (*func_NtQueryInformationFile)(h, &iosb,
496 &int_info, sizeof(int_info),
497 FileInternalInformation);
498 if (!NT_SUCCESS(status))
501 if (int_info.IndexNumber.QuadPart != ino)
504 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
505 &vol_info, sizeof(vol_info),
506 FileFsVolumeInformation);
507 if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
510 if (iosb.Information <
511 offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
512 sizeof(vol_info.VolumeSerialNumber))
515 return (vol_info.VolumeSerialNumber == dev);
519 * Given an (expected) NT namespace symbolic link or junction target @target of
520 * length @target_nbytes, determine if a prefix of the target points to a file
521 * identified by @capture_root_ino and @capture_root_dev.
523 * If yes, return a pointer to the portion of the link following this prefix.
525 * If no, return NULL.
527 * If the link target does not appear to be a valid NT namespace path, return
530 static const wchar_t *
531 winnt_get_root_relative_target(const wchar_t *target, size_t target_nbytes,
532 u64 capture_root_ino, u64 capture_root_dev)
535 OBJECT_ATTRIBUTES attr;
536 IO_STATUS_BLOCK iosb;
538 const wchar_t *target_end;
541 target_end = target + (target_nbytes / sizeof(wchar_t));
544 if (target_end == target)
547 /* No leading slash??? */
548 if (target[0] != L'\\')
552 if ((target_end - target) >= 2 &&
553 target[0] == L'\\' && target[1] == L'\\')
556 attr.Length = sizeof(attr);
557 attr.RootDirectory = NULL;
558 attr.ObjectName = &name;
560 attr.SecurityDescriptor = NULL;
561 attr.SecurityQualityOfService = NULL;
563 name.Buffer = (wchar_t *)target;
568 const wchar_t *orig_p = p;
570 /* Skip non-backslashes */
571 while (p != target_end && *p != L'\\')
574 /* Skip backslashes */
575 while (p != target_end && *p == L'\\')
578 /* Append path component */
579 name.Length += (p - orig_p) * sizeof(wchar_t);
580 name.MaximumLength = name.Length;
582 /* Try opening the file */
583 status = (*func_NtOpenFile) (&h,
584 FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
587 FILE_SHARE_VALID_FLAGS,
588 FILE_OPEN_FOR_BACKUP_INTENT);
590 if (NT_SUCCESS(status)) {
591 /* Reset root directory */
592 if (attr.RootDirectory)
593 (*func_NtClose)(attr.RootDirectory);
594 attr.RootDirectory = h;
595 name.Buffer = (wchar_t *)p;
598 if (file_has_ino_and_dev(h, capture_root_ino,
600 goto out_close_root_dir;
602 } while (p != target_end);
607 if (attr.RootDirectory)
608 (*func_NtClose)(attr.RootDirectory);
613 winnt_rpfix_progress(struct add_image_params *params, const wchar_t *path,
614 const struct reparse_data *rpdata, int scan_status)
616 size_t print_name_nchars = rpdata->print_name_nbytes / sizeof(wchar_t);
617 wchar_t print_name0[print_name_nchars + 1];
619 wmemcpy(print_name0, rpdata->print_name, print_name_nchars);
620 print_name0[print_name_nchars] = L'\0';
622 params->progress.scan.cur_path = printable_path(path);
623 params->progress.scan.symlink_target = print_name0;
624 return do_capture_progress(params, scan_status, NULL);
628 winnt_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
629 u64 capture_root_ino, u64 capture_root_dev,
630 const wchar_t *path, struct add_image_params *params)
632 struct reparse_data rpdata;
633 const wchar_t *rel_target;
636 if (parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata)) {
637 /* Couldn't even understand the reparse data. Don't try the
643 * Don't do reparse point fixups on relative symbolic links.
645 * On Windows, a relative symbolic link is supposed to be identifiable
646 * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
647 * SYMBOLIC_LINK_RELATIVE. We will use this information, although this
648 * may not always do what the user expects, since drive-relative
649 * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
650 * set, in addition to truely relative symbolic links such as "Users" or
651 * "Users\Public". However, WIMGAPI (as of Windows 8.1) has this same
654 * Otherwise, as far as I can tell, the targets of symbolic links that
655 * are NOT relative, as well as junctions (note: a mountpoint is the
656 * sames thing as a junction), must be NT namespace paths, for example:
658 * - \??\e:\Users\Public
659 * - \DosDevices\e:\Users\Public
660 * - \Device\HardDiskVolume4\Users\Public
661 * - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
662 * - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
664 if (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
665 (rpdata.rpflags & SYMBOLIC_LINK_RELATIVE))
668 rel_target = winnt_get_root_relative_target(rpdata.substitute_name,
669 rpdata.substitute_name_nbytes,
673 /* Target points outside of the tree being captured. Don't
675 ret = winnt_rpfix_progress(params, path, &rpdata,
676 WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK);
682 if (rel_target == rpdata.substitute_name) {
683 /* Weird target --- keep the reparse point and don't mess with
688 /* We have an absolute target pointing within the directory being
689 * captured. @rel_target is the suffix of the link target that is the
690 * part relative to the directory being captured.
692 * We will cut off the prefix before this part (which is the path to the
693 * directory being captured) and add a dummy prefix. Since the process
694 * will need to be reversed when applying the image, it shouldn't matter
695 * what exactly the prefix is, as long as it looks like an absolute
700 size_t rel_target_nbytes =
701 rpdata.substitute_name_nbytes - ((const u8 *)rel_target -
702 (const u8 *)rpdata.substitute_name);
703 size_t rel_target_nchars = rel_target_nbytes / sizeof(wchar_t);
705 wchar_t tmp[rel_target_nchars + 7];
707 wmemcpy(tmp, L"\\??\\X:\\", 7);
708 wmemcpy(tmp + 7, rel_target, rel_target_nchars);
710 rpdata.substitute_name = tmp;
711 rpdata.substitute_name_nbytes = rel_target_nbytes + (7 * sizeof(wchar_t));
712 rpdata.print_name = tmp + 4;
713 rpdata.print_name_nbytes = rel_target_nbytes + (3 * sizeof(wchar_t));
715 if (make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p))
718 ret = winnt_rpfix_progress(params, path, &rpdata,
719 WIMLIB_SCAN_DENTRY_FIXED_SYMLINK);
726 * Loads the reparse point data from a reparse point into memory, optionally
727 * fixing the targets of absolute symbolic links and junction points to be
728 * relative to the root of capture.
731 * Open handle to the reparse point file.
733 * Path to the reparse point file.
735 * Capture parameters. add_flags, capture_root_ino, capture_root_dev,
736 * progfunc, progctx, and progress are used.
738 * Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which the
739 * reparse point buffer will be loaded.
741 * On success, the length of the reparse point buffer in bytes is written
744 * On success, returns a negative `enum rp_status' value.
745 * On failure, returns a positive error code.
748 winnt_get_reparse_data(HANDLE h, const wchar_t *path,
749 struct add_image_params *params,
750 u8 *rpbuf, u16 *rpbuflen_ret)
752 DWORD bytes_returned;
757 if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
758 NULL, 0, rpbuf, REPARSE_POINT_MAX_SIZE,
759 &bytes_returned, NULL))
761 set_errno_from_GetLastError();
762 return WIMLIB_ERR_READ;
765 if (unlikely(bytes_returned < 8)) {
767 return WIMLIB_ERR_INVALID_REPARSE_DATA;
770 rpbuflen = bytes_returned;
771 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
773 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
774 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
775 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
777 ret = winnt_try_rpfix(rpbuf, &rpbuflen,
778 params->capture_root_ino,
779 params->capture_root_dev,
782 *rpbuflen_ret = rpbuflen;
787 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
790 *(u64*)_size_ret += len;
791 return ERROR_SUCCESS;
795 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
801 err = OpenEncryptedFileRaw(path, 0, &file_ctx);
802 if (err != ERROR_SUCCESS) {
803 set_errno_from_win32_error(err);
804 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
805 "for raw read", printable_path(path));
806 return WIMLIB_ERR_OPEN;
809 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
811 if (err != ERROR_SUCCESS) {
812 set_errno_from_win32_error(err);
813 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
814 "\"%ls\"", printable_path(path));
815 ret = WIMLIB_ERR_READ;
819 CloseEncryptedFileRaw(file_ctx);
824 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
825 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
827 const wchar_t *sep, *type, *end;
829 /* The stream name should be returned as :NAME:TYPE */
830 if (raw_stream_name_nchars < 1)
832 if (raw_stream_name[0] != L':')
836 raw_stream_name_nchars--;
838 end = raw_stream_name + raw_stream_name_nchars;
840 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
848 if (wmemcmp(type, L"$DATA", 5))
851 *stream_name_ret = raw_stream_name;
852 *stream_name_nchars_ret = sep - raw_stream_name;
857 build_stream_path(const wchar_t *path, size_t path_nchars,
858 const wchar_t *stream_name, size_t stream_name_nchars)
860 size_t stream_path_nchars;
861 wchar_t *stream_path;
864 stream_path_nchars = path_nchars;
865 if (stream_name_nchars)
866 stream_path_nchars += 1 + stream_name_nchars;
868 stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
870 p = wmempcpy(stream_path, path, path_nchars);
871 if (stream_name_nchars) {
873 p = wmempcpy(p, stream_name, stream_name_nchars);
881 winnt_scan_stream(const wchar_t *path, size_t path_nchars,
882 const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
884 struct wim_inode *inode, struct list_head *unhashed_streams)
886 const wchar_t *stream_name;
887 size_t stream_name_nchars;
888 struct wim_ads_entry *ads_entry;
889 wchar_t *stream_path;
890 struct wim_lookup_table_entry *lte;
893 /* Given the raw stream name (which is something like
894 * :streamname:$DATA), extract just the stream name part.
895 * Ignore any non-$DATA streams. */
896 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
897 &stream_name, &stream_name_nchars))
900 /* If this is a named stream, allocate an ADS entry for it. */
901 if (stream_name_nchars) {
902 ads_entry = inode_add_ads_utf16le(inode, stream_name,
906 return WIMLIB_ERR_NOMEM;
907 } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
908 /* Ignore unnamed data stream of reparse point */
914 /* If the stream is empty, no lookup table entry is needed. */
915 if (stream_size == 0)
918 /* Build the path to the stream. For unnamed streams, this is simply
919 * the path to the file. For named streams, this is the path to the
920 * file, followed by a colon, followed by the stream name. */
921 stream_path = build_stream_path(path, path_nchars,
922 stream_name, stream_name_nchars);
924 return WIMLIB_ERR_NOMEM;
926 /* Set up the lookup table entry for the stream. */
927 lte = new_lookup_table_entry();
930 return WIMLIB_ERR_NOMEM;
932 lte->file_on_disk = stream_path;
933 lte->resource_location = RESOURCE_IN_WINNT_FILE_ON_DISK;
934 lte->size = stream_size;
935 if ((inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) && !ads_entry) {
936 /* Special case for encrypted file. */
938 /* OpenEncryptedFileRaw() expects Win32 name, not NT name.
939 * Change \??\ into \\?\ */
940 lte->file_on_disk[1] = L'\\';
941 wimlib_assert(!wmemcmp(lte->file_on_disk, L"\\\\?\\", 4));
946 ret = win32_get_encrypted_file_size(lte->file_on_disk,
949 free_lookup_table_entry(lte);
952 lte->size = encrypted_size;
953 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
957 stream_id = ads_entry->stream_id;
958 ads_entry->lte = lte;
963 lte->file_inode = inode;
964 add_unhashed_stream(lte, inode, stream_id, unhashed_streams);
969 * Load information about the streams of an open file into a WIM inode.
971 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
972 * and FindNextStream(). This is done for two reasons:
974 * - FindFirstStream() opens its own handle to the file or directory and
975 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
976 * causing access denied errors on certain files (even when running as the
978 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
979 * and later, whereas the stream support in NtQueryInformationFile() was
980 * already present in Windows XP.
983 winnt_scan_streams(HANDLE *hFile_p, const wchar_t *path, size_t path_nchars,
984 struct wim_inode *inode, struct list_head *unhashed_streams,
985 u64 file_size, u32 vol_flags)
988 u8 _buf[1024] _aligned_attribute(8);
991 IO_STATUS_BLOCK iosb;
993 const FILE_STREAM_INFORMATION *info;
996 bufsize = sizeof(_buf);
998 if (!(vol_flags & FILE_NAMED_STREAMS))
1001 /* Get a buffer containing the stream information. */
1002 while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(*hFile_p,
1006 FileStreamInformation)))
1010 case STATUS_BUFFER_OVERFLOW:
1016 newbuf = MALLOC(bufsize);
1018 newbuf = REALLOC(buf, bufsize);
1020 ret = WIMLIB_ERR_NOMEM;
1026 case STATUS_NOT_IMPLEMENTED:
1027 case STATUS_NOT_SUPPORTED:
1028 case STATUS_INVALID_INFO_CLASS:
1031 set_errno_from_nt_status(status);
1032 ERROR_WITH_ERRNO("\"%ls\": Failed to query stream "
1033 "information (status=0x%08"PRIx32")",
1034 printable_path(path), (u32)status);
1035 ret = WIMLIB_ERR_READ;
1040 if (iosb.Information == 0) {
1041 /* No stream information. */
1046 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1047 /* OpenEncryptedFileRaw() seems to fail with
1048 * ERROR_SHARING_VIOLATION if there are any handles opened to
1050 (*func_NtClose)(*hFile_p);
1051 *hFile_p = INVALID_HANDLE_VALUE;
1054 /* Parse one or more stream information structures. */
1055 info = (const FILE_STREAM_INFORMATION *)buf;
1057 /* Load the stream information. */
1058 ret = winnt_scan_stream(path, path_nchars,
1060 info->StreamNameLength / 2,
1061 info->StreamSize.QuadPart,
1062 inode, unhashed_streams);
1066 if (info->NextEntryOffset == 0) {
1067 /* No more stream information. */
1070 /* Advance to next stream information. */
1071 info = (const FILE_STREAM_INFORMATION *)
1072 ((const u8 *)info + info->NextEntryOffset);
1078 /* The volume does not support named streams. Only capture the unnamed
1080 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1081 FILE_ATTRIBUTE_REPARSE_POINT))
1087 ret = winnt_scan_stream(path, path_nchars, L"::$DATA", 7,
1088 file_size, inode, unhashed_streams);
1090 /* Free buffer if allocated on heap. */
1091 if (unlikely(buf != _buf))
1097 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1100 size_t full_path_nchars,
1101 const wchar_t *filename,
1102 size_t filename_nchars,
1103 struct add_image_params *params,
1104 struct winnt_scan_stats *stats,
1107 struct wim_dentry *root = NULL;
1108 struct wim_inode *inode = NULL;
1109 HANDLE h = INVALID_HANDLE_VALUE;
1112 FILE_ALL_INFORMATION file_info;
1117 ret = try_exclude(full_path, full_path_nchars, params);
1118 if (ret < 0) /* Excluded? */
1120 if (ret > 0) /* Error? */
1123 /* Open the file. */
1124 status = winnt_openat(cur_dir,
1125 (cur_dir ? filename : full_path),
1126 (cur_dir ? filename_nchars : full_path_nchars),
1128 FILE_READ_ATTRIBUTES |
1130 ACCESS_SYSTEM_SECURITY |
1133 if (unlikely(!NT_SUCCESS(status))) {
1134 if (status == STATUS_DELETE_PENDING) {
1135 WARNING("\"%ls\": Deletion pending; skipping file",
1136 printable_path(full_path));
1139 set_errno_from_nt_status(status);
1140 ERROR_WITH_ERRNO("\"%ls\": Can't open file "
1141 "(status=0x%08"PRIx32")",
1142 printable_path(full_path), (u32)status);
1143 if (status == STATUS_FVE_LOCKED_VOLUME)
1144 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1146 ret = WIMLIB_ERR_OPEN;
1148 /* XXX: Provide option to exclude files that fail with
1149 * STATUS_SHARING_VIOLATION? */
1153 /* Get information about the file. */
1155 IO_STATUS_BLOCK iosb;
1157 status = (*func_NtQueryInformationFile)(h, &iosb,
1160 FileAllInformation);
1162 if (unlikely(!NT_SUCCESS(status) &&
1163 status != STATUS_BUFFER_OVERFLOW))
1165 set_errno_from_nt_status(status);
1166 ERROR_WITH_ERRNO("\"%ls\": Can't get file information "
1167 "(status=0x%08"PRIx32")",
1168 printable_path(full_path), (u32)status);
1169 ret = WIMLIB_ERR_STAT;
1174 if (unlikely(!cur_dir)) {
1176 /* Root of tree being captured; get volume information. */
1178 FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1179 FILE_FS_VOLUME_INFORMATION vol_info;
1180 IO_STATUS_BLOCK iosb;
1182 /* Get volume flags */
1183 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1186 FileFsAttributeInformation);
1187 if (likely((NT_SUCCESS(status) ||
1188 (status == STATUS_BUFFER_OVERFLOW)) &&
1189 (iosb.Information >=
1190 offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1191 FileSystemAttributes) +
1192 sizeof(attr_info.FileSystemAttributes))))
1194 vol_flags = attr_info.FileSystemAttributes;
1196 set_errno_from_nt_status(status);
1197 WARNING_WITH_ERRNO("\"%ls\": Can't get volume attributes "
1198 "(status=0x%08"PRIx32")",
1199 printable_path(full_path),
1204 /* Set inode number of root directory */
1205 params->capture_root_ino =
1206 file_info.InternalInformation.IndexNumber.QuadPart;
1208 /* Get volume ID. */
1209 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1212 FileFsVolumeInformation);
1213 if (likely((NT_SUCCESS(status) ||
1214 (status == STATUS_BUFFER_OVERFLOW)) &&
1215 (iosb.Information >=
1216 offsetof(FILE_FS_VOLUME_INFORMATION,
1217 VolumeSerialNumber) +
1218 sizeof(vol_info.VolumeSerialNumber))))
1220 params->capture_root_dev = vol_info.VolumeSerialNumber;
1222 set_errno_from_nt_status(status);
1223 WARNING_WITH_ERRNO("\"%ls\": Can't get volume ID "
1224 "(status=0x%08"PRIx32")",
1225 printable_path(full_path),
1227 params->capture_root_dev = 0;
1231 /* If this is a reparse point, read the reparse data. */
1232 if (unlikely(file_info.BasicInformation.FileAttributes &
1233 FILE_ATTRIBUTE_REPARSE_POINT))
1235 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1236 ret = winnt_get_reparse_data(h, full_path, params,
1246 ERROR_WITH_ERRNO("\"%ls\": Can't get reparse data",
1247 printable_path(full_path));
1252 /* Create a WIM dentry with an associated inode, which may be shared.
1254 * However, we need to explicitly check for directories and files with
1255 * only 1 link and refuse to hard link them. This is because Windows
1256 * has a bug where it can return duplicate File IDs for files and
1257 * directories on the FAT filesystem.
1259 * Since we don't follow mount points on Windows, we don't need to query
1260 * the volume ID per-file. Just once, for the root, is enough. But we
1261 * can't simply pass 0, because then there could be inode collisions
1262 * among multiple calls to win32_build_dentry_tree() that are scanning
1263 * files on different volumes. */
1264 ret = inode_table_new_dentry(params->inode_table,
1266 file_info.InternalInformation.IndexNumber.QuadPart,
1267 params->capture_root_dev,
1268 (file_info.StandardInformation.NumberOfLinks <= 1 ||
1269 (file_info.BasicInformation.FileAttributes &
1270 FILE_ATTRIBUTE_DIRECTORY)),
1275 /* Get the short (DOS) name of the file. */
1276 status = winnt_get_short_name(h, root);
1278 /* If we can't read the short filename for any reason other than
1279 * out-of-memory, just ignore the error and assume the file has no short
1280 * name. This shouldn't be an issue, since the short names are
1281 * essentially obsolete anyway. */
1282 if (unlikely(status == STATUS_NO_MEMORY)) {
1283 ret = WIMLIB_ERR_NOMEM;
1287 inode = root->d_inode;
1289 if (inode->i_nlink > 1) {
1290 /* Shared inode (hard link); skip reading per-inode information.
1295 inode->i_attributes = file_info.BasicInformation.FileAttributes;
1296 inode->i_creation_time = file_info.BasicInformation.CreationTime.QuadPart;
1297 inode->i_last_write_time = file_info.BasicInformation.LastWriteTime.QuadPart;
1298 inode->i_last_access_time = file_info.BasicInformation.LastAccessTime.QuadPart;
1299 inode->i_resolved = 1;
1301 /* Get the file's security descriptor, unless we are capturing in
1302 * NO_ACLS mode or the volume does not support security descriptors. */
1303 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1304 && (vol_flags & FILE_PERSISTENT_ACLS))
1306 status = winnt_get_security_descriptor(h, inode,
1307 params->sd_set, stats,
1309 if (!NT_SUCCESS(status)) {
1310 set_errno_from_nt_status(status);
1311 ERROR_WITH_ERRNO("\"%ls\": Can't read security "
1312 "descriptor (status=0x%08"PRIx32")",
1313 printable_path(full_path),
1315 ret = WIMLIB_ERR_STAT;
1320 /* Load information about the unnamed data stream and any named data
1322 ret = winnt_scan_streams(&h,
1326 params->unhashed_streams,
1327 file_info.StandardInformation.EndOfFile.QuadPart,
1332 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1334 /* Reparse point: set the reparse data (already read). */
1336 inode->i_not_rpfixed = not_rpfixed;
1337 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1338 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1339 params->lookup_table);
1342 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1344 /* Directory: recurse to children. */
1346 if (unlikely(h == INVALID_HANDLE_VALUE)) {
1347 /* Re-open handle that was closed to read raw encrypted
1349 status = winnt_openat(cur_dir,
1351 filename : full_path),
1353 filename_nchars : full_path_nchars),
1354 FILE_LIST_DIRECTORY | SYNCHRONIZE,
1356 if (!NT_SUCCESS(status)) {
1357 set_errno_from_nt_status(status);
1358 ERROR_WITH_ERRNO("\"%ls\": Can't re-open file "
1359 "(status=0x%08"PRIx32")",
1360 printable_path(full_path),
1362 ret = WIMLIB_ERR_OPEN;
1366 ret = winnt_recurse_directory(h,
1378 params->progress.scan.cur_path = printable_path(full_path);
1380 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1382 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1384 if (likely(h != INVALID_HANDLE_VALUE))
1386 if (likely(ret == 0))
1389 free_dentry_tree(root, params->lookup_table);
1394 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_stats *stats)
1396 if (likely(stats->num_get_sacl_priv_notheld == 0 &&
1397 stats->num_get_sd_access_denied == 0))
1400 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1401 if (stats->num_get_sacl_priv_notheld != 0) {
1402 WARNING("- Could not capture SACL (System Access Control List)\n"
1403 " on %lu files or directories.",
1404 stats->num_get_sacl_priv_notheld);
1406 if (stats->num_get_sd_access_denied != 0) {
1407 WARNING("- Could not capture security descriptor at all\n"
1408 " on %lu files or directories.",
1409 stats->num_get_sd_access_denied);
1411 WARNING("To fully capture all security descriptors, run the program\n"
1412 " with Administrator rights.");
1415 #define WINDOWS_NT_MAX_PATH 32768
1417 /* Win32 version of capturing a directory tree. */
1419 win32_build_dentry_tree(struct wim_dentry **root_ret,
1420 const wchar_t *root_disk_path,
1421 struct add_image_params *params)
1425 UNICODE_STRING ntpath;
1426 struct winnt_scan_stats stats;
1427 size_t ntpath_nchars;
1429 /* WARNING: There is no check for overflow later when this buffer is
1430 * being used! But it's as long as the maximum path length understood
1431 * by Windows NT (which is NOT the same as MAX_PATH). */
1432 path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1434 return WIMLIB_ERR_NOMEM;
1436 ret = win32_path_to_nt_path(root_disk_path, &ntpath);
1440 if (ntpath.Length < 4 * sizeof(wchar_t) ||
1441 ntpath.Length > WINDOWS_NT_MAX_PATH * sizeof(wchar_t) ||
1442 wmemcmp(ntpath.Buffer, L"\\??\\", 4))
1444 ERROR("\"%ls\": unrecognized path format", root_disk_path);
1445 ret = WIMLIB_ERR_INVALID_PARAM;
1447 ntpath_nchars = ntpath.Length / sizeof(wchar_t);
1448 wmemcpy(path, ntpath.Buffer, ntpath_nchars);
1449 path[ntpath_nchars] = L'\0';
1451 params->capture_root_nchars = ntpath_nchars;
1452 if (path[ntpath_nchars - 1] == L'\\')
1453 params->capture_root_nchars--;
1456 HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
1460 memset(&stats, 0, sizeof(stats));
1462 ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
1463 path, ntpath_nchars,
1464 L"", 0, params, &stats, 0);
1468 winnt_do_scan_warnings(root_disk_path, &stats);
1472 #endif /* __WIN32__ */