2 * win32_capture.c - Windows-specific code for capturing files into a WIM image.
4 * This now uses the native Windows NT API a lot and not just Win32.
8 * Copyright (C) 2013, 2014 Eric Biggers
10 * This file is part of wimlib, a library for working with WIM files.
12 * wimlib is free software; you can redistribute it and/or modify it under the
13 * terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 3 of the License, or (at your option)
17 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 * A PARTICULAR PURPOSE. See the GNU General Public License for more
22 * You should have received a copy of the GNU General Public License
23 * along with wimlib; if not, see http://www.gnu.org/licenses/.
32 #include "wimlib/win32_common.h"
34 #include "wimlib/capture.h"
35 #include "wimlib/dentry.h"
36 #include "wimlib/encoding.h"
37 #include "wimlib/endianness.h"
38 #include "wimlib/error.h"
39 #include "wimlib/lookup_table.h"
40 #include "wimlib/paths.h"
41 #include "wimlib/reparse.h"
45 struct winnt_scan_stats {
46 unsigned long num_get_sd_access_denied;
47 unsigned long num_get_sacl_priv_notheld;
48 unsigned long num_long_path_warnings;
51 static inline const wchar_t *
52 printable_path(const wchar_t *full_path)
54 /* Skip over \\?\ or \??\ */
59 * If cur_dir is not NULL, open an existing file relative to the already-open
62 * Otherwise, open the file specified by @path, which must be a Windows NT
66 winnt_openat(HANDLE cur_dir, const wchar_t *path, size_t path_nchars,
67 ACCESS_MASK perms, HANDLE *h_ret)
70 OBJECT_ATTRIBUTES attr;
74 name.Length = path_nchars * sizeof(wchar_t);
75 name.MaximumLength = name.Length + sizeof(wchar_t);
76 name.Buffer = (wchar_t *)path;
78 attr.Length = sizeof(attr);
79 attr.RootDirectory = cur_dir;
80 attr.ObjectName = &name;
82 attr.SecurityDescriptor = NULL;
83 attr.SecurityQualityOfService = NULL;
86 status = (*func_NtOpenFile)(h_ret, perms, &attr, &iosb,
87 FILE_SHARE_VALID_FLAGS,
88 FILE_OPEN_REPARSE_POINT |
89 FILE_OPEN_FOR_BACKUP_INTENT |
90 FILE_SYNCHRONOUS_IO_NONALERT |
91 FILE_SEQUENTIAL_ONLY);
92 if (!NT_SUCCESS(status)) {
93 /* Try requesting fewer permissions */
94 if (status == STATUS_ACCESS_DENIED ||
95 status == STATUS_PRIVILEGE_NOT_HELD) {
96 if (perms & ACCESS_SYSTEM_SECURITY) {
97 perms &= ~ACCESS_SYSTEM_SECURITY;
100 if (perms & READ_CONTROL) {
101 perms &= ~READ_CONTROL;
109 /* Read the first @size bytes from the file, or named data stream of a file,
110 * from which the stream entry @lte was created. */
112 read_winnt_file_prefix(const struct wim_lookup_table_entry *lte, u64 size,
113 consume_data_callback_t cb, void *cb_ctx)
122 /* This is an NT namespace path. */
123 path = lte->file_on_disk;
125 status = winnt_openat(NULL, path, wcslen(path),
126 FILE_READ_DATA | SYNCHRONIZE, &h);
127 if (!NT_SUCCESS(status)) {
128 set_errno_from_nt_status(status);
129 ERROR_WITH_ERRNO("\"%ls\": Can't open for reading "
130 "(status=0x%08"PRIx32")",
131 printable_path(path), (u32)status);
132 return WIMLIB_ERR_OPEN;
136 bytes_remaining = size;
137 while (bytes_remaining) {
138 IO_STATUS_BLOCK iosb;
142 count = min(sizeof(buf), bytes_remaining);
144 status = (*func_NtReadFile)(h, NULL, NULL, NULL,
145 &iosb, buf, count, NULL, NULL);
146 if (!NT_SUCCESS(status)) {
147 set_errno_from_nt_status(status);
148 ERROR_WITH_ERRNO("\"%ls\": Error reading data "
149 "(status=0x%08"PRIx32")",
150 printable_path(path), (u32)status);
151 ret = WIMLIB_ERR_READ;
155 bytes_read = iosb.Information;
157 bytes_remaining -= bytes_read;
158 ret = (*cb)(buf, bytes_read, cb_ctx);
166 struct win32_encrypted_read_ctx {
167 consume_data_callback_t read_prefix_cb;
168 void *read_prefix_ctx;
174 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
176 struct win32_encrypted_read_ctx *ctx = _ctx;
178 size_t bytes_to_consume = min(len, ctx->bytes_remaining);
180 if (bytes_to_consume == 0)
181 return ERROR_SUCCESS;
183 ret = (*ctx->read_prefix_cb)(data, bytes_to_consume, ctx->read_prefix_ctx);
185 ctx->wimlib_err_code = ret;
186 /* Shouldn't matter what error code is returned here, as long as
187 * it isn't ERROR_SUCCESS. */
188 return ERROR_READ_FAULT;
190 ctx->bytes_remaining -= bytes_to_consume;
191 return ERROR_SUCCESS;
195 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
197 consume_data_callback_t cb, void *cb_ctx)
199 struct win32_encrypted_read_ctx export_ctx;
204 export_ctx.read_prefix_cb = cb;
205 export_ctx.read_prefix_ctx = cb_ctx;
206 export_ctx.wimlib_err_code = 0;
207 export_ctx.bytes_remaining = size;
209 err = OpenEncryptedFileRaw(lte->file_on_disk, 0, &file_ctx);
210 if (err != ERROR_SUCCESS) {
211 set_errno_from_win32_error(err);
212 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
214 printable_path(lte->file_on_disk));
215 return WIMLIB_ERR_OPEN;
217 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
218 &export_ctx, file_ctx);
219 if (err != ERROR_SUCCESS) {
220 set_errno_from_win32_error(err);
221 ERROR_WITH_ERRNO("Failed to read encrypted file \"%ls\"",
222 printable_path(lte->file_on_disk));
223 ret = export_ctx.wimlib_err_code;
225 ret = WIMLIB_ERR_READ;
226 } else if (export_ctx.bytes_remaining != 0) {
227 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
228 "encryted file \"%ls\"",
229 size - export_ctx.bytes_remaining, size,
230 printable_path(lte->file_on_disk));
231 ret = WIMLIB_ERR_READ;
235 CloseEncryptedFileRaw(file_ctx);
240 * Load the short name of a file into a WIM dentry.
243 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
245 /* It's not any harder to just make the NtQueryInformationFile() system
246 * call ourselves, and it saves a dumb call to FindFirstFile() which of
247 * course has to create its own handle. */
249 IO_STATUS_BLOCK iosb;
250 u8 buf[128] _aligned_attribute(8);
251 const FILE_NAME_INFORMATION *info;
253 status = (*func_NtQueryInformationFile)(h, &iosb, buf, sizeof(buf),
254 FileAlternateNameInformation);
255 info = (const FILE_NAME_INFORMATION *)buf;
256 if (NT_SUCCESS(status) && info->FileNameLength != 0) {
257 dentry->short_name = utf16le_dupz(info->FileName,
258 info->FileNameLength);
259 if (!dentry->short_name)
260 return STATUS_NO_MEMORY;
261 dentry->short_name_nbytes = info->FileNameLength;
267 * Load the security descriptor of a file into the corresponding inode, and the
268 * WIM image's security descriptor set.
271 winnt_get_security_descriptor(HANDLE h, struct wim_inode *inode,
272 struct wim_sd_set *sd_set,
273 struct winnt_scan_stats *stats, int add_flags)
275 SECURITY_INFORMATION requestedInformation;
276 u8 _buf[4096] _aligned_attribute(8);
282 requestedInformation = DACL_SECURITY_INFORMATION |
283 SACL_SECURITY_INFORMATION |
284 OWNER_SECURITY_INFORMATION |
285 GROUP_SECURITY_INFORMATION;
287 bufsize = sizeof(_buf);
290 * We need the file's security descriptor in
291 * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
292 * opened with as many relevant permissions as possible. At this point,
293 * on Windows there are a number of options for reading a file's
294 * security descriptor:
296 * GetFileSecurity(): This takes in a path and returns the
297 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle,
298 * not ours, and the handle created internally doesn't specify
299 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied
300 * errors on some files and directories, even when running as the
303 * GetSecurityInfo(): This takes in a handle and returns the security
304 * descriptor split into a bunch of different parts. This should work,
305 * but it's dumb because we have to put the security descriptor back
308 * BackupRead(): This can read the security descriptor, but this is a
309 * difficult-to-use API, probably only works as the Administrator, and
310 * the format of the returned data is not well documented.
312 * NtQuerySecurityObject(): This is exactly what we need, as it takes
313 * in a handle and returns the security descriptor in
314 * SECURITY_DESCRIPTOR_RELATIVE format. Only problem is that it's a
315 * ntdll function and therefore not officially part of the Win32 API.
318 while (!(NT_SUCCESS(status = (*func_NtQuerySecurityObject)(h,
319 requestedInformation,
320 (PSECURITY_DESCRIPTOR)buf,
325 case STATUS_BUFFER_TOO_SMALL:
326 wimlib_assert(buf == _buf);
327 buf = MALLOC(len_needed);
329 return STATUS_NO_MEMORY;
330 bufsize = len_needed;
332 case STATUS_PRIVILEGE_NOT_HELD:
333 case STATUS_ACCESS_DENIED:
334 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
336 /* Permission denied in STRICT_ACLS mode, or
340 if (requestedInformation & SACL_SECURITY_INFORMATION) {
341 /* Try again without the SACL. */
342 stats->num_get_sacl_priv_notheld++;
343 requestedInformation &= ~SACL_SECURITY_INFORMATION;
346 /* Fake success (useful when capturing as
347 * non-Administrator). */
348 stats->num_get_sd_access_denied++;
349 status = STATUS_SUCCESS;
354 /* Add the security descriptor to the WIM image, and save its ID in
356 inode->i_security_id = sd_set_add_sd(sd_set, buf, len_needed);
357 if (unlikely(inode->i_security_id < 0))
358 status = STATUS_NO_MEMORY;
360 if (unlikely(buf != _buf))
366 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
369 size_t full_path_nchars,
370 const wchar_t *filename,
371 size_t filename_nchars,
372 struct add_image_params *params,
373 struct winnt_scan_stats *stats,
377 winnt_recurse_directory(HANDLE h,
379 size_t full_path_nchars,
380 struct wim_dentry *parent,
381 struct add_image_params *params,
382 struct winnt_scan_stats *stats,
386 const size_t bufsize = 8192;
387 IO_STATUS_BLOCK iosb;
391 buf = MALLOC(bufsize);
393 return WIMLIB_ERR_NOMEM;
395 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
396 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
398 while (NT_SUCCESS(status = (*func_NtQueryDirectoryFile)(h, NULL, NULL, NULL,
400 FileNamesInformation,
401 FALSE, NULL, FALSE)))
403 const FILE_NAMES_INFORMATION *info = buf;
405 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
406 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
407 info->FileName[1] == L'.'))
410 struct wim_dentry *child;
412 p = full_path + full_path_nchars;
414 p = wmempcpy(p, info->FileName,
415 info->FileNameLength / 2);
418 ret = winnt_build_dentry_tree_recursive(
423 full_path + full_path_nchars + 1,
424 info->FileNameLength / 2,
429 full_path[full_path_nchars] = L'\0';
434 dentry_add_child(parent, child);
436 if (info->NextEntryOffset == 0)
438 info = (const FILE_NAMES_INFORMATION *)
439 ((const u8 *)info + info->NextEntryOffset);
443 if (unlikely(status != STATUS_NO_MORE_FILES)) {
444 set_errno_from_nt_status(status);
445 ERROR_WITH_ERRNO("\"%ls\": Can't read directory "
446 "(status=0x%08"PRIx32")",
447 printable_path(full_path), (u32)status);
448 ret = WIMLIB_ERR_READ;
455 /* Reparse point fixup status code */
457 /* Reparse point should be excluded from capture */
460 /* Reparse point will be captured literally (no fixup) */
463 /* Reparse point will be captured with fixup */
468 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
471 IO_STATUS_BLOCK iosb;
472 FILE_INTERNAL_INFORMATION int_info;
473 FILE_FS_VOLUME_INFORMATION vol_info;
475 status = (*func_NtQueryInformationFile)(h, &iosb,
476 &int_info, sizeof(int_info),
477 FileInternalInformation);
478 if (!NT_SUCCESS(status))
481 if (int_info.IndexNumber.QuadPart != ino)
484 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
485 &vol_info, sizeof(vol_info),
486 FileFsVolumeInformation);
487 if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
490 if (iosb.Information <
491 offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
492 sizeof(vol_info.VolumeSerialNumber))
495 return (vol_info.VolumeSerialNumber == dev);
499 * Given an (expected) NT namespace symbolic link or junction target @target of
500 * length @target_nbytes, determine if a prefix of the target points to a file
501 * identified by @capture_root_ino and @capture_root_dev.
503 * If yes, return a pointer to the portion of the link following this prefix.
505 * If no, return NULL.
507 * If the link target does not appear to be a valid NT namespace path, return
510 static const wchar_t *
511 winnt_get_root_relative_target(const wchar_t *target, size_t target_nbytes,
512 u64 capture_root_ino, u64 capture_root_dev)
515 OBJECT_ATTRIBUTES attr;
516 IO_STATUS_BLOCK iosb;
518 const wchar_t *target_end;
521 target_end = target + (target_nbytes / sizeof(wchar_t));
524 if (target_end == target)
527 /* No leading slash??? */
528 if (target[0] != L'\\')
532 if ((target_end - target) >= 2 &&
533 target[0] == L'\\' && target[1] == L'\\')
536 attr.Length = sizeof(attr);
537 attr.RootDirectory = NULL;
538 attr.ObjectName = &name;
540 attr.SecurityDescriptor = NULL;
541 attr.SecurityQualityOfService = NULL;
543 name.Buffer = (wchar_t *)target;
548 const wchar_t *orig_p = p;
550 /* Skip non-backslashes */
551 while (p != target_end && *p != L'\\')
554 /* Skip backslashes */
555 while (p != target_end && *p == L'\\')
558 /* Append path component */
559 name.Length += (p - orig_p) * sizeof(wchar_t);
560 name.MaximumLength = name.Length;
562 /* Try opening the file */
563 status = (*func_NtOpenFile) (&h,
564 FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
567 FILE_SHARE_VALID_FLAGS,
568 FILE_OPEN_FOR_BACKUP_INTENT);
570 if (NT_SUCCESS(status)) {
571 /* Reset root directory */
572 if (attr.RootDirectory)
573 (*func_NtClose)(attr.RootDirectory);
574 attr.RootDirectory = h;
575 name.Buffer = (wchar_t *)p;
578 if (file_has_ino_and_dev(h, capture_root_ino,
580 goto out_close_root_dir;
582 } while (p != target_end);
587 if (attr.RootDirectory)
588 (*func_NtClose)(attr.RootDirectory);
593 winnt_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
594 u64 capture_root_ino, u64 capture_root_dev,
595 const wchar_t *path, struct add_image_params *params)
597 struct reparse_data rpdata;
598 const wchar_t *rel_target;
600 if (parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata)) {
601 /* Couldn't even understand the reparse data. Don't try the
607 * Don't do reparse point fixups on relative symbolic links.
609 * On Windows, a relative symbolic link is supposed to be identifiable
610 * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
611 * SYMBOLIC_LINK_RELATIVE. We will use this information, although this
612 * may not always do what the user expects, since drive-relative
613 * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
614 * set, in addition to truely relative symbolic links such as "Users" or
615 * "Users\Public". However, WIMGAPI (as of Windows 8.1) has this same
618 * Otherwise, as far as I can tell, the targets of symbolic links that
619 * are NOT relative, as well as junctions (note: a mountpoint is the
620 * sames thing as a junction), must be NT namespace paths, for example:
622 * - \??\e:\Users\Public
623 * - \DosDevices\e:\Users\Public
624 * - \Device\HardDiskVolume4\Users\Public
625 * - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
626 * - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
628 if (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
629 (rpdata.rpflags & SYMBOLIC_LINK_RELATIVE))
632 rel_target = winnt_get_root_relative_target(rpdata.substitute_name,
633 rpdata.substitute_name_nbytes,
637 /* Target points outside of the tree being captured. Exclude
638 * this reparse point from the capture (but inform the library
640 size_t print_name_nchars = rpdata.print_name_nbytes / sizeof(wchar_t);
641 wchar_t print_name0[print_name_nchars + 1];
642 print_name0[print_name_nchars] = L'\0';
643 wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
645 params->progress.scan.cur_path = printable_path(path);
646 params->progress.scan.symlink_target = print_name0;
647 int ret = do_capture_progress(params,
648 WIMLIB_SCAN_DENTRY_EXCLUDED_SYMLINK,
655 if (rel_target == rpdata.substitute_name) {
656 /* Weird target --- keep the reparse point and don't mess with
661 /* We have an absolute target pointing within the directory being
662 * captured, @rel_target is the suffix of the link target that is the
663 * part relative to the directory being captured.
665 * We will cut off the prefix before this part (which is the path to the
666 * directory being captured) and add a dummy prefix. Since the process
667 * will need to be reversed when applying the image, it shouldn't matter
668 * what exactly the prefix is, as long as it looks like an absolute
673 size_t rel_target_nbytes =
674 rpdata.substitute_name_nbytes - ((const u8 *)rel_target -
675 (const u8 *)rpdata.substitute_name);
676 size_t rel_target_nchars = rel_target_nbytes / sizeof(wchar_t);
678 wchar_t tmp[rel_target_nchars + 7];
680 wmemcpy(tmp, L"\\??\\X:\\", 7);
681 wmemcpy(tmp + 7, rel_target, rel_target_nchars);
683 rpdata.substitute_name = tmp;
684 rpdata.substitute_name_nbytes = rel_target_nbytes + (7 * sizeof(wchar_t));
685 rpdata.print_name = tmp + 4;
686 rpdata.print_name_nbytes = rel_target_nbytes + (3 * sizeof(wchar_t));
688 if (make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p))
695 * Loads the reparse point data from a reparse point into memory, optionally
696 * fixing the targets of absolute symbolic links and junction points to be
697 * relative to the root of capture.
700 * Open handle to the reparse point file.
702 * Path to the reparse point file.
704 * Capture parameters. add_flags, capture_root_ino, capture_root_dev,
705 * progfunc, progctx, and progress are used.
707 * Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which the
708 * reparse point buffer will be loaded.
710 * On success, the length of the reparse point buffer in bytes is written
713 * On success, returns a nonpositive `enum rp_status' value.
714 * On failure, returns a positive error code.
717 winnt_get_reparse_data(HANDLE h, const wchar_t *path,
718 struct add_image_params *params,
719 u8 *rpbuf, u16 *rpbuflen_ret)
721 DWORD bytes_returned;
726 if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
727 NULL, 0, rpbuf, REPARSE_POINT_MAX_SIZE,
728 &bytes_returned, NULL))
730 set_errno_from_GetLastError();
731 return WIMLIB_ERR_READ;
734 if (unlikely(bytes_returned < 8)) {
736 return WIMLIB_ERR_INVALID_REPARSE_DATA;
739 rpbuflen = bytes_returned;
740 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
742 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
743 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
744 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
746 ret = winnt_try_rpfix(rpbuf, &rpbuflen,
747 params->capture_root_ino,
748 params->capture_root_dev,
751 *rpbuflen_ret = rpbuflen;
756 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
759 *(u64*)_size_ret += len;
760 return ERROR_SUCCESS;
764 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
770 err = OpenEncryptedFileRaw(path, 0, &file_ctx);
771 if (err != ERROR_SUCCESS) {
772 set_errno_from_win32_error(err);
773 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
774 "for raw read", printable_path(path));
775 return WIMLIB_ERR_OPEN;
778 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
780 if (err != ERROR_SUCCESS) {
781 set_errno_from_win32_error(err);
782 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
783 "\"%ls\"", printable_path(path));
784 ret = WIMLIB_ERR_READ;
788 CloseEncryptedFileRaw(file_ctx);
793 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
794 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
796 const wchar_t *sep, *type, *end;
798 /* The stream name should be returned as :NAME:TYPE */
799 if (raw_stream_name_nchars < 1)
801 if (raw_stream_name[0] != L':')
805 raw_stream_name_nchars--;
807 end = raw_stream_name + raw_stream_name_nchars;
809 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
817 if (wmemcmp(type, L"$DATA", 5))
820 *stream_name_ret = raw_stream_name;
821 *stream_name_nchars_ret = sep - raw_stream_name;
826 build_stream_path(const wchar_t *path, size_t path_nchars,
827 const wchar_t *stream_name, size_t stream_name_nchars)
829 size_t stream_path_nchars;
830 wchar_t *stream_path;
833 stream_path_nchars = path_nchars;
834 if (stream_name_nchars)
835 stream_path_nchars += 1 + stream_name_nchars;
837 stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
839 p = wmempcpy(stream_path, path, path_nchars);
840 if (stream_name_nchars) {
842 p = wmempcpy(p, stream_name, stream_name_nchars);
850 winnt_scan_stream(const wchar_t *path, size_t path_nchars,
851 const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
853 struct wim_inode *inode, struct list_head *unhashed_streams)
855 const wchar_t *stream_name;
856 size_t stream_name_nchars;
857 struct wim_ads_entry *ads_entry;
858 wchar_t *stream_path;
859 struct wim_lookup_table_entry *lte;
862 /* Given the raw stream name (which is something like
863 * :streamname:$DATA), extract just the stream name part.
864 * Ignore any non-$DATA streams. */
865 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
866 &stream_name, &stream_name_nchars))
869 /* If this is a named stream, allocate an ADS entry for it. */
870 if (stream_name_nchars) {
871 ads_entry = inode_add_ads_utf16le(inode, stream_name,
875 return WIMLIB_ERR_NOMEM;
880 /* If the stream is empty, no lookup table entry is needed. */
881 if (stream_size == 0)
884 /* Build the path to the stream. For unnamed streams, this is simply
885 * the path to the file. For named streams, this is the path to the
886 * file, followed by a colon, followed by the stream name. */
887 stream_path = build_stream_path(path, path_nchars,
888 stream_name, stream_name_nchars);
890 return WIMLIB_ERR_NOMEM;
892 /* Set up the lookup table entry for the stream. */
893 lte = new_lookup_table_entry();
896 return WIMLIB_ERR_NOMEM;
898 lte->file_on_disk = stream_path;
899 lte->resource_location = RESOURCE_IN_WINNT_FILE_ON_DISK;
900 lte->size = stream_size;
901 if ((inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) && !ads_entry) {
902 /* Special case for encrypted file. */
904 /* OpenEncryptedFileRaw() expects Win32 name, not NT name.
905 * Change \??\ into \\?\ */
906 lte->file_on_disk[1] = L'\\';
907 wimlib_assert(!wmemcmp(lte->file_on_disk, L"\\\\?\\", 4));
912 ret = win32_get_encrypted_file_size(lte->file_on_disk,
915 free_lookup_table_entry(lte);
918 lte->size = encrypted_size;
919 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
923 stream_id = ads_entry->stream_id;
924 ads_entry->lte = lte;
929 add_unhashed_stream(lte, inode, stream_id, unhashed_streams);
934 * Load information about the streams of an open file into a WIM inode.
936 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
937 * and FindNextStream(). This is done for two reasons:
939 * - FindFirstStream() opens its own handle to the file or directory and
940 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
941 * causing access denied errors on certain files (even when running as the
943 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
944 * and later, whereas the stream support in NtQueryInformationFile() was
945 * already present in Windows XP.
948 winnt_scan_streams(HANDLE *hFile_p, const wchar_t *path, size_t path_nchars,
949 struct wim_inode *inode, struct list_head *unhashed_streams,
950 u64 file_size, u32 vol_flags)
953 u8 _buf[1024] _aligned_attribute(8);
956 IO_STATUS_BLOCK iosb;
958 const FILE_STREAM_INFORMATION *info;
961 bufsize = sizeof(_buf);
963 if (!(vol_flags & FILE_NAMED_STREAMS))
966 /* Get a buffer containing the stream information. */
967 while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(*hFile_p,
971 FileStreamInformation)))
975 case STATUS_BUFFER_OVERFLOW:
981 newbuf = MALLOC(bufsize);
983 newbuf = REALLOC(buf, bufsize);
985 ret = WIMLIB_ERR_NOMEM;
991 case STATUS_NOT_IMPLEMENTED:
992 case STATUS_NOT_SUPPORTED:
993 case STATUS_INVALID_INFO_CLASS:
996 set_errno_from_nt_status(status);
997 ERROR_WITH_ERRNO("\"%ls\": Failed to query stream "
998 "information (status=0x%08"PRIx32")",
999 printable_path(path), (u32)status);
1000 ret = WIMLIB_ERR_READ;
1005 if (iosb.Information == 0) {
1006 /* No stream information. */
1011 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1012 /* OpenEncryptedFileRaw() seems to fail with
1013 * ERROR_SHARING_VIOLATION if there are any handles opened to
1015 (*func_NtClose)(*hFile_p);
1016 *hFile_p = INVALID_HANDLE_VALUE;
1019 /* Parse one or more stream information structures. */
1020 info = (const FILE_STREAM_INFORMATION *)buf;
1022 /* Load the stream information. */
1023 ret = winnt_scan_stream(path, path_nchars,
1025 info->StreamNameLength / 2,
1026 info->StreamSize.QuadPart,
1027 inode, unhashed_streams);
1031 if (info->NextEntryOffset == 0) {
1032 /* No more stream information. */
1035 /* Advance to next stream information. */
1036 info = (const FILE_STREAM_INFORMATION *)
1037 ((const u8 *)info + info->NextEntryOffset);
1043 /* The volume does not support named streams. Only capture the unnamed
1045 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1046 FILE_ATTRIBUTE_REPARSE_POINT))
1052 ret = winnt_scan_stream(path, path_nchars, L"::$DATA", 7,
1053 file_size, inode, unhashed_streams);
1055 /* Free buffer if allocated on heap. */
1056 if (unlikely(buf != _buf))
1062 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1065 size_t full_path_nchars,
1066 const wchar_t *filename,
1067 size_t filename_nchars,
1068 struct add_image_params *params,
1069 struct winnt_scan_stats *stats,
1072 struct wim_dentry *root = NULL;
1073 struct wim_inode *inode = NULL;
1074 HANDLE h = INVALID_HANDLE_VALUE;
1077 FILE_ALL_INFORMATION file_info;
1082 if (should_exclude_path(full_path + params->capture_root_nchars,
1083 full_path_nchars - params->capture_root_nchars,
1090 /* Open the file. */
1091 status = winnt_openat(cur_dir,
1092 (cur_dir ? filename : full_path),
1093 (cur_dir ? filename_nchars : full_path_nchars),
1095 FILE_READ_ATTRIBUTES |
1097 ACCESS_SYSTEM_SECURITY |
1100 if (unlikely(!NT_SUCCESS(status))) {
1101 set_errno_from_nt_status(status);
1102 ERROR_WITH_ERRNO("\"%ls\": Can't open file "
1103 "(status=0x%08"PRIx32")",
1104 printable_path(full_path), (u32)status);
1105 ret = WIMLIB_ERR_OPEN;
1109 /* Get information about the file. */
1111 IO_STATUS_BLOCK iosb;
1113 status = (*func_NtQueryInformationFile)(h, &iosb,
1116 FileAllInformation);
1118 if (unlikely(!NT_SUCCESS(status) &&
1119 status != STATUS_BUFFER_OVERFLOW))
1121 set_errno_from_nt_status(status);
1122 ERROR_WITH_ERRNO("\"%ls\": Can't get file information "
1123 "(status=0x%08"PRIx32")",
1124 printable_path(full_path), (u32)status);
1125 ret = WIMLIB_ERR_STAT;
1130 if (unlikely(!cur_dir)) {
1132 /* Root of tree being captured; get volume information. */
1134 FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1135 FILE_FS_VOLUME_INFORMATION vol_info;
1136 IO_STATUS_BLOCK iosb;
1138 /* Get volume flags */
1139 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1142 FileFsAttributeInformation);
1143 if (likely((NT_SUCCESS(status) ||
1144 (status == STATUS_BUFFER_OVERFLOW)) &&
1145 (iosb.Information >=
1146 offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1147 FileSystemAttributes) +
1148 sizeof(attr_info.FileSystemAttributes))))
1150 vol_flags = attr_info.FileSystemAttributes;
1152 set_errno_from_nt_status(status);
1153 WARNING_WITH_ERRNO("\"%ls\": Can't get volume attributes "
1154 "(status=0x%08"PRIx32")",
1155 printable_path(full_path),
1160 /* Set inode number of root directory */
1161 params->capture_root_ino =
1162 file_info.InternalInformation.IndexNumber.QuadPart;
1164 /* Get volume ID. */
1165 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1168 FileFsVolumeInformation);
1169 if (likely((NT_SUCCESS(status) ||
1170 (status == STATUS_BUFFER_OVERFLOW)) &&
1171 (iosb.Information >=
1172 offsetof(FILE_FS_VOLUME_INFORMATION,
1173 VolumeSerialNumber) +
1174 sizeof(vol_info.VolumeSerialNumber))))
1176 params->capture_root_dev = vol_info.VolumeSerialNumber;
1178 set_errno_from_nt_status(status);
1179 WARNING_WITH_ERRNO("\"%ls\": Can't get volume ID "
1180 "(status=0x%08"PRIx32")",
1181 printable_path(full_path),
1183 params->capture_root_dev = 0;
1187 /* If this is a reparse point, read the reparse data. */
1188 if (unlikely(file_info.BasicInformation.FileAttributes &
1189 FILE_ATTRIBUTE_REPARSE_POINT))
1191 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1192 ret = winnt_get_reparse_data(h, full_path, params,
1205 ERROR_WITH_ERRNO("\"%ls\": Can't get reparse data",
1206 printable_path(full_path));
1211 /* Create a WIM dentry with an associated inode, which may be shared.
1213 * However, we need to explicitly check for directories and files with
1214 * only 1 link and refuse to hard link them. This is because Windows
1215 * has a bug where it can return duplicate File IDs for files and
1216 * directories on the FAT filesystem. */
1217 ret = inode_table_new_dentry(params->inode_table,
1219 file_info.InternalInformation.IndexNumber.QuadPart,
1220 0, /* We don't follow mount points, so we
1221 currently don't need to get the
1222 volume ID / device number. */
1223 (file_info.StandardInformation.NumberOfLinks <= 1 ||
1224 (file_info.BasicInformation.FileAttributes &
1225 FILE_ATTRIBUTE_DIRECTORY)),
1230 /* Get the short (DOS) name of the file. */
1231 status = winnt_get_short_name(h, root);
1233 /* If we can't read the short filename for any reason other than
1234 * out-of-memory, just ignore the error and assume the file has no short
1235 * name. This shouldn't be an issue, since the short names are
1236 * essentially obsolete anyway. */
1237 if (unlikely(status == STATUS_NO_MEMORY)) {
1238 ret = WIMLIB_ERR_NOMEM;
1242 inode = root->d_inode;
1244 if (inode->i_nlink > 1) {
1245 /* Shared inode (hard link); skip reading per-inode information.
1251 inode->i_attributes = file_info.BasicInformation.FileAttributes;
1252 inode->i_creation_time = file_info.BasicInformation.CreationTime.QuadPart;
1253 inode->i_last_write_time = file_info.BasicInformation.LastWriteTime.QuadPart;
1254 inode->i_last_access_time = file_info.BasicInformation.LastAccessTime.QuadPart;
1255 inode->i_resolved = 1;
1257 /* Get the file's security descriptor, unless we are capturing in
1258 * NO_ACLS mode or the volume does not support security descriptors. */
1259 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1260 && (vol_flags & FILE_PERSISTENT_ACLS))
1262 status = winnt_get_security_descriptor(h, inode,
1263 params->sd_set, stats,
1265 if (!NT_SUCCESS(status)) {
1266 set_errno_from_nt_status(status);
1267 ERROR_WITH_ERRNO("\"%ls\": Can't read security "
1268 "descriptor (status=0x%08"PRIu32")",
1269 printable_path(full_path),
1271 ret = WIMLIB_ERR_STAT;
1276 /* Load information about the unnamed data stream and any named data
1278 ret = winnt_scan_streams(&h,
1282 params->unhashed_streams,
1283 file_info.StandardInformation.EndOfFile.QuadPart,
1288 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1290 /* Reparse point: set the reparse data (already read). */
1292 inode->i_not_rpfixed = not_rpfixed;
1293 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1294 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1295 params->lookup_table);
1298 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1300 /* Directory: recurse to children. */
1302 if (unlikely(h == INVALID_HANDLE_VALUE)) {
1303 /* Re-open handle that was closed to read raw encrypted
1305 status = winnt_openat(cur_dir,
1307 filename : full_path),
1309 filename_nchars : full_path_nchars),
1310 FILE_LIST_DIRECTORY | SYNCHRONIZE,
1312 if (!NT_SUCCESS(status)) {
1313 set_errno_from_nt_status(status);
1314 ERROR_WITH_ERRNO("\"%ls\": Can't re-open file "
1315 "(status=0x%08"PRIx32")",
1316 printable_path(full_path),
1318 ret = WIMLIB_ERR_OPEN;
1322 ret = winnt_recurse_directory(h,
1334 params->progress.scan.cur_path = printable_path(full_path);
1336 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1338 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1340 if (likely(h != INVALID_HANDLE_VALUE))
1342 if (likely(ret == 0))
1345 free_dentry_tree(root, params->lookup_table);
1350 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_stats *stats)
1352 if (likely(stats->num_get_sacl_priv_notheld == 0 &&
1353 stats->num_get_sd_access_denied == 0))
1356 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1357 if (stats->num_get_sacl_priv_notheld != 0) {
1358 WARNING("- Could not capture SACL (System Access Control List)\n"
1359 " on %lu files or directories.",
1360 stats->num_get_sacl_priv_notheld);
1362 if (stats->num_get_sd_access_denied != 0) {
1363 WARNING("- Could not capture security descriptor at all\n"
1364 " on %lu files or directories.",
1365 stats->num_get_sd_access_denied);
1367 WARNING("To fully capture all security descriptors, run the program\n"
1368 " with Administrator rights.");
1371 #define WINDOWS_NT_MAX_PATH 32768
1373 /* Win32 version of capturing a directory tree. */
1375 win32_build_dentry_tree(struct wim_dentry **root_ret,
1376 const wchar_t *root_disk_path,
1377 struct add_image_params *params)
1383 struct winnt_scan_stats stats;
1385 /* WARNING: There is no check for overflow later when this buffer is
1386 * being used! But it's as long as the maximum path length understood
1387 * by Windows NT (which is NOT the same as MAX_PATH). */
1388 path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1390 return WIMLIB_ERR_NOMEM;
1392 /* Translate into full path. */
1393 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 3,
1396 if (unlikely(dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 3)) {
1397 ERROR("Can't get full path name for \"%ls\"", root_disk_path);
1398 return WIMLIB_ERR_UNSUPPORTED;
1401 /* Add \??\ prefix to form the NT namespace path. */
1402 wmemcpy(path, L"\\??\\", 4);
1403 path_nchars = dret + 4;
1405 /* Strip trailing slashes. If we don't do this, we may create a path
1406 * with multiple consecutive backslashes, which for some reason causes
1407 * Windows to report that the file cannot be found. */
1408 while (unlikely(path[path_nchars - 1] == L'\\' &&
1409 path[path_nchars - 2] != L':'))
1410 path[--path_nchars] = L'\0';
1412 params->capture_root_nchars = path_nchars;
1414 memset(&stats, 0, sizeof(stats));
1416 ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
1417 path, path_nchars, L"", 0,
1421 winnt_do_scan_warnings(root_disk_path, &stats);
1425 #endif /* __WIN32__ */