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);
592 static enum rp_status
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 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED_SYMLINK, NULL);
651 if (rel_target == rpdata.substitute_name) {
652 /* Weird target --- keep the reparse point and don't mess with
657 /* We have an absolute target pointing within the directory being
658 * captured, @rel_target is the suffix of the link target that is the
659 * part relative to the directory being captured.
661 * We will cut off the prefix before this part (which is the path to the
662 * directory being captured) and add a dummy prefix. Since the process
663 * will need to be reversed when applying the image, it shouldn't matter
664 * what exactly the prefix is, as long as it looks like an absolute
669 size_t rel_target_nbytes =
670 rpdata.substitute_name_nbytes - ((const u8 *)rel_target -
671 (const u8 *)rpdata.substitute_name);
672 size_t rel_target_nchars = rel_target_nbytes / sizeof(wchar_t);
674 wchar_t tmp[rel_target_nchars + 7];
676 wmemcpy(tmp, L"\\??\\X:\\", 7);
677 wmemcpy(tmp + 7, rel_target, rel_target_nchars);
679 rpdata.substitute_name = tmp;
680 rpdata.substitute_name_nbytes = rel_target_nbytes + (7 * sizeof(wchar_t));
681 rpdata.print_name = tmp + 4;
682 rpdata.print_name_nbytes = rel_target_nbytes + (3 * sizeof(wchar_t));
684 if (make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p))
691 * Loads the reparse point data from a reparse point into memory, optionally
692 * fixing the targets of absolute symbolic links and junction points to be
693 * relative to the root of capture.
696 * Open handle to the reparse point file.
698 * Path to the reparse point file.
700 * Capture parameters. add_flags, capture_root_ino, capture_root_dev,
701 * progress_func, and progress are used.
703 * Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which the
704 * reparse point buffer will be loaded.
706 * On success, the length of the reparse point buffer in bytes is written
709 * On success, returns a nonpositive `enum rp_status' value.
710 * On failure, returns a positive error code.
713 winnt_get_reparse_data(HANDLE h, const wchar_t *path,
714 struct add_image_params *params,
715 u8 *rpbuf, u16 *rpbuflen_ret)
717 DWORD bytes_returned;
722 if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
723 NULL, 0, rpbuf, REPARSE_POINT_MAX_SIZE,
724 &bytes_returned, NULL))
726 set_errno_from_GetLastError();
727 return WIMLIB_ERR_READ;
730 if (unlikely(bytes_returned < 8)) {
732 return WIMLIB_ERR_INVALID_REPARSE_DATA;
735 rpbuflen = bytes_returned;
736 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
738 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
739 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
740 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
742 ret = winnt_try_rpfix(rpbuf, &rpbuflen,
743 params->capture_root_ino,
744 params->capture_root_dev,
747 *rpbuflen_ret = rpbuflen;
752 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
755 *(u64*)_size_ret += len;
756 return ERROR_SUCCESS;
760 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
766 err = OpenEncryptedFileRaw(path, 0, &file_ctx);
767 if (err != ERROR_SUCCESS) {
768 set_errno_from_win32_error(err);
769 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
770 "for raw read", printable_path(path));
771 return WIMLIB_ERR_OPEN;
774 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
776 if (err != ERROR_SUCCESS) {
777 set_errno_from_win32_error(err);
778 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
779 "\"%ls\"", printable_path(path));
780 ret = WIMLIB_ERR_READ;
784 CloseEncryptedFileRaw(file_ctx);
789 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
790 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
792 const wchar_t *sep, *type, *end;
794 /* The stream name should be returned as :NAME:TYPE */
795 if (raw_stream_name_nchars < 1)
797 if (raw_stream_name[0] != L':')
801 raw_stream_name_nchars--;
803 end = raw_stream_name + raw_stream_name_nchars;
805 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
813 if (wmemcmp(type, L"$DATA", 5))
816 *stream_name_ret = raw_stream_name;
817 *stream_name_nchars_ret = sep - raw_stream_name;
822 build_stream_path(const wchar_t *path, size_t path_nchars,
823 const wchar_t *stream_name, size_t stream_name_nchars)
825 size_t stream_path_nchars;
826 wchar_t *stream_path;
829 stream_path_nchars = path_nchars;
830 if (stream_name_nchars)
831 stream_path_nchars += 1 + stream_name_nchars;
833 stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
835 p = wmempcpy(stream_path, path, path_nchars);
836 if (stream_name_nchars) {
838 p = wmempcpy(p, stream_name, stream_name_nchars);
846 winnt_scan_stream(const wchar_t *path, size_t path_nchars,
847 const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
849 struct wim_inode *inode, struct list_head *unhashed_streams)
851 const wchar_t *stream_name;
852 size_t stream_name_nchars;
853 struct wim_ads_entry *ads_entry;
854 wchar_t *stream_path;
855 struct wim_lookup_table_entry *lte;
858 /* Given the raw stream name (which is something like
859 * :streamname:$DATA), extract just the stream name part.
860 * Ignore any non-$DATA streams. */
861 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
862 &stream_name, &stream_name_nchars))
865 /* If this is a named stream, allocate an ADS entry for it. */
866 if (stream_name_nchars) {
867 ads_entry = inode_add_ads_utf16le(inode, stream_name,
871 return WIMLIB_ERR_NOMEM;
876 /* If the stream is empty, no lookup table entry is needed. */
877 if (stream_size == 0)
880 /* Build the path to the stream. For unnamed streams, this is simply
881 * the path to the file. For named streams, this is the path to the
882 * file, followed by a colon, followed by the stream name. */
883 stream_path = build_stream_path(path, path_nchars,
884 stream_name, stream_name_nchars);
886 return WIMLIB_ERR_NOMEM;
888 /* Set up the lookup table entry for the stream. */
889 lte = new_lookup_table_entry();
892 return WIMLIB_ERR_NOMEM;
894 lte->file_on_disk = stream_path;
895 lte->resource_location = RESOURCE_IN_WINNT_FILE_ON_DISK;
896 lte->size = stream_size;
897 if ((inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) && !ads_entry) {
898 /* Special case for encrypted file. */
900 /* OpenEncryptedFileRaw() expects Win32 name, not NT name.
901 * Change \??\ into \\?\ */
902 lte->file_on_disk[1] = L'\\';
903 wimlib_assert(!wmemcmp(lte->file_on_disk, L"\\\\?\\", 4));
908 ret = win32_get_encrypted_file_size(lte->file_on_disk,
911 free_lookup_table_entry(lte);
914 lte->size = encrypted_size;
915 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
919 stream_id = ads_entry->stream_id;
920 ads_entry->lte = lte;
925 add_unhashed_stream(lte, inode, stream_id, unhashed_streams);
930 * Load information about the streams of an open file into a WIM inode.
932 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
933 * and FindNextStream(). This is done for two reasons:
935 * - FindFirstStream() opens its own handle to the file or directory and
936 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
937 * causing access denied errors on certain files (even when running as the
939 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
940 * and later, whereas the stream support in NtQueryInformationFile() was
941 * already present in Windows XP.
944 winnt_scan_streams(HANDLE *hFile_p, const wchar_t *path, size_t path_nchars,
945 struct wim_inode *inode, struct list_head *unhashed_streams,
946 u64 file_size, u32 vol_flags)
949 u8 _buf[1024] _aligned_attribute(8);
952 IO_STATUS_BLOCK iosb;
954 const FILE_STREAM_INFORMATION *info;
957 bufsize = sizeof(_buf);
959 if (!(vol_flags & FILE_NAMED_STREAMS))
962 /* Get a buffer containing the stream information. */
963 while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(*hFile_p,
967 FileStreamInformation)))
971 case STATUS_BUFFER_OVERFLOW:
977 newbuf = MALLOC(bufsize);
979 newbuf = REALLOC(buf, bufsize);
981 ret = WIMLIB_ERR_NOMEM;
987 case STATUS_NOT_IMPLEMENTED:
988 case STATUS_NOT_SUPPORTED:
989 case STATUS_INVALID_INFO_CLASS:
992 set_errno_from_nt_status(status);
993 ERROR_WITH_ERRNO("\"%ls\": Failed to query stream "
994 "information (status=0x%08"PRIx32")",
995 printable_path(path), (u32)status);
996 ret = WIMLIB_ERR_READ;
1001 if (iosb.Information == 0) {
1002 /* No stream information. */
1007 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1008 /* OpenEncryptedFileRaw() seems to fail with
1009 * ERROR_SHARING_VIOLATION if there are any handles opened to
1011 (*func_NtClose)(*hFile_p);
1012 *hFile_p = INVALID_HANDLE_VALUE;
1015 /* Parse one or more stream information structures. */
1016 info = (const FILE_STREAM_INFORMATION *)buf;
1018 /* Load the stream information. */
1019 ret = winnt_scan_stream(path, path_nchars,
1021 info->StreamNameLength / 2,
1022 info->StreamSize.QuadPart,
1023 inode, unhashed_streams);
1027 if (info->NextEntryOffset == 0) {
1028 /* No more stream information. */
1031 /* Advance to next stream information. */
1032 info = (const FILE_STREAM_INFORMATION *)
1033 ((const u8 *)info + info->NextEntryOffset);
1039 /* The volume does not support named streams. Only capture the unnamed
1041 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1042 FILE_ATTRIBUTE_REPARSE_POINT))
1048 ret = winnt_scan_stream(path, path_nchars, L"::$DATA", 7,
1049 file_size, inode, unhashed_streams);
1051 /* Free buffer if allocated on heap. */
1052 if (unlikely(buf != _buf))
1058 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1061 size_t full_path_nchars,
1062 const wchar_t *filename,
1063 size_t filename_nchars,
1064 struct add_image_params *params,
1065 struct winnt_scan_stats *stats,
1068 struct wim_dentry *root = NULL;
1069 struct wim_inode *inode = NULL;
1070 HANDLE h = INVALID_HANDLE_VALUE;
1073 FILE_ALL_INFORMATION file_info;
1078 if (should_exclude_path(full_path + params->capture_root_nchars,
1079 full_path_nchars - params->capture_root_nchars,
1086 /* Open the file. */
1087 status = winnt_openat(cur_dir,
1088 (cur_dir ? filename : full_path),
1089 (cur_dir ? filename_nchars : full_path_nchars),
1091 FILE_READ_ATTRIBUTES |
1093 ACCESS_SYSTEM_SECURITY |
1096 if (unlikely(!NT_SUCCESS(status))) {
1097 set_errno_from_nt_status(status);
1098 ERROR_WITH_ERRNO("\"%ls\": Can't open file "
1099 "(status=0x%08"PRIx32")",
1100 printable_path(full_path), (u32)status);
1101 ret = WIMLIB_ERR_OPEN;
1105 /* Get information about the file. */
1107 IO_STATUS_BLOCK iosb;
1109 status = (*func_NtQueryInformationFile)(h, &iosb,
1112 FileAllInformation);
1114 if (unlikely(!NT_SUCCESS(status) &&
1115 status != STATUS_BUFFER_OVERFLOW))
1117 set_errno_from_nt_status(status);
1118 ERROR_WITH_ERRNO("\"%ls\": Can't get file information "
1119 "(status=0x%08"PRIx32")",
1120 printable_path(full_path), (u32)status);
1121 ret = WIMLIB_ERR_STAT;
1126 if (unlikely(!cur_dir)) {
1128 /* Root of tree being captured; get volume information. */
1130 FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1131 FILE_FS_VOLUME_INFORMATION vol_info;
1132 IO_STATUS_BLOCK iosb;
1134 /* Get volume flags */
1135 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1138 FileFsAttributeInformation);
1139 if (likely((NT_SUCCESS(status) ||
1140 (status == STATUS_BUFFER_OVERFLOW)) &&
1141 (iosb.Information >=
1142 offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1143 FileSystemAttributes) +
1144 sizeof(attr_info.FileSystemAttributes))))
1146 vol_flags = attr_info.FileSystemAttributes;
1148 set_errno_from_nt_status(status);
1149 WARNING_WITH_ERRNO("\"%ls\": Can't get volume attributes "
1150 "(status=0x%08"PRIx32")",
1151 printable_path(full_path),
1156 /* Set inode number of root directory */
1157 params->capture_root_ino =
1158 file_info.InternalInformation.IndexNumber.QuadPart;
1160 /* Get volume ID. */
1161 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1164 FileFsVolumeInformation);
1165 if (likely((NT_SUCCESS(status) ||
1166 (status == STATUS_BUFFER_OVERFLOW)) &&
1167 (iosb.Information >=
1168 offsetof(FILE_FS_VOLUME_INFORMATION,
1169 VolumeSerialNumber) +
1170 sizeof(vol_info.VolumeSerialNumber))))
1172 params->capture_root_dev = vol_info.VolumeSerialNumber;
1174 set_errno_from_nt_status(status);
1175 WARNING_WITH_ERRNO("\"%ls\": Can't get volume ID "
1176 "(status=0x%08"PRIx32")",
1177 printable_path(full_path),
1179 params->capture_root_dev = 0;
1183 /* If this is a reparse point, read the reparse data. */
1184 if (unlikely(file_info.BasicInformation.FileAttributes &
1185 FILE_ATTRIBUTE_REPARSE_POINT))
1187 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1188 ret = winnt_get_reparse_data(h, full_path, params,
1201 ERROR_WITH_ERRNO("\"%ls\": Can't get reparse data",
1202 printable_path(full_path));
1207 /* Create a WIM dentry with an associated inode, which may be shared.
1209 * However, we need to explicitly check for directories and files with
1210 * only 1 link and refuse to hard link them. This is because Windows
1211 * has a bug where it can return duplicate File IDs for files and
1212 * directories on the FAT filesystem. */
1213 ret = inode_table_new_dentry(params->inode_table,
1215 file_info.InternalInformation.IndexNumber.QuadPart,
1216 0, /* We don't follow mount points, so we
1217 currently don't need to get the
1218 volume ID / device number. */
1219 (file_info.StandardInformation.NumberOfLinks <= 1 ||
1220 (file_info.BasicInformation.FileAttributes &
1221 FILE_ATTRIBUTE_DIRECTORY)),
1226 /* Get the short (DOS) name of the file. */
1227 status = winnt_get_short_name(h, root);
1229 /* If we can't read the short filename for any reason other than
1230 * out-of-memory, just ignore the error and assume the file has no short
1231 * name. This shouldn't be an issue, since the short names are
1232 * essentially obsolete anyway. */
1233 if (unlikely(status == STATUS_NO_MEMORY)) {
1234 ret = WIMLIB_ERR_NOMEM;
1238 inode = root->d_inode;
1240 if (inode->i_nlink > 1) {
1241 /* Shared inode (hard link); skip reading per-inode information.
1247 inode->i_attributes = file_info.BasicInformation.FileAttributes;
1248 inode->i_creation_time = file_info.BasicInformation.CreationTime.QuadPart;
1249 inode->i_last_write_time = file_info.BasicInformation.LastWriteTime.QuadPart;
1250 inode->i_last_access_time = file_info.BasicInformation.LastAccessTime.QuadPart;
1251 inode->i_resolved = 1;
1253 /* Get the file's security descriptor, unless we are capturing in
1254 * NO_ACLS mode or the volume does not support security descriptors. */
1255 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1256 && (vol_flags & FILE_PERSISTENT_ACLS))
1258 status = winnt_get_security_descriptor(h, inode,
1259 params->sd_set, stats,
1261 if (!NT_SUCCESS(status)) {
1262 set_errno_from_nt_status(status);
1263 ERROR_WITH_ERRNO("\"%ls\": Can't read security "
1264 "descriptor (status=0x%08"PRIu32")",
1265 printable_path(full_path),
1267 ret = WIMLIB_ERR_STAT;
1272 /* Load information about the unnamed data stream and any named data
1274 ret = winnt_scan_streams(&h,
1278 params->unhashed_streams,
1279 file_info.StandardInformation.EndOfFile.QuadPart,
1284 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1286 /* Reparse point: set the reparse data (already read). */
1288 inode->i_not_rpfixed = not_rpfixed;
1289 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1290 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1291 params->lookup_table);
1294 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1296 /* Directory: recurse to children. */
1298 if (unlikely(h == INVALID_HANDLE_VALUE)) {
1299 /* Re-open handle that was closed to read raw encrypted
1301 status = winnt_openat(cur_dir,
1303 filename : full_path),
1305 filename_nchars : full_path_nchars),
1306 FILE_LIST_DIRECTORY | SYNCHRONIZE,
1308 if (!NT_SUCCESS(status)) {
1309 set_errno_from_nt_status(status);
1310 ERROR_WITH_ERRNO("\"%ls\": Can't re-open file "
1311 "(status=0x%08"PRIx32")",
1312 printable_path(full_path),
1314 ret = WIMLIB_ERR_OPEN;
1318 ret = winnt_recurse_directory(h,
1330 params->progress.scan.cur_path = printable_path(full_path);
1332 do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1334 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1336 if (likely(h != INVALID_HANDLE_VALUE))
1338 if (likely(ret == 0))
1341 free_dentry_tree(root, params->lookup_table);
1346 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_stats *stats)
1348 if (likely(stats->num_get_sacl_priv_notheld == 0 &&
1349 stats->num_get_sd_access_denied == 0))
1352 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1353 if (stats->num_get_sacl_priv_notheld != 0) {
1354 WARNING("- Could not capture SACL (System Access Control List)\n"
1355 " on %lu files or directories.",
1356 stats->num_get_sacl_priv_notheld);
1358 if (stats->num_get_sd_access_denied != 0) {
1359 WARNING("- Could not capture security descriptor at all\n"
1360 " on %lu files or directories.",
1361 stats->num_get_sd_access_denied);
1363 WARNING("To fully capture all security descriptors, run the program\n"
1364 " with Administrator rights.");
1367 #define WINDOWS_NT_MAX_PATH 32768
1369 /* Win32 version of capturing a directory tree. */
1371 win32_build_dentry_tree(struct wim_dentry **root_ret,
1372 const wchar_t *root_disk_path,
1373 struct add_image_params *params)
1379 struct winnt_scan_stats stats;
1381 /* WARNING: There is no check for overflow later when this buffer is
1382 * being used! But it's as long as the maximum path length understood
1383 * by Windows NT (which is NOT the same as MAX_PATH). */
1384 path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1386 return WIMLIB_ERR_NOMEM;
1388 /* Translate into full path. */
1389 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 3,
1392 if (unlikely(dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 3)) {
1393 ERROR("Can't get full path name for \"%ls\"", root_disk_path);
1394 return WIMLIB_ERR_UNSUPPORTED;
1397 /* Add \??\ prefix to form the NT namespace path. */
1398 wmemcpy(path, L"\\??\\", 4);
1399 path_nchars = dret + 4;
1401 /* Strip trailing slashes. If we don't do this, we may create a path
1402 * with multiple consecutive backslashes, which for some reason causes
1403 * Windows to report that the file cannot be found. */
1404 while (unlikely(path[path_nchars - 1] == L'\\' &&
1405 path[path_nchars - 2] != L':'))
1406 path[--path_nchars] = L'\0';
1408 params->capture_root_nchars = path_nchars;
1410 memset(&stats, 0, sizeof(stats));
1412 ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
1413 path, path_nchars, L"", 0,
1417 winnt_do_scan_warnings(root_disk_path, &stats);
1421 #endif /* __WIN32__ */