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);
285 requestedInformation = DACL_SECURITY_INFORMATION |
286 SACL_SECURITY_INFORMATION |
287 OWNER_SECURITY_INFORMATION |
288 GROUP_SECURITY_INFORMATION;
290 bufsize = sizeof(_buf);
293 * We need the file's security descriptor in
294 * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
295 * opened with as many relevant permissions as possible. At this point,
296 * on Windows there are a number of options for reading a file's
297 * security descriptor:
299 * GetFileSecurity(): This takes in a path and returns the
300 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle,
301 * not ours, and the handle created internally doesn't specify
302 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied
303 * errors on some files and directories, even when running as the
306 * GetSecurityInfo(): This takes in a handle and returns the security
307 * descriptor split into a bunch of different parts. This should work,
308 * but it's dumb because we have to put the security descriptor back
311 * BackupRead(): This can read the security descriptor, but this is a
312 * difficult-to-use API, probably only works as the Administrator, and
313 * the format of the returned data is not well documented.
315 * NtQuerySecurityObject(): This is exactly what we need, as it takes
316 * in a handle and returns the security descriptor in
317 * SECURITY_DESCRIPTOR_RELATIVE format. Only problem is that it's a
318 * ntdll function and therefore not officially part of the Win32 API.
321 while (!(NT_SUCCESS(status = (*func_NtQuerySecurityObject)(h,
322 requestedInformation,
323 (PSECURITY_DESCRIPTOR)buf,
328 case STATUS_BUFFER_TOO_SMALL:
329 wimlib_assert(buf == _buf);
330 buf = MALLOC(len_needed);
332 return STATUS_NO_MEMORY;
333 bufsize = len_needed;
335 case STATUS_PRIVILEGE_NOT_HELD:
336 case STATUS_ACCESS_DENIED:
337 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
339 /* Permission denied in STRICT_ACLS mode, or
343 if (requestedInformation & SACL_SECURITY_INFORMATION) {
344 /* Try again without the SACL. */
345 stats->num_get_sacl_priv_notheld++;
346 requestedInformation &= ~SACL_SECURITY_INFORMATION;
349 /* Fake success (useful when capturing as
350 * non-Administrator). */
351 stats->num_get_sd_access_denied++;
352 status = STATUS_SUCCESS;
357 /* Add the security descriptor to the WIM image, and save its ID in
359 inode->i_security_id = sd_set_add_sd(sd_set, buf, len_needed);
360 if (unlikely(inode->i_security_id < 0))
361 status = STATUS_NO_MEMORY;
363 if (unlikely(buf != _buf))
369 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
372 size_t full_path_nchars,
373 const wchar_t *filename,
374 size_t filename_nchars,
375 struct add_image_params *params,
376 struct winnt_scan_stats *stats,
380 winnt_recurse_directory(HANDLE h,
382 size_t full_path_nchars,
383 struct wim_dentry *parent,
384 struct add_image_params *params,
385 struct winnt_scan_stats *stats,
389 const size_t bufsize = 8192;
390 IO_STATUS_BLOCK iosb;
394 buf = MALLOC(bufsize);
396 return WIMLIB_ERR_NOMEM;
398 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
399 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
401 while (NT_SUCCESS(status = (*func_NtQueryDirectoryFile)(h, NULL, NULL, NULL,
403 FileNamesInformation,
404 FALSE, NULL, FALSE)))
406 const FILE_NAMES_INFORMATION *info = buf;
408 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
409 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
410 info->FileName[1] == L'.'))
413 struct wim_dentry *child;
415 p = full_path + full_path_nchars;
417 p = wmempcpy(p, info->FileName,
418 info->FileNameLength / 2);
421 ret = winnt_build_dentry_tree_recursive(
426 full_path + full_path_nchars + 1,
427 info->FileNameLength / 2,
432 full_path[full_path_nchars] = L'\0';
437 dentry_add_child(parent, child);
439 if (info->NextEntryOffset == 0)
441 info = (const FILE_NAMES_INFORMATION *)
442 ((const u8 *)info + info->NextEntryOffset);
446 if (unlikely(status != STATUS_NO_MORE_FILES)) {
447 set_errno_from_nt_status(status);
448 ERROR_WITH_ERRNO("\"%ls\": Can't read directory "
449 "(status=0x%08"PRIx32")",
450 printable_path(full_path), (u32)status);
451 ret = WIMLIB_ERR_READ;
458 /* Reparse point fixup status code */
460 /* Reparse point corresponded to an absolute symbolic link or junction
461 * point that pointed outside the directory tree being captured, and
462 * therefore was excluded. */
465 /* Reparse point was not fixed as it was either a relative symbolic
466 * link, a mount point, or something else we could not understand. */
469 /* Reparse point corresponded to an absolute symbolic link or junction
470 * point that pointed inside the directory tree being captured, where
471 * the target was specified by a "full" \??\ prefixed path, and
472 * therefore was fixed to be relative to the root of the directory tree
474 RP_FIXED_FULLPATH = 0x2,
476 /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
477 * have the \??\ prefix. It may have begun with a drive letter though.
479 RP_FIXED_ABSPATH = 0x4,
481 /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
482 RP_FIXED = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
485 /* Given the "substitute name" target of a Windows reparse point, try doing a
486 * fixup where we change it to be absolute relative to the root of the directory
487 * tree being captured.
489 * Note that this is only executed when WIMLIB_ADD_FLAG_RPFIX has been
492 * @capture_root_ino and @capture_root_dev indicate the inode number and device
493 * of the root of the directory tree being captured. They are meant to identify
494 * this directory (as an alternative to its actual path, which could potentially
495 * be reached via multiple destinations due to other symbolic links). This may
496 * not work properly on FAT, which doesn't seem to supply proper inode numbers
497 * or file IDs. However, FAT doesn't support reparse points so this function
498 * wouldn't even be called anyway.
500 static enum rp_status
501 winnt_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
502 u64 capture_root_ino, u64 capture_root_dev,
505 u16 target_nchars = *target_nbytes_p / 2;
506 size_t stripped_chars;
507 wchar_t *orig_target;
510 ret = parse_substitute_name(target, *target_nbytes_p, rptag);
513 stripped_chars = ret;
516 target[target_nchars] = L'\0';
517 orig_target = target;
518 target = capture_fixup_absolute_symlink(target + stripped_chars,
519 capture_root_ino, capture_root_dev);
522 target_nchars = wcslen(target);
523 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
524 *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
526 return RP_FIXED_FULLPATH;
528 return RP_FIXED_ABSPATH;
531 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
534 winnt_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
535 u64 capture_root_ino, u64 capture_root_dev,
536 const wchar_t *path, struct add_image_params *params)
538 struct reparse_data rpdata;
540 enum rp_status rp_status;
542 ret = parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata);
546 rp_status = winnt_capture_maybe_rpfix_target(rpdata.substitute_name,
547 &rpdata.substitute_name_nbytes,
550 le32_to_cpu(*(le32*)rpbuf));
551 if (rp_status & RP_FIXED) {
552 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
553 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
554 wmemcpy(substitute_name_copy, rpdata.substitute_name,
555 rpdata.substitute_name_nbytes / 2);
556 rpdata.substitute_name = substitute_name_copy;
557 rpdata.print_name = substitute_name_copy;
558 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
559 if (rp_status == RP_FIXED_FULLPATH) {
560 /* "full path", meaning \??\ prefixed. We should not
561 * include this prefix in the print name, as it is
562 * apparently meant for the filesystem driver only. */
563 rpdata.print_name += 4;
564 rpdata.print_name_nbytes -= 8;
566 ret = make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
572 if (rp_status == RP_EXCLUDED) {
573 /* Ignoring absolute symbolic link or junction point
574 * that points out of the tree to be captured. */
575 size_t print_name_nchars = rpdata.print_name_nbytes / 2;
576 wchar_t print_name0[print_name_nchars + 1];
577 print_name0[print_name_nchars] = L'\0';
578 wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
580 params->progress.scan.cur_path = printable_path(path);
581 params->progress.scan.symlink_target = print_name0;
582 do_capture_progress(params,
583 WIMLIB_SCAN_DENTRY_EXCLUDED_SYMLINK,
592 * Loads the reparse point data from a reparse point into memory, optionally
593 * fixing the targets of absolute symbolic links and junction points to be
594 * relative to the root of capture.
596 * @h: Open handle to the reparse point.
597 * @path: Path to the reparse point file.
598 * @params: Additional parameters, including whether to do reparse point fixups
600 * @rpbuf: Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
601 * the reparse point buffer will be loaded.
602 * @rpbuflen_ret: On success, the length of the reparse point buffer in bytes
603 * is written to this location.
606 * On success, returns an `enum rp_status' value that indicates if and/or
607 * how the reparse point fixup was done.
609 * On failure, returns a negative value that is a negated WIMLIB_ERR_*
613 winnt_get_reparse_data(HANDLE h, const wchar_t *path,
614 struct add_image_params *params,
615 u8 *rpbuf, u16 *rpbuflen_ret)
622 if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
623 NULL, /* "Not used with this operation; set to NULL" */
624 0, /* "Not used with this operation; set to 0" */
625 rpbuf, /* "A pointer to a buffer that
626 receives the reparse point data */
627 REPARSE_POINT_MAX_SIZE, /* "The size of the output
632 set_errno_from_GetLastError();
633 return -WIMLIB_ERR_READ;
636 if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
638 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
641 rpbuflen = bytesReturned;
642 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
643 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
644 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
645 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
647 /* Try doing reparse point fixup */
648 ret = winnt_capture_try_rpfix(rpbuf,
650 params->capture_root_ino,
651 params->capture_root_dev,
657 *rpbuflen_ret = rpbuflen;
662 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
665 *(u64*)_size_ret += len;
666 return ERROR_SUCCESS;
670 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
676 err = OpenEncryptedFileRaw(path, 0, &file_ctx);
677 if (err != ERROR_SUCCESS) {
678 set_errno_from_win32_error(err);
679 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
680 "for raw read", printable_path(path));
681 return WIMLIB_ERR_OPEN;
684 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
686 if (err != ERROR_SUCCESS) {
687 set_errno_from_win32_error(err);
688 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
689 "\"%ls\"", printable_path(path));
690 ret = WIMLIB_ERR_READ;
694 CloseEncryptedFileRaw(file_ctx);
699 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
700 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
702 const wchar_t *sep, *type, *end;
704 /* The stream name should be returned as :NAME:TYPE */
705 if (raw_stream_name_nchars < 1)
707 if (raw_stream_name[0] != L':')
711 raw_stream_name_nchars--;
713 end = raw_stream_name + raw_stream_name_nchars;
715 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
723 if (wmemcmp(type, L"$DATA", 5))
726 *stream_name_ret = raw_stream_name;
727 *stream_name_nchars_ret = sep - raw_stream_name;
732 build_stream_path(const wchar_t *path, size_t path_nchars,
733 const wchar_t *stream_name, size_t stream_name_nchars)
735 size_t stream_path_nchars;
736 wchar_t *stream_path;
739 stream_path_nchars = path_nchars;
740 if (stream_name_nchars)
741 stream_path_nchars += 1 + stream_name_nchars;
743 stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
745 p = wmempcpy(stream_path, path, path_nchars);
746 if (stream_name_nchars) {
748 p = wmempcpy(p, stream_name, stream_name_nchars);
756 winnt_scan_stream(const wchar_t *path, size_t path_nchars,
757 const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
759 struct wim_inode *inode, struct list_head *unhashed_streams)
761 const wchar_t *stream_name;
762 size_t stream_name_nchars;
763 struct wim_ads_entry *ads_entry;
764 wchar_t *stream_path;
765 struct wim_lookup_table_entry *lte;
768 /* Given the raw stream name (which is something like
769 * :streamname:$DATA), extract just the stream name part.
770 * Ignore any non-$DATA streams. */
771 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
772 &stream_name, &stream_name_nchars))
775 /* If this is a named stream, allocate an ADS entry for it. */
776 if (stream_name_nchars) {
777 ads_entry = inode_add_ads_utf16le(inode, stream_name,
781 return WIMLIB_ERR_NOMEM;
786 /* If the stream is empty, no lookup table entry is needed. */
787 if (stream_size == 0)
790 /* Build the path to the stream. For unnamed streams, this is simply
791 * the path to the file. For named streams, this is the path to the
792 * file, followed by a colon, followed by the stream name. */
793 stream_path = build_stream_path(path, path_nchars,
794 stream_name, stream_name_nchars);
796 return WIMLIB_ERR_NOMEM;
798 /* Set up the lookup table entry for the stream. */
799 lte = new_lookup_table_entry();
802 return WIMLIB_ERR_NOMEM;
804 lte->file_on_disk = stream_path;
805 lte->resource_location = RESOURCE_IN_WINNT_FILE_ON_DISK;
806 lte->size = stream_size;
807 if ((inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) && !ads_entry) {
808 /* Special case for encrypted file. */
810 /* OpenEncryptedFileRaw() expects Win32 name, not NT name.
811 * Change \??\ into \\?\ */
812 lte->file_on_disk[1] = L'\\';
813 wimlib_assert(!wmemcmp(lte->file_on_disk, L"\\\\?\\", 4));
818 ret = win32_get_encrypted_file_size(lte->file_on_disk,
821 free_lookup_table_entry(lte);
824 lte->size = encrypted_size;
825 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
829 stream_id = ads_entry->stream_id;
830 ads_entry->lte = lte;
835 add_unhashed_stream(lte, inode, stream_id, unhashed_streams);
840 * Load information about the streams of an open file into a WIM inode.
842 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
843 * and FindNextStream(). This is done for two reasons:
845 * - FindFirstStream() opens its own handle to the file or directory and
846 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
847 * causing access denied errors on certain files (even when running as the
849 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
850 * and later, whereas the stream support in NtQueryInformationFile() was
851 * already present in Windows XP.
854 winnt_scan_streams(HANDLE *hFile_p, const wchar_t *path, size_t path_nchars,
855 struct wim_inode *inode, struct list_head *unhashed_streams,
856 u64 file_size, u32 vol_flags)
859 u8 _buf[1024] _aligned_attribute(8);
862 IO_STATUS_BLOCK iosb;
864 const FILE_STREAM_INFORMATION *info;
867 bufsize = sizeof(_buf);
869 if (!(vol_flags & FILE_NAMED_STREAMS))
872 /* Get a buffer containing the stream information. */
873 while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(*hFile_p,
877 FileStreamInformation)))
881 case STATUS_BUFFER_OVERFLOW:
887 newbuf = MALLOC(bufsize);
889 newbuf = REALLOC(buf, bufsize);
891 ret = WIMLIB_ERR_NOMEM;
897 case STATUS_NOT_IMPLEMENTED:
898 case STATUS_NOT_SUPPORTED:
899 case STATUS_INVALID_INFO_CLASS:
902 set_errno_from_nt_status(status);
903 ERROR_WITH_ERRNO("\"%ls\": Failed to query stream "
904 "information (status=0x%08"PRIx32")",
905 printable_path(path), (u32)status);
906 ret = WIMLIB_ERR_READ;
911 if (iosb.Information == 0) {
912 /* No stream information. */
917 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
918 /* OpenEncryptedFileRaw() seems to fail with
919 * ERROR_SHARING_VIOLATION if there are any handles opened to
921 (*func_NtClose)(*hFile_p);
922 *hFile_p = INVALID_HANDLE_VALUE;
925 /* Parse one or more stream information structures. */
926 info = (const FILE_STREAM_INFORMATION *)buf;
928 /* Load the stream information. */
929 ret = winnt_scan_stream(path, path_nchars,
931 info->StreamNameLength / 2,
932 info->StreamSize.QuadPart,
933 inode, unhashed_streams);
937 if (info->NextEntryOffset == 0) {
938 /* No more stream information. */
941 /* Advance to next stream information. */
942 info = (const FILE_STREAM_INFORMATION *)
943 ((const u8 *)info + info->NextEntryOffset);
949 /* The volume does not support named streams. Only capture the unnamed
951 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
952 FILE_ATTRIBUTE_REPARSE_POINT))
958 ret = winnt_scan_stream(path, path_nchars, L"::$DATA", 7,
959 file_size, inode, unhashed_streams);
961 /* Free buffer if allocated on heap. */
962 if (unlikely(buf != _buf))
968 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
971 size_t full_path_nchars,
972 const wchar_t *filename,
973 size_t filename_nchars,
974 struct add_image_params *params,
975 struct winnt_scan_stats *stats,
978 struct wim_dentry *root = NULL;
979 struct wim_inode *inode = NULL;
980 HANDLE h = INVALID_HANDLE_VALUE;
983 FILE_ALL_INFORMATION file_info;
988 if (should_exclude_path(full_path + params->capture_root_nchars,
989 full_path_nchars - params->capture_root_nchars,
997 status = winnt_openat(cur_dir,
998 (cur_dir ? filename : full_path),
999 (cur_dir ? filename_nchars : full_path_nchars),
1001 FILE_READ_ATTRIBUTES |
1003 ACCESS_SYSTEM_SECURITY |
1006 if (unlikely(!NT_SUCCESS(status))) {
1007 set_errno_from_nt_status(status);
1008 ERROR_WITH_ERRNO("\"%ls\": Can't open file "
1009 "(status=0x%08"PRIx32")",
1010 printable_path(full_path), (u32)status);
1011 ret = WIMLIB_ERR_OPEN;
1015 /* Get information about the file. */
1017 IO_STATUS_BLOCK iosb;
1019 status = (*func_NtQueryInformationFile)(h, &iosb,
1022 FileAllInformation);
1024 if (unlikely(!NT_SUCCESS(status) &&
1025 status != STATUS_BUFFER_OVERFLOW))
1027 set_errno_from_nt_status(status);
1028 ERROR_WITH_ERRNO("\"%ls\": Can't get file information "
1029 "(status=0x%08"PRIx32")",
1030 printable_path(full_path), (u32)status);
1031 ret = WIMLIB_ERR_STAT;
1036 if (unlikely(!cur_dir)) {
1038 /* Root of tree being captured; get volume information. */
1040 FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1041 FILE_FS_VOLUME_INFORMATION vol_info;
1042 IO_STATUS_BLOCK iosb;
1044 /* Get volume flags */
1045 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1048 FileFsAttributeInformation);
1049 if (likely((NT_SUCCESS(status) ||
1050 (status == STATUS_BUFFER_OVERFLOW)) &&
1051 (iosb.Information >=
1052 offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1053 FileSystemAttributes) +
1054 sizeof(attr_info.FileSystemAttributes))))
1056 vol_flags = attr_info.FileSystemAttributes;
1058 set_errno_from_nt_status(status);
1059 WARNING_WITH_ERRNO("\"%ls\": Can't get volume attributes "
1060 "(status=0x%"PRIx32")",
1061 printable_path(full_path),
1066 /* Set inode number of root directory */
1067 params->capture_root_ino =
1068 file_info.InternalInformation.IndexNumber.QuadPart;
1070 /* Get volume ID. */
1071 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1074 FileFsVolumeInformation);
1075 if (likely((NT_SUCCESS(status) ||
1076 (status == STATUS_BUFFER_OVERFLOW)) &&
1077 (iosb.Information >=
1078 offsetof(FILE_FS_VOLUME_INFORMATION,
1079 VolumeSerialNumber) +
1080 sizeof(vol_info.VolumeSerialNumber))))
1082 params->capture_root_dev = vol_info.VolumeSerialNumber;
1084 set_errno_from_nt_status(status);
1085 WARNING_WITH_ERRNO("\"%ls\": Can't get volume ID "
1086 "(status=0x%08"PRIx32")",
1087 printable_path(full_path),
1089 params->capture_root_dev = 0;
1093 /* If this is a reparse point, read the reparse data. */
1094 if (unlikely(file_info.BasicInformation.FileAttributes &
1095 FILE_ATTRIBUTE_REPARSE_POINT))
1097 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1098 ret = winnt_get_reparse_data(h, full_path, params,
1101 /* WIMLIB_ERR_* (inverted) */
1103 ERROR_WITH_ERRNO("\"%ls\": Can't get reparse data",
1104 printable_path(full_path));
1106 } else if (ret & RP_FIXED) {
1108 } else if (ret == RP_EXCLUDED) {
1116 /* Create a WIM dentry with an associated inode, which may be shared.
1118 * However, we need to explicitly check for directories and files with
1119 * only 1 link and refuse to hard link them. This is because Windows
1120 * has a bug where it can return duplicate File IDs for files and
1121 * directories on the FAT filesystem. */
1122 ret = inode_table_new_dentry(params->inode_table,
1124 file_info.InternalInformation.IndexNumber.QuadPart,
1125 0, /* We don't follow mount points, so we
1126 currently don't need to get the
1127 volume ID / device number. */
1128 (file_info.StandardInformation.NumberOfLinks <= 1 ||
1129 (file_info.BasicInformation.FileAttributes &
1130 FILE_ATTRIBUTE_DIRECTORY)),
1135 /* Get the short (DOS) name of the file. */
1136 status = winnt_get_short_name(h, root);
1138 /* If we can't read the short filename for any reason other than
1139 * out-of-memory, just ignore the error and assume the file has no short
1140 * name. This shouldn't be an issue, since the short names are
1141 * essentially obsolete anyway. */
1142 if (unlikely(status == STATUS_NO_MEMORY)) {
1143 ret = WIMLIB_ERR_NOMEM;
1147 inode = root->d_inode;
1149 if (inode->i_nlink > 1) {
1150 /* Shared inode (hard link); skip reading per-inode information.
1156 inode->i_attributes = file_info.BasicInformation.FileAttributes;
1157 inode->i_creation_time = file_info.BasicInformation.CreationTime.QuadPart;
1158 inode->i_last_write_time = file_info.BasicInformation.LastWriteTime.QuadPart;
1159 inode->i_last_access_time = file_info.BasicInformation.LastAccessTime.QuadPart;
1160 inode->i_resolved = 1;
1162 /* Get the file's security descriptor, unless we are capturing in
1163 * NO_ACLS mode or the volume does not support security descriptors. */
1164 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1165 && (vol_flags & FILE_PERSISTENT_ACLS))
1167 status = winnt_get_security_descriptor(h, inode,
1168 params->sd_set, stats,
1170 if (!NT_SUCCESS(status)) {
1171 set_errno_from_nt_status(status);
1172 ERROR_WITH_ERRNO("\"%ls\": Can't read security "
1173 "descriptor (status=0x%08"PRIu32")",
1174 printable_path(full_path),
1176 ret = WIMLIB_ERR_STAT;
1181 /* Load information about the unnamed data stream and any named data
1183 ret = winnt_scan_streams(&h,
1187 params->unhashed_streams,
1188 file_info.StandardInformation.EndOfFile.QuadPart,
1193 if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1195 /* Reparse point: set the reparse data (already read). */
1197 inode->i_not_rpfixed = not_rpfixed;
1198 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1199 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1200 params->lookup_table);
1203 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1205 /* Directory: recurse to children. */
1207 if (unlikely(h == INVALID_HANDLE_VALUE)) {
1208 /* Re-open handle that was closed to read raw encrypted
1210 status = winnt_openat(cur_dir,
1212 filename : full_path),
1214 filename_nchars : full_path_nchars),
1215 FILE_LIST_DIRECTORY | SYNCHRONIZE,
1217 if (!NT_SUCCESS(status)) {
1218 set_errno_from_nt_status(status);
1219 ERROR_WITH_ERRNO("\"%ls\": Can't re-open file "
1220 "(status=0x%08"PRIx32")",
1221 printable_path(full_path),
1223 ret = WIMLIB_ERR_OPEN;
1227 ret = winnt_recurse_directory(h,
1239 params->progress.scan.cur_path = printable_path(full_path);
1241 do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1243 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1245 if (likely(h != INVALID_HANDLE_VALUE))
1247 if (likely(ret == 0))
1250 free_dentry_tree(root, params->lookup_table);
1255 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_stats *stats)
1257 if (likely(stats->num_get_sacl_priv_notheld == 0 &&
1258 stats->num_get_sd_access_denied == 0))
1261 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1262 if (stats->num_get_sacl_priv_notheld != 0) {
1263 WARNING("- Could not capture SACL (System Access Control List)\n"
1264 " on %lu files or directories.",
1265 stats->num_get_sacl_priv_notheld);
1267 if (stats->num_get_sd_access_denied != 0) {
1268 WARNING("- Could not capture security descriptor at all\n"
1269 " on %lu files or directories.",
1270 stats->num_get_sd_access_denied);
1272 WARNING("To fully capture all security descriptors, run the program\n"
1273 " with Administrator rights.");
1276 #define WINDOWS_NT_MAX_PATH 32768
1278 /* Win32 version of capturing a directory tree. */
1280 win32_build_dentry_tree(struct wim_dentry **root_ret,
1281 const wchar_t *root_disk_path,
1282 struct add_image_params *params)
1288 struct winnt_scan_stats stats;
1290 /* WARNING: There is no check for overflow later when this buffer is
1291 * being used! But it's as long as the maximum path length understood
1292 * by Windows NT (which is NOT the same as MAX_PATH). */
1293 path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1295 return WIMLIB_ERR_NOMEM;
1297 /* Translate into full path. */
1298 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 3,
1301 if (unlikely(dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 3)) {
1302 ERROR("Can't get full path name for \"%ls\"", root_disk_path);
1303 return WIMLIB_ERR_UNSUPPORTED;
1306 /* Add \??\ prefix to form the NT namespace path. */
1307 wmemcpy(path, L"\\??\\", 4);
1308 path_nchars = dret + 4;
1310 /* Strip trailing slashes. If we don't do this, we may create a path
1311 * with multiple consecutive backslashes, which for some reason causes
1312 * Windows to report that the file cannot be found. */
1313 while (unlikely(path[path_nchars - 1] == L'\\' &&
1314 path[path_nchars - 2] != L':'))
1315 path[--path_nchars] = L'\0';
1317 params->capture_root_nchars = path_nchars;
1319 memset(&stats, 0, sizeof(stats));
1321 ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
1322 path, path_nchars, L"", 0,
1326 winnt_do_scan_warnings(root_disk_path, &stats);
1330 #endif /* __WIN32__ */