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,
90 FILE_OPEN_REPARSE_POINT |
91 FILE_OPEN_FOR_BACKUP_INTENT |
92 FILE_SYNCHRONOUS_IO_NONALERT |
93 FILE_SEQUENTIAL_ONLY);
94 if (!NT_SUCCESS(status)) {
95 /* Try requesting fewer permissions */
96 if (status == STATUS_ACCESS_DENIED ||
97 status == STATUS_PRIVILEGE_NOT_HELD) {
98 if (perms & ACCESS_SYSTEM_SECURITY) {
99 perms &= ~ACCESS_SYSTEM_SECURITY;
102 if (perms & READ_CONTROL) {
103 perms &= ~READ_CONTROL;
111 /* Read the first @size bytes from the file, or named data stream of a file,
112 * from which the stream entry @lte was created. */
114 read_winnt_file_prefix(const struct wim_lookup_table_entry *lte, u64 size,
115 consume_data_callback_t cb, void *cb_ctx)
124 /* This is an NT namespace path. */
125 path = lte->file_on_disk;
127 status = winnt_openat(NULL, path, wcslen(path),
128 FILE_READ_DATA | SYNCHRONIZE, &h);
129 if (!NT_SUCCESS(status)) {
130 set_errno_from_nt_status(status);
131 ERROR_WITH_ERRNO("\"%ls\": Can't open for reading "
132 "(status=0x%08"PRIx32")",
133 printable_path(path), (u32)status);
134 return WIMLIB_ERR_OPEN;
138 bytes_remaining = size;
139 while (bytes_remaining) {
140 IO_STATUS_BLOCK iosb;
144 count = min(sizeof(buf), bytes_remaining);
146 status = (*func_NtReadFile)(h, NULL, NULL, NULL,
147 &iosb, buf, count, NULL, NULL);
148 if (!NT_SUCCESS(status)) {
149 set_errno_from_nt_status(status);
150 ERROR_WITH_ERRNO("\"%ls\": Error reading data "
151 "(status=0x%08"PRIx32")",
152 printable_path(path), (u32)status);
153 ret = WIMLIB_ERR_READ;
157 bytes_read = iosb.Information;
159 bytes_remaining -= bytes_read;
160 ret = (*cb)(buf, bytes_read, cb_ctx);
168 struct win32_encrypted_read_ctx {
169 consume_data_callback_t read_prefix_cb;
170 void *read_prefix_ctx;
176 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
178 struct win32_encrypted_read_ctx *ctx = _ctx;
180 size_t bytes_to_consume = min(len, ctx->bytes_remaining);
182 if (bytes_to_consume == 0)
183 return ERROR_SUCCESS;
185 ret = (*ctx->read_prefix_cb)(data, bytes_to_consume, ctx->read_prefix_ctx);
187 ctx->wimlib_err_code = ret;
188 /* Shouldn't matter what error code is returned here, as long as
189 * it isn't ERROR_SUCCESS. */
190 return ERROR_READ_FAULT;
192 ctx->bytes_remaining -= bytes_to_consume;
193 return ERROR_SUCCESS;
197 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
199 consume_data_callback_t cb, void *cb_ctx)
201 struct win32_encrypted_read_ctx export_ctx;
206 export_ctx.read_prefix_cb = cb;
207 export_ctx.read_prefix_ctx = cb_ctx;
208 export_ctx.wimlib_err_code = 0;
209 export_ctx.bytes_remaining = size;
211 err = OpenEncryptedFileRaw(lte->file_on_disk, 0, &file_ctx);
212 if (err != ERROR_SUCCESS) {
213 set_errno_from_win32_error(err);
214 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
216 printable_path(lte->file_on_disk));
217 return WIMLIB_ERR_OPEN;
219 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
220 &export_ctx, file_ctx);
221 if (err != ERROR_SUCCESS) {
222 set_errno_from_win32_error(err);
223 ERROR_WITH_ERRNO("Failed to read encrypted file \"%ls\"",
224 printable_path(lte->file_on_disk));
225 ret = export_ctx.wimlib_err_code;
227 ret = WIMLIB_ERR_READ;
228 } else if (export_ctx.bytes_remaining != 0) {
229 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
230 "encryted file \"%ls\"",
231 size - export_ctx.bytes_remaining, size,
232 printable_path(lte->file_on_disk));
233 ret = WIMLIB_ERR_READ;
237 CloseEncryptedFileRaw(file_ctx);
242 * Load the short name of a file into a WIM dentry.
245 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
247 /* It's not any harder to just make the NtQueryInformationFile() system
248 * call ourselves, and it saves a dumb call to FindFirstFile() which of
249 * course has to create its own handle. */
251 IO_STATUS_BLOCK iosb;
252 u8 buf[128] _aligned_attribute(8);
253 const FILE_NAME_INFORMATION *info;
255 status = (*func_NtQueryInformationFile)(h, &iosb, buf, sizeof(buf),
256 FileAlternateNameInformation);
257 info = (const FILE_NAME_INFORMATION *)buf;
258 if (NT_SUCCESS(status) && info->FileNameLength != 0) {
259 dentry->short_name = utf16le_dupz(info->FileName,
260 info->FileNameLength);
261 if (!dentry->short_name)
262 return STATUS_NO_MEMORY;
263 dentry->short_name_nbytes = info->FileNameLength;
269 * Load the security descriptor of a file into the corresponding inode, and the
270 * WIM image's security descriptor set.
273 winnt_get_security_descriptor(HANDLE h, struct wim_inode *inode,
274 struct wim_sd_set *sd_set,
275 struct winnt_scan_stats *stats, int add_flags)
277 SECURITY_INFORMATION requestedInformation;
278 u8 _buf[4096] _aligned_attribute(8);
284 requestedInformation = DACL_SECURITY_INFORMATION |
285 SACL_SECURITY_INFORMATION |
286 OWNER_SECURITY_INFORMATION |
287 GROUP_SECURITY_INFORMATION;
289 bufsize = sizeof(_buf);
292 * We need the file's security descriptor in
293 * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
294 * opened with as many relevant permissions as possible. At this point,
295 * on Windows there are a number of options for reading a file's
296 * security descriptor:
298 * GetFileSecurity(): This takes in a path and returns the
299 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle,
300 * not ours, and the handle created internally doesn't specify
301 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied
302 * errors on some files and directories, even when running as the
305 * GetSecurityInfo(): This takes in a handle and returns the security
306 * descriptor split into a bunch of different parts. This should work,
307 * but it's dumb because we have to put the security descriptor back
310 * BackupRead(): This can read the security descriptor, but this is a
311 * difficult-to-use API, probably only works as the Administrator, and
312 * the format of the returned data is not well documented.
314 * NtQuerySecurityObject(): This is exactly what we need, as it takes
315 * in a handle and returns the security descriptor in
316 * SECURITY_DESCRIPTOR_RELATIVE format. Only problem is that it's a
317 * ntdll function and therefore not officially part of the Win32 API.
320 while (!(NT_SUCCESS(status = (*func_NtQuerySecurityObject)(h,
321 requestedInformation,
322 (PSECURITY_DESCRIPTOR)buf,
327 case STATUS_BUFFER_TOO_SMALL:
328 wimlib_assert(buf == _buf);
329 buf = MALLOC(len_needed);
331 return STATUS_NO_MEMORY;
332 bufsize = len_needed;
334 case STATUS_PRIVILEGE_NOT_HELD:
335 case STATUS_ACCESS_DENIED:
336 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
338 /* Permission denied in STRICT_ACLS mode, or
342 if (requestedInformation & SACL_SECURITY_INFORMATION) {
343 /* Try again without the SACL. */
344 stats->num_get_sacl_priv_notheld++;
345 requestedInformation &= ~SACL_SECURITY_INFORMATION;
348 /* Fake success (useful when capturing as
349 * non-Administrator). */
350 stats->num_get_sd_access_denied++;
351 status = STATUS_SUCCESS;
356 /* Add the security descriptor to the WIM image, and save its ID in
358 inode->i_security_id = sd_set_add_sd(sd_set, buf, len_needed);
359 if (unlikely(inode->i_security_id < 0))
360 status = STATUS_NO_MEMORY;
362 if (unlikely(buf != _buf))
368 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
371 size_t full_path_nchars,
372 const wchar_t *filename,
373 size_t filename_nchars,
374 struct add_image_params *params,
375 struct winnt_scan_stats *stats,
379 winnt_recurse_directory(HANDLE h,
381 size_t full_path_nchars,
382 struct wim_dentry *parent,
383 struct add_image_params *params,
384 struct winnt_scan_stats *stats,
388 const size_t bufsize = 8192;
389 IO_STATUS_BLOCK iosb;
393 buf = MALLOC(bufsize);
395 return WIMLIB_ERR_NOMEM;
397 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
398 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
400 while (NT_SUCCESS(status = (*func_NtQueryDirectoryFile)(h, NULL, NULL, NULL,
402 FileNamesInformation,
403 FALSE, NULL, FALSE)))
405 const FILE_NAMES_INFORMATION *info = buf;
407 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
408 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
409 info->FileName[1] == L'.'))
412 struct wim_dentry *child;
414 p = full_path + full_path_nchars;
416 p = wmempcpy(p, info->FileName,
417 info->FileNameLength / 2);
420 ret = winnt_build_dentry_tree_recursive(
425 full_path + full_path_nchars + 1,
426 info->FileNameLength / 2,
431 full_path[full_path_nchars] = L'\0';
436 dentry_add_child(parent, child);
438 if (info->NextEntryOffset == 0)
440 info = (const FILE_NAMES_INFORMATION *)
441 ((const u8 *)info + info->NextEntryOffset);
445 if (unlikely(status != STATUS_NO_MORE_FILES)) {
446 set_errno_from_nt_status(status);
447 ERROR_WITH_ERRNO("\"%ls\": Can't read directory "
448 "(status=0x%08"PRIx32")",
449 printable_path(full_path), (u32)status);
450 ret = WIMLIB_ERR_READ;
457 /* Reparse point fixup status code */
459 /* Reparse point corresponded to an absolute symbolic link or junction
460 * point that pointed outside the directory tree being captured, and
461 * therefore was excluded. */
464 /* Reparse point was not fixed as it was either a relative symbolic
465 * link, a mount point, or something else we could not understand. */
468 /* Reparse point corresponded to an absolute symbolic link or junction
469 * point that pointed inside the directory tree being captured, where
470 * the target was specified by a "full" \??\ prefixed path, and
471 * therefore was fixed to be relative to the root of the directory tree
473 RP_FIXED_FULLPATH = 0x2,
475 /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
476 * have the \??\ prefix. It may have begun with a drive letter though.
478 RP_FIXED_ABSPATH = 0x4,
480 /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
481 RP_FIXED = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
484 /* Given the "substitute name" target of a Windows reparse point, try doing a
485 * fixup where we change it to be absolute relative to the root of the directory
486 * tree being captured.
488 * Note that this is only executed when WIMLIB_ADD_FLAG_RPFIX has been
491 * @capture_root_ino and @capture_root_dev indicate the inode number and device
492 * of the root of the directory tree being captured. They are meant to identify
493 * this directory (as an alternative to its actual path, which could potentially
494 * be reached via multiple destinations due to other symbolic links). This may
495 * not work properly on FAT, which doesn't seem to supply proper inode numbers
496 * or file IDs. However, FAT doesn't support reparse points so this function
497 * wouldn't even be called anyway.
499 static enum rp_status
500 winnt_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
501 u64 capture_root_ino, u64 capture_root_dev,
504 u16 target_nchars = *target_nbytes_p / 2;
505 size_t stripped_chars;
506 wchar_t *orig_target;
509 ret = parse_substitute_name(target, *target_nbytes_p, rptag);
512 stripped_chars = ret;
515 target[target_nchars] = L'\0';
516 orig_target = target;
517 target = capture_fixup_absolute_symlink(target + stripped_chars,
518 capture_root_ino, capture_root_dev);
521 target_nchars = wcslen(target);
522 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
523 *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
525 return RP_FIXED_FULLPATH;
527 return RP_FIXED_ABSPATH;
530 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
533 winnt_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
534 u64 capture_root_ino, u64 capture_root_dev,
535 const wchar_t *path, struct add_image_params *params)
537 struct reparse_data rpdata;
539 enum rp_status rp_status;
541 ret = parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata);
545 rp_status = winnt_capture_maybe_rpfix_target(rpdata.substitute_name,
546 &rpdata.substitute_name_nbytes,
549 le32_to_cpu(*(le32*)rpbuf));
550 if (rp_status & RP_FIXED) {
551 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
552 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
553 wmemcpy(substitute_name_copy, rpdata.substitute_name,
554 rpdata.substitute_name_nbytes / 2);
555 rpdata.substitute_name = substitute_name_copy;
556 rpdata.print_name = substitute_name_copy;
557 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
558 if (rp_status == RP_FIXED_FULLPATH) {
559 /* "full path", meaning \??\ prefixed. We should not
560 * include this prefix in the print name, as it is
561 * apparently meant for the filesystem driver only. */
562 rpdata.print_name += 4;
563 rpdata.print_name_nbytes -= 8;
565 ret = make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
571 if (rp_status == RP_EXCLUDED) {
572 /* Ignoring absolute symbolic link or junction point
573 * that points out of the tree to be captured. */
574 size_t print_name_nchars = rpdata.print_name_nbytes / 2;
575 wchar_t print_name0[print_name_nchars + 1];
576 print_name0[print_name_nchars] = L'\0';
577 wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
579 params->progress.scan.cur_path = printable_path(path);
580 params->progress.scan.symlink_target = print_name0;
581 do_capture_progress(params,
582 WIMLIB_SCAN_DENTRY_EXCLUDED_SYMLINK,
591 * Loads the reparse point data from a reparse point into memory, optionally
592 * fixing the targets of absolute symbolic links and junction points to be
593 * relative to the root of capture.
595 * @h: Open handle to the reparse point.
596 * @path: Path to the reparse point file.
597 * @params: Additional parameters, including whether to do reparse point fixups
599 * @rpbuf: Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
600 * the reparse point buffer will be loaded.
601 * @rpbuflen_ret: On success, the length of the reparse point buffer in bytes
602 * is written to this location.
605 * On success, returns an `enum rp_status' value that indicates if and/or
606 * how the reparse point fixup was done.
608 * On failure, returns a negative value that is a negated WIMLIB_ERR_*
612 winnt_get_reparse_data(HANDLE h, const wchar_t *path,
613 struct add_image_params *params,
614 u8 *rpbuf, u16 *rpbuflen_ret)
621 if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
622 NULL, /* "Not used with this operation; set to NULL" */
623 0, /* "Not used with this operation; set to 0" */
624 rpbuf, /* "A pointer to a buffer that
625 receives the reparse point data */
626 REPARSE_POINT_MAX_SIZE, /* "The size of the output
631 set_errno_from_GetLastError();
632 return -WIMLIB_ERR_READ;
635 if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
637 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
640 rpbuflen = bytesReturned;
641 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
642 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
643 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
644 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
646 /* Try doing reparse point fixup */
647 ret = winnt_capture_try_rpfix(rpbuf,
649 params->capture_root_ino,
650 params->capture_root_dev,
656 *rpbuflen_ret = rpbuflen;
661 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
664 *(u64*)_size_ret += len;
665 return ERROR_SUCCESS;
669 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
675 err = OpenEncryptedFileRaw(path, 0, &file_ctx);
676 if (err != ERROR_SUCCESS) {
677 set_errno_from_win32_error(err);
678 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
679 "for raw read", printable_path(path));
680 return WIMLIB_ERR_OPEN;
683 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
685 if (err != ERROR_SUCCESS) {
686 set_errno_from_win32_error(err);
687 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
688 "\"%ls\"", printable_path(path));
689 ret = WIMLIB_ERR_READ;
693 CloseEncryptedFileRaw(file_ctx);
698 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
699 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
701 const wchar_t *sep, *type, *end;
703 /* The stream name should be returned as :NAME:TYPE */
704 if (raw_stream_name_nchars < 1)
706 if (raw_stream_name[0] != L':')
710 raw_stream_name_nchars--;
712 end = raw_stream_name + raw_stream_name_nchars;
714 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
722 if (wmemcmp(type, L"$DATA", 5))
725 *stream_name_ret = raw_stream_name;
726 *stream_name_nchars_ret = sep - raw_stream_name;
731 build_stream_path(const wchar_t *path, size_t path_nchars,
732 const wchar_t *stream_name, size_t stream_name_nchars)
734 size_t stream_path_nchars;
735 wchar_t *stream_path;
738 stream_path_nchars = path_nchars;
739 if (stream_name_nchars)
740 stream_path_nchars += 1 + stream_name_nchars;
742 stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
744 p = wmempcpy(stream_path, path, path_nchars);
745 if (stream_name_nchars) {
747 p = wmempcpy(p, stream_name, stream_name_nchars);
755 winnt_scan_stream(const wchar_t *path, size_t path_nchars,
756 const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
758 struct wim_inode *inode, struct list_head *unhashed_streams)
760 const wchar_t *stream_name;
761 size_t stream_name_nchars;
762 struct wim_ads_entry *ads_entry;
763 wchar_t *stream_path;
764 struct wim_lookup_table_entry *lte;
767 /* Given the raw stream name (which is something like
768 * :streamname:$DATA), extract just the stream name part.
769 * Ignore any non-$DATA streams. */
770 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
771 &stream_name, &stream_name_nchars))
774 /* If this is a named stream, allocate an ADS entry for it. */
775 if (stream_name_nchars) {
776 ads_entry = inode_add_ads_utf16le(inode, stream_name,
780 return WIMLIB_ERR_NOMEM;
785 /* If the stream is empty, no lookup table entry is needed. */
786 if (stream_size == 0)
789 /* Build the path to the stream. For unnamed streams, this is simply
790 * the path to the file. For named streams, this is the path to the
791 * file, followed by a colon, followed by the stream name. */
792 stream_path = build_stream_path(path, path_nchars,
793 stream_name, stream_name_nchars);
795 return WIMLIB_ERR_NOMEM;
797 /* Set up the lookup table entry for the stream. */
798 lte = new_lookup_table_entry();
801 return WIMLIB_ERR_NOMEM;
803 lte->file_on_disk = stream_path;
804 lte->resource_location = RESOURCE_IN_WINNT_FILE_ON_DISK;
805 lte->size = stream_size;
806 if ((inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) && !ads_entry) {
807 /* Special case for encrypted file. */
809 /* OpenEncryptedFileRaw() expects Win32 name, not NT name.
810 * Change \??\ into \\?\ */
811 lte->file_on_disk[1] = L'\\';
812 wimlib_assert(!wmemcmp(lte->file_on_disk, L"\\\\?\\", 4));
817 ret = win32_get_encrypted_file_size(lte->file_on_disk,
820 free_lookup_table_entry(lte);
823 lte->size = encrypted_size;
824 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
828 stream_id = ads_entry->stream_id;
829 ads_entry->lte = lte;
834 add_unhashed_stream(lte, inode, stream_id, unhashed_streams);
839 * Load information about the streams of an open file into a WIM inode.
841 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
842 * and FindNextStream(). This is done for two reasons:
844 * - FindFirstStream() opens its own handle to the file or directory and
845 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
846 * causing access denied errors on certain files (even when running as the
848 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
849 * and later, whereas the stream support in NtQueryInformationFile() was
850 * already present in Windows XP.
853 winnt_scan_streams(HANDLE *hFile_p, const wchar_t *path, size_t path_nchars,
854 struct wim_inode *inode, struct list_head *unhashed_streams,
855 u64 file_size, u32 vol_flags)
858 u8 _buf[1024] _aligned_attribute(8);
861 IO_STATUS_BLOCK iosb;
863 const FILE_STREAM_INFORMATION *info;
866 bufsize = sizeof(_buf);
868 if (!(vol_flags & FILE_NAMED_STREAMS))
871 /* Get a buffer containing the stream information. */
872 while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(*hFile_p,
876 FileStreamInformation)))
880 case STATUS_BUFFER_OVERFLOW:
886 newbuf = MALLOC(bufsize);
888 newbuf = REALLOC(buf, bufsize);
890 ret = WIMLIB_ERR_NOMEM;
896 case STATUS_NOT_IMPLEMENTED:
897 case STATUS_NOT_SUPPORTED:
898 case STATUS_INVALID_INFO_CLASS:
901 set_errno_from_nt_status(status);
902 ERROR_WITH_ERRNO("\"%ls\": Failed to query stream "
903 "information (status=0x%08"PRIx32")",
904 printable_path(path), (u32)status);
905 ret = WIMLIB_ERR_READ;
910 if (iosb.Information == 0) {
911 /* No stream information. */
916 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
917 /* OpenEncryptedFileRaw() seems to fail with
918 * ERROR_SHARING_VIOLATION if there are any handles opened to
920 (*func_NtClose)(*hFile_p);
921 *hFile_p = INVALID_HANDLE_VALUE;
924 /* Parse one or more stream information structures. */
925 info = (const FILE_STREAM_INFORMATION *)buf;
927 /* Load the stream information. */
928 ret = winnt_scan_stream(path, path_nchars,
930 info->StreamNameLength / 2,
931 info->StreamSize.QuadPart,
932 inode, unhashed_streams);
936 if (info->NextEntryOffset == 0) {
937 /* No more stream information. */
940 /* Advance to next stream information. */
941 info = (const FILE_STREAM_INFORMATION *)
942 ((const u8 *)info + info->NextEntryOffset);
948 /* The volume does not support named streams. Only capture the unnamed
950 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
951 FILE_ATTRIBUTE_REPARSE_POINT))
957 ret = winnt_scan_stream(path, path_nchars, L"::$DATA", 7,
958 file_size, inode, unhashed_streams);
960 /* Free buffer if allocated on heap. */
961 if (unlikely(buf != _buf))
967 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
970 size_t full_path_nchars,
971 const wchar_t *filename,
972 size_t filename_nchars,
973 struct add_image_params *params,
974 struct winnt_scan_stats *stats,
977 struct wim_dentry *root = NULL;
978 struct wim_inode *inode = NULL;
979 HANDLE h = INVALID_HANDLE_VALUE;
982 FILE_ALL_INFORMATION file_info;
987 if (should_exclude_path(full_path + params->capture_root_nchars,
988 full_path_nchars - params->capture_root_nchars,
996 status = winnt_openat(cur_dir,
997 (cur_dir ? filename : full_path),
998 (cur_dir ? filename_nchars : full_path_nchars),
1000 FILE_READ_ATTRIBUTES |
1002 ACCESS_SYSTEM_SECURITY |
1005 if (unlikely(!NT_SUCCESS(status))) {
1006 set_errno_from_nt_status(status);
1007 ERROR_WITH_ERRNO("\"%ls\": Can't open file "
1008 "(status=0x%08"PRIx32")",
1009 printable_path(full_path), (u32)status);
1010 ret = WIMLIB_ERR_OPEN;
1014 /* Get information about the file. */
1016 IO_STATUS_BLOCK iosb;
1018 status = (*func_NtQueryInformationFile)(h, &iosb,
1021 FileAllInformation);
1023 if (unlikely(!NT_SUCCESS(status) &&
1024 status != STATUS_BUFFER_OVERFLOW))
1026 set_errno_from_nt_status(status);
1027 ERROR_WITH_ERRNO("\"%ls\": Can't get file information "
1028 "(status=0x%08"PRIx32")",
1029 printable_path(full_path), (u32)status);
1030 ret = WIMLIB_ERR_STAT;
1035 if (unlikely(!cur_dir)) {
1037 /* Root of tree being captured; get volume information. */
1039 FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1040 FILE_FS_VOLUME_INFORMATION vol_info;
1041 IO_STATUS_BLOCK iosb;
1043 /* Get volume flags */
1044 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1047 FileFsAttributeInformation);
1048 if (likely((NT_SUCCESS(status) ||
1049 (status == STATUS_BUFFER_OVERFLOW)) &&
1050 (iosb.Information >=
1051 offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1052 FileSystemAttributes) +
1053 sizeof(attr_info.FileSystemAttributes))))
1055 vol_flags = attr_info.FileSystemAttributes;
1057 set_errno_from_nt_status(status);
1058 WARNING_WITH_ERRNO("\"%ls\": Can't get volume attributes "
1059 "(status=0x%"PRIx32")",
1060 printable_path(full_path),
1065 /* Set inode number of root directory */
1066 params->capture_root_ino =
1067 file_info.InternalInformation.IndexNumber.QuadPart;
1069 /* Get volume ID. */
1070 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1073 FileFsVolumeInformation);
1074 if (likely((NT_SUCCESS(status) ||
1075 (status == STATUS_BUFFER_OVERFLOW)) &&
1076 (iosb.Information >=
1077 offsetof(FILE_FS_VOLUME_INFORMATION,
1078 VolumeSerialNumber) +
1079 sizeof(vol_info.VolumeSerialNumber))))
1081 params->capture_root_dev = vol_info.VolumeSerialNumber;
1083 set_errno_from_nt_status(status);
1084 WARNING_WITH_ERRNO("\"%ls\": Can't get volume ID "
1085 "(status=0x%08"PRIx32")",
1086 printable_path(full_path),
1088 params->capture_root_dev = 0;
1092 /* If this is a reparse point, read the reparse data. */
1093 if (unlikely(file_info.BasicInformation.FileAttributes &
1094 FILE_ATTRIBUTE_REPARSE_POINT))
1096 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1097 ret = winnt_get_reparse_data(h, full_path, params,
1100 /* WIMLIB_ERR_* (inverted) */
1102 ERROR_WITH_ERRNO("\"%ls\": Can't get reparse data",
1103 printable_path(full_path));
1105 } else if (ret & RP_FIXED) {
1107 } else if (ret == RP_EXCLUDED) {
1115 /* Create a WIM dentry with an associated inode, which may be shared.
1117 * However, we need to explicitly check for directories and files with
1118 * only 1 link and refuse to hard link them. This is because Windows
1119 * has a bug where it can return duplicate File IDs for files and
1120 * directories on the FAT filesystem. */
1121 ret = inode_table_new_dentry(params->inode_table,
1123 file_info.InternalInformation.IndexNumber.QuadPart,
1124 0, /* We don't follow mount points, so we
1125 currently don't need to get the
1126 volume ID / device number. */
1127 (file_info.StandardInformation.NumberOfLinks <= 1 ||
1128 (file_info.BasicInformation.FileAttributes &
1129 FILE_ATTRIBUTE_DIRECTORY)),
1134 /* Get the short (DOS) name of the file. */
1135 status = winnt_get_short_name(h, root);
1137 /* If we can't read the short filename for any reason other than
1138 * out-of-memory, just ignore the error and assume the file has no short
1139 * name. This shouldn't be an issue, since the short names are
1140 * essentially obsolete anyway. */
1141 if (unlikely(status == STATUS_NO_MEMORY)) {
1142 ret = WIMLIB_ERR_NOMEM;
1146 inode = root->d_inode;
1148 if (inode->i_nlink > 1) {
1149 /* Shared inode (hard link); skip reading per-inode information.
1155 inode->i_attributes = file_info.BasicInformation.FileAttributes;
1156 inode->i_creation_time = file_info.BasicInformation.CreationTime.QuadPart;
1157 inode->i_last_write_time = file_info.BasicInformation.LastWriteTime.QuadPart;
1158 inode->i_last_access_time = file_info.BasicInformation.LastAccessTime.QuadPart;
1159 inode->i_resolved = 1;
1161 /* Get the file's security descriptor, unless we are capturing in
1162 * NO_ACLS mode or the volume does not support security descriptors. */
1163 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1164 && (vol_flags & FILE_PERSISTENT_ACLS))
1166 status = winnt_get_security_descriptor(h, inode,
1167 params->sd_set, stats,
1169 if (!NT_SUCCESS(status)) {
1170 set_errno_from_nt_status(status);
1171 ERROR_WITH_ERRNO("\"%ls\": Can't read security "
1172 "descriptor (status=0x%08"PRIu32")",
1173 printable_path(full_path),
1175 ret = WIMLIB_ERR_STAT;
1180 /* Load information about the unnamed data stream and any named data
1182 ret = winnt_scan_streams(&h,
1186 params->unhashed_streams,
1187 file_info.StandardInformation.EndOfFile.QuadPart,
1192 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1194 /* Reparse point: set the reparse data (already read). */
1196 inode->i_not_rpfixed = not_rpfixed;
1197 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1198 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1199 params->lookup_table);
1202 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1204 /* Directory: recurse to children. */
1206 if (unlikely(h == INVALID_HANDLE_VALUE)) {
1207 /* Re-open handle that was closed to read raw encrypted
1209 status = winnt_openat(cur_dir,
1211 filename : full_path),
1213 filename_nchars : full_path_nchars),
1214 FILE_LIST_DIRECTORY | SYNCHRONIZE,
1216 if (!NT_SUCCESS(status)) {
1217 set_errno_from_nt_status(status);
1218 ERROR_WITH_ERRNO("\"%ls\": Can't re-open file "
1219 "(status=0x%08"PRIx32")",
1220 printable_path(full_path),
1222 ret = WIMLIB_ERR_OPEN;
1226 ret = winnt_recurse_directory(h,
1238 params->progress.scan.cur_path = printable_path(full_path);
1240 do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1242 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1244 if (likely(h != INVALID_HANDLE_VALUE))
1246 if (likely(ret == 0))
1249 free_dentry_tree(root, params->lookup_table);
1254 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_stats *stats)
1256 if (likely(stats->num_get_sacl_priv_notheld == 0 &&
1257 stats->num_get_sd_access_denied == 0))
1260 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1261 if (stats->num_get_sacl_priv_notheld != 0) {
1262 WARNING("- Could not capture SACL (System Access Control List)\n"
1263 " on %lu files or directories.",
1264 stats->num_get_sacl_priv_notheld);
1266 if (stats->num_get_sd_access_denied != 0) {
1267 WARNING("- Could not capture security descriptor at all\n"
1268 " on %lu files or directories.",
1269 stats->num_get_sd_access_denied);
1271 WARNING("To fully capture all security descriptors, run the program\n"
1272 " with Administrator rights.");
1275 #define WINDOWS_NT_MAX_PATH 32768
1277 /* Win32 version of capturing a directory tree. */
1279 win32_build_dentry_tree(struct wim_dentry **root_ret,
1280 const wchar_t *root_disk_path,
1281 struct add_image_params *params)
1287 struct winnt_scan_stats stats;
1289 /* WARNING: There is no check for overflow later when this buffer is
1290 * being used! But it's as long as the maximum path length understood
1291 * by Windows NT (which is NOT the same as MAX_PATH). */
1292 path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1294 return WIMLIB_ERR_NOMEM;
1296 /* Translate into full path. */
1297 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 3,
1300 if (unlikely(dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 3)) {
1301 ERROR("Can't get full path name for \"%ls\"", root_disk_path);
1302 return WIMLIB_ERR_UNSUPPORTED;
1305 /* Add \??\ prefix to form the NT namespace path. */
1306 wmemcpy(path, L"\\??\\", 4);
1307 path_nchars = dret + 4;
1309 /* Strip trailing slashes. If we don't do this, we may create a path
1310 * with multiple consecutive backslashes, which for some reason causes
1311 * Windows to report that the file cannot be found. */
1312 while (unlikely(path[path_nchars - 1] == L'\\' &&
1313 path[path_nchars - 2] != L':'))
1314 path[--path_nchars] = L'\0';
1316 params->capture_root_nchars = path_nchars;
1318 memset(&stats, 0, sizeof(stats));
1320 ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
1321 path, path_nchars, L"", 0,
1325 winnt_do_scan_warnings(root_disk_path, &stats);
1329 #endif /* __WIN32__ */