2 * win32_capture.c - Windows-specific code for capturing files into a WIM image.
6 * Copyright (C) 2013 Eric Biggers
8 * This file is part of wimlib, a library for working with WIM files.
10 * wimlib is free software; you can redistribute it and/or modify it under the
11 * terms of the GNU General Public License as published by the Free
12 * Software Foundation; either version 3 of the License, or (at your option)
15 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 * A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with wimlib; if not, see http://www.gnu.org/licenses/.
30 #include "wimlib/win32_common.h"
32 #include "wimlib/capture.h"
33 #include "wimlib/endianness.h"
34 #include "wimlib/error.h"
35 #include "wimlib/lookup_table.h"
36 #include "wimlib/paths.h"
37 #include "wimlib/reparse.h"
40 # include <winternl.h>
41 # include <ntstatus.h>
44 NtQuerySecurityObject(HANDLE handle,
45 SECURITY_INFORMATION SecurityInformation,
46 PSECURITY_DESCRIPTOR SecurityDescriptor,
50 NtQueryDirectoryFile(HANDLE FileHandle,
52 PIO_APC_ROUTINE ApcRoutine,
54 PIO_STATUS_BLOCK IoStatusBlock,
55 PVOID FileInformation,
57 FILE_INFORMATION_CLASS FileInformationClass,
58 BOOLEAN ReturnSingleEntry,
59 PUNICODE_STRING FileName,
63 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
64 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
65 #define MAX_CAPTURE_LONG_PATH_WARNINGS 5
67 struct win32_capture_state {
68 unsigned long num_get_sd_access_denied;
69 unsigned long num_get_sacl_priv_notheld;
70 unsigned long num_long_path_warnings;
74 static const wchar_t *capture_access_denied_msg =
75 L" If you are not running this program as the administrator, you may\n"
76 " need to do so, so that all data and metadata can be backed up.\n"
77 " Otherwise, there may be no way to access the desired data or\n"
78 " metadata without taking ownership of the file or directory.\n"
82 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
84 consume_data_callback_t cb,
93 HANDLE hFile = win32_open_file_data_only(lte->file_on_disk);
94 if (hFile == INVALID_HANDLE_VALUE) {
96 ERROR("Failed to open \"%ls\"", lte->file_on_disk);
98 return WIMLIB_ERR_OPEN;
102 out_buf = alloca(WIM_CHUNK_SIZE);
104 out_buf = ctx_or_buf;
106 bytes_remaining = size;
107 while (bytes_remaining) {
108 DWORD bytesToRead, bytesRead;
110 bytesToRead = min(WIM_CHUNK_SIZE, bytes_remaining);
111 if (!ReadFile(hFile, out_buf, bytesToRead, &bytesRead, NULL) ||
112 bytesRead != bytesToRead)
114 err = GetLastError();
115 ERROR("Failed to read data from \"%ls\"", lte->file_on_disk);
117 ret = WIMLIB_ERR_READ;
120 bytes_remaining -= bytesRead;
122 ret = (*cb)(out_buf, bytesRead, ctx_or_buf);
126 out_buf += bytesRead;
133 struct win32_encrypted_read_ctx {
134 consume_data_callback_t read_prefix_cb;
135 void *read_prefix_ctx_or_buf;
143 win32_encrypted_export_cb(unsigned char *_data, void *_ctx, unsigned long len)
145 const void *data = _data;
146 struct win32_encrypted_read_ctx *ctx = _ctx;
149 DEBUG("len = %lu", len);
150 if (ctx->read_prefix_cb) {
151 /* The length of the buffer passed to the ReadEncryptedFileRaw()
152 * export callback is undocumented, so we assume it may be of
154 size_t bytes_to_buffer = min(ctx->bytes_remaining - ctx->buf_filled,
156 while (bytes_to_buffer) {
157 size_t bytes_to_copy_to_buf =
158 min(bytes_to_buffer, WIM_CHUNK_SIZE - ctx->buf_filled);
160 memcpy(ctx->buf + ctx->buf_filled, data,
161 bytes_to_copy_to_buf);
162 ctx->buf_filled += bytes_to_copy_to_buf;
163 data += bytes_to_copy_to_buf;
164 bytes_to_buffer -= bytes_to_copy_to_buf;
166 if (ctx->buf_filled == WIM_CHUNK_SIZE ||
167 ctx->buf_filled == ctx->bytes_remaining)
169 ret = (*ctx->read_prefix_cb)(ctx->buf,
171 ctx->read_prefix_ctx_or_buf);
173 ctx->wimlib_err_code = ret;
174 /* Shouldn't matter what error code is returned
175 * here, as long as it isn't ERROR_SUCCESS. */
176 return ERROR_READ_FAULT;
178 ctx->bytes_remaining -= ctx->buf_filled;
183 size_t len_to_copy = min(len, ctx->bytes_remaining);
184 ctx->read_prefix_ctx_or_buf = mempcpy(ctx->read_prefix_ctx_or_buf,
187 ctx->bytes_remaining -= len_to_copy;
189 return ERROR_SUCCESS;
193 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
195 consume_data_callback_t cb,
199 struct win32_encrypted_read_ctx export_ctx;
204 DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
205 size, lte->file_on_disk);
207 export_ctx.read_prefix_cb = cb;
208 export_ctx.read_prefix_ctx_or_buf = ctx_or_buf;
209 export_ctx.wimlib_err_code = 0;
211 export_ctx.buf = MALLOC(WIM_CHUNK_SIZE);
213 return WIMLIB_ERR_NOMEM;
215 export_ctx.buf = NULL;
217 export_ctx.buf_filled = 0;
218 export_ctx.bytes_remaining = size;
220 err = OpenEncryptedFileRawW(lte->file_on_disk, 0, &file_ctx);
221 if (err != ERROR_SUCCESS) {
222 ERROR("Failed to open encrypted file \"%ls\" for raw read",
225 ret = WIMLIB_ERR_OPEN;
228 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
229 &export_ctx, file_ctx);
230 if (err != ERROR_SUCCESS) {
231 ERROR("Failed to read encrypted file \"%ls\"",
234 ret = export_ctx.wimlib_err_code;
236 ret = WIMLIB_ERR_READ;
237 } else if (export_ctx.bytes_remaining != 0) {
238 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
239 "encryted file \"%ls\"",
240 size - export_ctx.bytes_remaining, size,
242 ret = WIMLIB_ERR_READ;
246 CloseEncryptedFileRaw(file_ctx);
248 FREE(export_ctx.buf);
254 FILETIME_to_u64(const FILETIME *ft)
256 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
259 /* Load the short name of a file into a WIM dentry.
261 * If we can't read the short filename for some reason, we just ignore the error
262 * and assume the file has no short name. This shouldn't be an issue, since the
263 * short names are essentially obsolete anyway.
266 win32_get_short_name(HANDLE hFile, const wchar_t *path, struct wim_dentry *dentry)
269 /* It's not any harder to just make the NtQueryInformationFile() system
270 * call ourselves, and it saves a dumb call to FindFirstFile() which of
271 * course has to create its own handle. */
274 IO_STATUS_BLOCK io_status;
275 u8 buf[128] _aligned_attribute(8);
276 const FILE_NAME_INFORMATION *info;
278 status = NtQueryInformationFile(hFile, &io_status, buf, sizeof(buf),
279 FileAlternateNameInformation);
280 info = (const FILE_NAME_INFORMATION*)buf;
281 if (status == STATUS_SUCCESS && info->FileNameLength != 0) {
282 dentry->short_name = MALLOC(info->FileNameLength + 2);
283 if (!dentry->short_name)
284 return WIMLIB_ERR_NOMEM;
285 memcpy(dentry->short_name, info->FileName,
286 info->FileNameLength);
287 dentry->short_name[info->FileNameLength / 2] = L'\0';
288 dentry->short_name_nbytes = info->FileNameLength;
292 WIN32_FIND_DATAW dat;
296 hFind = FindFirstFile(path, &dat);
297 if (hFind != INVALID_HANDLE_VALUE) {
298 if (dat.cAlternateFileName[0] != L'\0') {
299 DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
300 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
302 size_t n = short_name_nbytes + sizeof(wchar_t);
303 dentry->short_name = MALLOC(n);
304 if (dentry->short_name) {
305 memcpy(dentry->short_name, dat.cAlternateFileName, n);
306 dentry->short_name_nbytes = short_name_nbytes;
308 ret = WIMLIB_ERR_NOMEM;
318 * win32_query_security_descriptor() - Query a file's security descriptor
320 * We need the file's security descriptor in SECURITY_DESCRIPTOR_RELATIVE
321 * relative format, and we currently have a handle opened with as many relevant
322 * permissions as possible. At this point, on Windows there are a number of
323 * options for reading a file's security descriptor:
325 * GetFileSecurity(): This takes in a path and returns the
326 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle, not
327 * ours, and the handle created internally doesn't specify
328 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied errors on
329 * some files and directories, even when running as the Administrator.
331 * GetSecurityInfo(): This takes in a handle and returns the security
332 * descriptor split into a bunch of different parts. This should work, but it's
333 * dumb because we have to put the security descriptor back together again.
335 * BackupRead(): This can read the security descriptor, but this is a
336 * difficult-to-use API, probably only works as the Administrator, and the
337 * format of the returned data is not well documented.
339 * NtQuerySecurityObject(): This is exactly what we need, as it takes in a
340 * handle and returns the security descriptor in SECURITY_DESCRIPTOR_RELATIVE
341 * format. Only problem is that it's a ntdll function and therefore not
342 * officially part of the Win32 API. Oh well.
345 win32_query_security_descriptor(HANDLE hFile, const wchar_t *path,
346 SECURITY_INFORMATION requestedInformation,
347 PSECURITY_DESCRIPTOR *buf,
348 DWORD bufsize, DWORD *lengthNeeded)
353 status = NtQuerySecurityObject(hFile, requestedInformation, buf,
354 bufsize, lengthNeeded);
355 /* Since it queries an already-open handle, NtQuerySecurityObject()
356 * apparently returns STATUS_ACCESS_DENIED rather than
357 * STATUS_PRIVILEGE_NOT_HELD. */
358 if (status == STATUS_ACCESS_DENIED)
359 return ERROR_PRIVILEGE_NOT_HELD;
361 return RtlNtStatusToDosError(status);
363 if (GetFileSecurity(path, requestedInformation, buf,
364 bufsize, lengthNeeded))
365 return ERROR_SUCCESS;
367 return GetLastError();
372 win32_get_security_descriptor(HANDLE hFile,
374 struct wim_inode *inode,
375 struct wim_sd_set *sd_set,
376 struct win32_capture_state *state,
379 SECURITY_INFORMATION requestedInformation;
387 requestedInformation = DACL_SECURITY_INFORMATION |
388 SACL_SECURITY_INFORMATION |
389 OWNER_SECURITY_INFORMATION |
390 GROUP_SECURITY_INFORMATION;
392 bufsize = sizeof(_buf);
394 err = win32_query_security_descriptor(hFile, path,
395 requestedInformation,
396 (PSECURITY_DESCRIPTOR)buf,
397 bufsize, &lenNeeded);
400 goto have_descriptor;
401 case ERROR_INSUFFICIENT_BUFFER:
402 wimlib_assert(buf == _buf);
403 buf = MALLOC(lenNeeded);
405 return WIMLIB_ERR_NOMEM;
408 case ERROR_PRIVILEGE_NOT_HELD:
409 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS)
411 if (requestedInformation & SACL_SECURITY_INFORMATION) {
412 state->num_get_sacl_priv_notheld++;
413 requestedInformation &= ~SACL_SECURITY_INFORMATION;
417 case ERROR_ACCESS_DENIED:
418 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS)
420 state->num_get_sd_access_denied++;
425 errno = win32_error_to_errno(err);
426 ERROR("Failed to read security descriptor of \"%ls\"", path);
427 ret = WIMLIB_ERR_READ;
433 inode->i_security_id = sd_set_add_sd(sd_set, buf, lenNeeded);
434 if (inode->i_security_id < 0)
435 ret = WIMLIB_ERR_NOMEM;
445 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
447 size_t path_num_chars,
448 struct add_image_params *params,
449 struct win32_capture_state *state,
452 /* Reads the directory entries of directory and recursively calls
453 * win32_build_dentry_tree() on them. */
455 win32_recurse_directory(HANDLE hDir,
457 size_t dir_path_num_chars,
458 struct wim_dentry *root,
459 struct add_image_params *params,
460 struct win32_capture_state *state,
465 DEBUG("Recurse to directory \"%ls\"", dir_path);
467 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
468 * which we opened with FILE_FLAG_BACKUP_SEMANTICS (probably not the
469 * case for the FindFirstFile() API; it's not documented). */
472 IO_STATUS_BLOCK io_status;
473 const size_t bufsize = 8192;
475 BOOL restartScan = TRUE;
476 const FILE_NAMES_INFORMATION *info;
478 buf = MALLOC(bufsize);
480 return WIMLIB_ERR_NOMEM;
482 status = NtQueryDirectoryFile(hDir, NULL, NULL, NULL,
483 &io_status, buf, bufsize,
484 FileNamesInformation,
485 FALSE, NULL, restartScan);
487 if (status != STATUS_SUCCESS) {
488 if (status == STATUS_NO_MORE_FILES ||
489 status == STATUS_NO_MORE_ENTRIES ||
490 status == STATUS_NO_MORE_MATCHES) {
493 errno = win32_error_to_errno(
494 RtlNtStatusToDosError(status));
495 ERROR_WITH_ERRNO("Failed to read directory "
496 "\"%ls\"", dir_path);
497 ret = WIMLIB_ERR_READ;
501 wimlib_assert(io_status.Information != 0);
502 info = (const FILE_NAMES_INFORMATION*)buf;
504 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
505 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
506 info->FileName[1] == L'.'))
509 struct wim_dentry *child;
511 p = dir_path + dir_path_num_chars;
513 p = wmempcpy(p, info->FileName,
514 info->FileNameLength / 2);
517 ret = win32_build_dentry_tree_recursive(
525 dir_path[dir_path_num_chars] = L'\0';
530 dentry_add_child(root, child);
532 if (info->NextEntryOffset == 0)
534 info = (const FILE_NAMES_INFORMATION*)
535 ((const u8*)info + info->NextEntryOffset);
542 WIN32_FIND_DATAW dat;
546 /* Begin reading the directory by calling FindFirstFileW. Unlike UNIX
547 * opendir(), FindFirstFileW has file globbing built into it. But this
548 * isn't what we actually want, so just add a dummy glob to get all
550 dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
551 dir_path[dir_path_num_chars + 1] = L'*';
552 dir_path[dir_path_num_chars + 2] = L'\0';
553 hFind = FindFirstFileW(dir_path, &dat);
554 dir_path[dir_path_num_chars] = L'\0';
556 if (hFind == INVALID_HANDLE_VALUE) {
557 err = GetLastError();
558 if (err == ERROR_FILE_NOT_FOUND) {
561 ERROR("Failed to read directory \"%ls\"", dir_path);
563 return WIMLIB_ERR_READ;
568 /* Skip . and .. entries */
569 if (dat.cFileName[0] == L'.' &&
570 (dat.cFileName[1] == L'\0' ||
571 (dat.cFileName[1] == L'.' &&
572 dat.cFileName[2] == L'\0')))
574 size_t filename_len = wcslen(dat.cFileName);
576 dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
577 wmemcpy(dir_path + dir_path_num_chars + 1,
581 struct wim_dentry *child;
582 size_t path_len = dir_path_num_chars + 1 + filename_len;
583 ret = win32_build_dentry_tree_recursive(&child,
589 dir_path[dir_path_num_chars] = L'\0';
593 dentry_add_child(root, child);
594 } while (FindNextFileW(hFind, &dat));
595 err = GetLastError();
596 if (err != ERROR_NO_MORE_FILES) {
597 ERROR("Failed to read directory \"%ls\"", dir_path);
600 ret = WIMLIB_ERR_READ;
608 /* Reparse point fixup status code */
610 /* Reparse point corresponded to an absolute symbolic link or junction
611 * point that pointed outside the directory tree being captured, and
612 * therefore was excluded. */
615 /* Reparse point was not fixed as it was either a relative symbolic
616 * link, a mount point, or something else we could not understand. */
619 /* Reparse point corresponded to an absolute symbolic link or junction
620 * point that pointed inside the directory tree being captured, where
621 * the target was specified by a "full" \??\ prefixed path, and
622 * therefore was fixed to be relative to the root of the directory tree
624 RP_FIXED_FULLPATH = 0x2,
626 /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
627 * have the \??\ prefix. It may have begun with a drive letter though.
629 RP_FIXED_ABSPATH = 0x4,
631 /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
632 RP_FIXED = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
635 /* Given the "substitute name" target of a Windows reparse point, try doing a
636 * fixup where we change it to be absolute relative to the root of the directory
637 * tree being captured.
639 * Note that this is only executed when WIMLIB_ADD_FLAG_RPFIX has been
642 * @capture_root_ino and @capture_root_dev indicate the inode number and device
643 * of the root of the directory tree being captured. They are meant to identify
644 * this directory (as an alternative to its actual path, which could potentially
645 * be reached via multiple destinations due to other symbolic links). This may
646 * not work properly on FAT, which doesn't seem to supply proper inode numbers
647 * or file IDs. However, FAT doesn't support reparse points so this function
648 * wouldn't even be called anyway.
650 static enum rp_status
651 win32_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
652 u64 capture_root_ino, u64 capture_root_dev,
655 u16 target_nchars = *target_nbytes_p / 2;
656 size_t stripped_chars;
657 wchar_t *orig_target;
660 ret = parse_substitute_name(target, *target_nbytes_p, rptag);
663 stripped_chars = ret;
666 target[target_nchars] = L'\0';
667 orig_target = target;
668 target = capture_fixup_absolute_symlink(target + stripped_chars,
669 capture_root_ino, capture_root_dev);
672 target_nchars = wcslen(target);
673 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
674 *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
675 DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
677 return RP_FIXED_FULLPATH;
679 return RP_FIXED_ABSPATH;
682 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
685 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
686 u64 capture_root_ino, u64 capture_root_dev,
689 struct reparse_data rpdata;
691 enum rp_status rp_status;
693 ret = parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata);
697 rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
698 &rpdata.substitute_name_nbytes,
701 le32_to_cpu(*(le32*)rpbuf));
702 if (rp_status & RP_FIXED) {
703 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
704 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
705 wmemcpy(substitute_name_copy, rpdata.substitute_name,
706 rpdata.substitute_name_nbytes / 2);
707 rpdata.substitute_name = substitute_name_copy;
708 rpdata.print_name = substitute_name_copy;
709 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
710 if (rp_status == RP_FIXED_FULLPATH) {
711 /* "full path", meaning \??\ prefixed. We should not
712 * include this prefix in the print name, as it is
713 * apparently meant for the filesystem driver only. */
714 rpdata.print_name += 4;
715 rpdata.print_name_nbytes -= 8;
717 ret = make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
723 if (rp_status == RP_EXCLUDED) {
724 size_t print_name_nchars = rpdata.print_name_nbytes / 2;
725 wchar_t print_name0[print_name_nchars + 1];
726 print_name0[print_name_nchars] = L'\0';
727 wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
728 WARNING("Ignoring %ls pointing out of capture directory:\n"
729 " \"%ls\" -> \"%ls\"\n"
730 " (Use --norpfix to capture all symbolic links "
731 "and junction points as-is)",
732 (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK) ?
733 L"absolute symbolic link" : L"junction point",
742 * Loads the reparse point data from a reparse point into memory, optionally
743 * fixing the targets of absolute symbolic links and junction points to be
744 * relative to the root of capture.
746 * @hFile: Open handle to the reparse point.
747 * @path: Path to the reparse point. Used for error messages only.
748 * @params: Additional parameters, including whether to do reparse point fixups
750 * @rpbuf: Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
751 * the reparse point buffer will be loaded.
752 * @rpbuflen_ret: On success, the length of the reparse point buffer in bytes
753 * is written to this location.
756 * On success, returns an `enum rp_status' value that indicates if and/or
757 * how the reparse point fixup was done.
759 * On failure, returns a negative value that is a negated WIMLIB_ERR_*
763 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
764 struct add_image_params *params,
765 u8 *rpbuf, u16 *rpbuflen_ret)
772 DEBUG("Loading reparse data from \"%ls\"", path);
773 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
774 NULL, /* "Not used with this operation; set to NULL" */
775 0, /* "Not used with this operation; set to 0" */
776 rpbuf, /* "A pointer to a buffer that
777 receives the reparse point data */
778 REPARSE_POINT_MAX_SIZE, /* "The size of the output
783 DWORD err = GetLastError();
784 ERROR("Failed to get reparse data of \"%ls\"", path);
786 return -WIMLIB_ERR_READ;
788 if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
789 ERROR("Reparse data on \"%ls\" is invalid", path);
790 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
793 rpbuflen = bytesReturned;
794 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
795 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
796 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
797 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
799 /* Try doing reparse point fixup */
800 ret = win32_capture_try_rpfix(rpbuf,
802 params->capture_root_ino,
803 params->capture_root_dev,
808 *rpbuflen_ret = rpbuflen;
813 win32_tally_encrypted_size_cb(unsigned char *_data, void *_ctx,
817 return ERROR_SUCCESS;
821 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
828 err = OpenEncryptedFileRawW(path, 0, &file_ctx);
829 if (err != ERROR_SUCCESS) {
830 ERROR("Failed to open encrypted file \"%ls\" for raw read", path);
832 return WIMLIB_ERR_OPEN;
834 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
836 if (err != ERROR_SUCCESS) {
837 ERROR("Failed to read raw encrypted data from \"%ls\"", path);
839 ret = WIMLIB_ERR_READ;
843 CloseEncryptedFileRaw(file_ctx);
847 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
848 * stream); calculates its SHA1 message digest and either creates a `struct
849 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
850 * wim_lookup_table_entry' for an identical stream.
852 * @path: Path to the file (UTF-16LE).
854 * @path_num_chars: Number of 2-byte characters in @path.
856 * @inode: WIM inode to save the stream into.
858 * @lookup_table: Stream lookup table for the WIM.
860 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
863 * Returns 0 on success; nonzero on failure.
866 win32_capture_stream(const wchar_t *path,
867 size_t path_num_chars,
868 struct wim_inode *inode,
869 struct wim_lookup_table *lookup_table,
870 WIN32_FIND_STREAM_DATA *dat)
872 struct wim_ads_entry *ads_entry;
873 struct wim_lookup_table_entry *lte;
875 wchar_t *stream_name, *colon;
876 size_t stream_name_nchars;
877 bool is_named_stream;
880 size_t spath_buf_nbytes;
881 const wchar_t *relpath_prefix;
882 const wchar_t *colonchar;
884 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
886 /* The stream name should be returned as :NAME:TYPE */
887 stream_name = dat->cStreamName;
888 if (*stream_name != L':')
889 goto out_invalid_stream_name;
891 colon = wcschr(stream_name, L':');
893 goto out_invalid_stream_name;
895 if (wcscmp(colon + 1, L"$DATA")) {
896 /* Not a DATA stream */
903 stream_name_nchars = colon - stream_name;
904 is_named_stream = (stream_name_nchars != 0);
906 if (is_named_stream) {
907 /* Allocate an ADS entry for the named stream. */
908 ads_entry = inode_add_ads_utf16le(inode, stream_name,
909 stream_name_nchars * sizeof(wchar_t));
911 ret = WIMLIB_ERR_NOMEM;
916 /* If zero length stream, no lookup table entry needed. */
917 if ((u64)dat->StreamSize.QuadPart == 0) {
922 /* Create a UTF-16LE string @spath that gives the filename, then a
923 * colon, then the stream name. Or, if it's an unnamed stream, just the
924 * filename. It is MALLOC()'ed so that it can be saved in the
925 * wim_lookup_table_entry if needed.
927 * As yet another special case, relative paths need to be changed to
928 * begin with an explicit "./" so that, for example, a file t:ads, where
929 * :ads is the part we added, is not interpreted as a file on the t:
931 spath_nchars = path_num_chars;
932 relpath_prefix = L"";
934 if (is_named_stream) {
935 spath_nchars += 1 + stream_name_nchars;
937 if (path_num_chars == 1 && !is_any_path_separator(path[0])) {
939 static const wchar_t _relpath_prefix[] =
940 {L'.', OS_PREFERRED_PATH_SEPARATOR, L'\0'};
941 relpath_prefix = _relpath_prefix;
945 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
946 spath = MALLOC(spath_buf_nbytes);
948 swprintf(spath, L"%ls%ls%ls%ls",
949 relpath_prefix, path, colonchar, stream_name);
951 /* Make a new wim_lookup_table_entry */
952 lte = new_lookup_table_entry();
954 ret = WIMLIB_ERR_NOMEM;
957 lte->file_on_disk = spath;
959 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
961 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
962 ret = win32_get_encrypted_file_size(path, &encrypted_size);
965 lte->resource_entry.original_size = encrypted_size;
967 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
968 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
972 if (is_named_stream) {
973 stream_id = ads_entry->stream_id;
974 ads_entry->lte = lte;
979 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
985 out_invalid_stream_name:
986 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
987 ret = WIMLIB_ERR_READ;
991 /* Load information about the streams of an open file into a WIM inode.
993 * By default, we use the NtQueryInformationFile() system call instead of
994 * FindFirstStream() and FindNextStream(). This is done for two reasons:
996 * - FindFirstStream() opens its own handle to the file or directory and
997 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
998 * causing access denied errors on certain files (even when running as the
1000 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
1001 * and later, whereas the stream support in NtQueryInformationFile() was
1002 * already present in Windows XP.
1005 win32_capture_streams(HANDLE hFile,
1006 const wchar_t *path,
1007 size_t path_num_chars,
1008 struct wim_inode *inode,
1009 struct wim_lookup_table *lookup_table,
1013 WIN32_FIND_STREAM_DATA dat;
1016 u8 _buf[8192] _aligned_attribute(8);
1019 IO_STATUS_BLOCK io_status;
1021 const FILE_STREAM_INFORMATION *info;
1027 DEBUG("Capturing streams from \"%ls\"", path);
1029 if (!(vol_flags & FILE_NAMED_STREAMS))
1032 if (win32func_FindFirstStreamW == NULL)
1038 bufsize = sizeof(_buf);
1040 /* Get a buffer containing the stream information. */
1042 status = NtQueryInformationFile(hFile, &io_status, buf, bufsize,
1043 FileStreamInformation);
1044 if (status == STATUS_SUCCESS) {
1046 } else if (status == STATUS_BUFFER_OVERFLOW) {
1051 newbuf = MALLOC(bufsize);
1053 newbuf = REALLOC(buf, bufsize);
1056 ret = WIMLIB_ERR_NOMEM;
1061 errno = win32_error_to_errno(RtlNtStatusToDosError(status));
1062 ERROR_WITH_ERRNO("Failed to read streams of %ls", path);
1063 ret = WIMLIB_ERR_READ;
1068 if (io_status.Information == 0) {
1069 /* No stream information. */
1074 /* Parse one or more stream information structures. */
1075 info = (const FILE_STREAM_INFORMATION*)buf;
1077 if (info->StreamNameLength <= sizeof(dat.cStreamName) - 2) {
1078 dat.StreamSize = info->StreamSize;
1079 memcpy(dat.cStreamName, info->StreamName, info->StreamNameLength);
1080 dat.cStreamName[info->StreamNameLength / 2] = L'\0';
1082 /* Capture the stream. */
1083 ret = win32_capture_stream(path, path_num_chars, inode,
1084 lookup_table, &dat);
1088 if (info->NextEntryOffset == 0) {
1089 /* No more stream information. */
1093 /* Advance to next stream information. */
1094 info = (const FILE_STREAM_INFORMATION*)
1095 ((const u8*)info + info->NextEntryOffset);
1098 /* Free buffer if allocated on heap. */
1103 #else /* WITH_NTDLL */
1104 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1105 if (hFind == INVALID_HANDLE_VALUE) {
1106 err = GetLastError();
1107 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1110 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1111 * points and directories */
1112 if ((inode->i_attributes &
1113 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1114 && err == ERROR_HANDLE_EOF)
1116 DEBUG("ERROR_HANDLE_EOF (ok)");
1119 if (err == ERROR_ACCESS_DENIED) {
1120 WARNING("Failed to look up data streams "
1121 "of \"%ls\": Access denied!\n%ls",
1122 path, capture_access_denied_msg);
1125 ERROR("Failed to look up data streams "
1126 "of \"%ls\"", path);
1128 return WIMLIB_ERR_READ;
1133 ret = win32_capture_stream(path,
1135 inode, lookup_table,
1138 goto out_find_close;
1139 } while (win32func_FindNextStreamW(hFind, &dat));
1140 err = GetLastError();
1141 if (err != ERROR_HANDLE_EOF) {
1142 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
1144 ret = WIMLIB_ERR_READ;
1149 #endif /* !WITH_NTDLL */
1152 /* FindFirstStreamW() API is not available, or the volume does not
1153 * support named streams. Only capture the unnamed data stream. */
1154 DEBUG("Only capturing unnamed data stream");
1155 if (!(inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1156 FILE_ATTRIBUTE_REPARSE_POINT)))
1158 wcscpy(dat.cStreamName, L"::$DATA");
1159 dat.StreamSize.QuadPart = file_size;
1160 ret = win32_capture_stream(path,
1162 inode, lookup_table,
1171 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1173 size_t path_num_chars,
1174 struct add_image_params *params,
1175 struct win32_capture_state *state,
1178 struct wim_dentry *root = NULL;
1179 struct wim_inode *inode;
1187 DWORD desiredAccess;
1189 params->progress.scan.cur_path = path;
1191 if (exclude_path(path, path_num_chars, params->config, true)) {
1192 if (params->add_flags & WIMLIB_ADD_FLAG_ROOT) {
1193 ERROR("Cannot exclude the root directory from capture");
1194 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1197 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED);
1203 if (path_num_chars >= 4 &&
1204 !wmemcmp(path, L"\\\\?\\", 4) &&
1205 path_num_chars + 1 - 4 > MAX_PATH &&
1206 state->num_long_path_warnings < MAX_CAPTURE_LONG_PATH_WARNINGS)
1208 WARNING("Path \"%ls\" exceeds MAX_PATH", path);
1209 if (++state->num_long_path_warnings == MAX_CAPTURE_LONG_PATH_WARNINGS)
1210 WARNING("Suppressing further warnings about long paths.");
1214 do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK);
1216 desiredAccess = FILE_READ_DATA | FILE_READ_ATTRIBUTES |
1217 READ_CONTROL | ACCESS_SYSTEM_SECURITY;
1219 hFile = win32_open_existing_file(path, desiredAccess);
1220 if (hFile == INVALID_HANDLE_VALUE) {
1221 err = GetLastError();
1222 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD) {
1223 if (desiredAccess & ACCESS_SYSTEM_SECURITY) {
1224 desiredAccess &= ~ACCESS_SYSTEM_SECURITY;
1227 if (desiredAccess & READ_CONTROL) {
1228 desiredAccess &= ~READ_CONTROL;
1232 set_errno_from_GetLastError();
1233 ERROR_WITH_ERRNO("Failed to open \"%ls\" for reading", path);
1234 ret = WIMLIB_ERR_OPEN;
1238 BY_HANDLE_FILE_INFORMATION file_info;
1239 if (!GetFileInformationByHandle(hFile, &file_info)) {
1240 set_errno_from_GetLastError();
1241 ERROR_WITH_ERRNO("Failed to get file information for \"%ls\"",
1243 ret = WIMLIB_ERR_STAT;
1244 goto out_close_handle;
1247 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1248 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1249 ret = win32_get_reparse_data(hFile, path, params,
1252 /* WIMLIB_ERR_* (inverted) */
1254 goto out_close_handle;
1255 } else if (ret & RP_FIXED) {
1257 } else if (ret == RP_EXCLUDED) {
1259 goto out_close_handle;
1265 /* Create a WIM dentry with an associated inode, which may be shared.
1267 * However, we need to explicitly check for directories and files with
1268 * only 1 link and refuse to hard link them. This is because Windows
1269 * has a bug where it can return duplicate File IDs for files and
1270 * directories on the FAT filesystem. */
1271 ret = inode_table_new_dentry(¶ms->inode_table,
1272 path_basename_with_len(path, path_num_chars),
1273 ((u64)file_info.nFileIndexHigh << 32) |
1274 (u64)file_info.nFileIndexLow,
1275 file_info.dwVolumeSerialNumber,
1276 (file_info.nNumberOfLinks <= 1 ||
1277 (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1280 goto out_close_handle;
1282 ret = win32_get_short_name(hFile, path, root);
1284 goto out_close_handle;
1286 inode = root->d_inode;
1288 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1289 goto out_close_handle;
1291 inode->i_attributes = file_info.dwFileAttributes;
1292 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1293 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1294 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1295 inode->i_resolved = 1;
1297 params->add_flags &= ~WIMLIB_ADD_FLAG_ROOT;
1299 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1300 && (vol_flags & FILE_PERSISTENT_ACLS))
1302 ret = win32_get_security_descriptor(hFile, path, inode,
1303 ¶ms->sd_set, state,
1306 goto out_close_handle;
1309 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1310 (u64)file_info.nFileSizeLow;
1313 /* Capture the unnamed data stream (only should be present for regular
1314 * files) and any alternate data streams. */
1315 ret = win32_capture_streams(hFile,
1319 params->lookup_table,
1323 goto out_close_handle;
1325 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1326 /* Reparse point: set the reparse data (which we read already)
1328 inode->i_not_rpfixed = not_rpfixed;
1329 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1330 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1331 params->lookup_table);
1332 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1333 /* Directory (not a reparse point) --- recurse to children */
1334 ret = win32_recurse_directory(hFile,
1348 free_dentry_tree(root, params->lookup_table);
1353 win32_do_capture_warnings(const wchar_t *path,
1354 const struct win32_capture_state *state,
1357 if (state->num_get_sacl_priv_notheld == 0 &&
1358 state->num_get_sd_access_denied == 0)
1361 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1362 if (state->num_get_sacl_priv_notheld != 0) {
1363 WARNING("- Could not capture SACL (System Access Control List)\n"
1364 " on %lu files or directories.",
1365 state->num_get_sacl_priv_notheld);
1367 if (state->num_get_sd_access_denied != 0) {
1368 WARNING("- Could not capture security descriptor at all\n"
1369 " on %lu files or directories.",
1370 state->num_get_sd_access_denied);
1372 WARNING("To fully capture all security descriptors, run the program\n"
1373 " with Administrator rights.");
1376 #define WINDOWS_NT_MAX_PATH 32768
1378 /* Win32 version of capturing a directory tree */
1380 win32_build_dentry_tree(struct wim_dentry **root_ret,
1381 const wchar_t *root_disk_path,
1382 struct add_image_params *params)
1387 struct win32_capture_state state;
1390 bool need_prefix_free = false;
1393 if (!win32func_FindFirstStreamW) {
1394 WARNING("Running on Windows XP or earlier; "
1395 "alternate data streams will not be captured.");
1399 path_nchars = wcslen(root_disk_path);
1400 if (path_nchars > WINDOWS_NT_MAX_PATH)
1401 return WIMLIB_ERR_INVALID_PARAM;
1403 if (GetFileAttributesW(root_disk_path) == INVALID_FILE_ATTRIBUTES &&
1404 GetLastError() == ERROR_FILE_NOT_FOUND)
1406 ERROR("Capture directory \"%ls\" does not exist!",
1408 return WIMLIB_ERR_OPENDIR;
1411 ret = win32_get_file_and_vol_ids(root_disk_path,
1412 ¶ms->capture_root_ino,
1413 ¶ms->capture_root_dev);
1417 win32_get_vol_flags(root_disk_path, &vol_flags, NULL);
1419 /* WARNING: There is no check for overflow later when this buffer is
1420 * being used! But it's as long as the maximum path length understood
1421 * by Windows NT (which is NOT the same as MAX_PATH). */
1422 path = MALLOC(WINDOWS_NT_MAX_PATH * sizeof(wchar_t));
1424 return WIMLIB_ERR_NOMEM;
1426 /* Work around defective behavior in Windows where paths longer than 260
1427 * characters are not supported by default; instead they need to be
1428 * turned into absolute paths and prefixed with "\\?\". */
1430 if (wcsncmp(root_disk_path, L"\\\\?\\", 4)) {
1431 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 4,
1434 if (dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 4) {
1435 WARNING("Can't get full path name for \"%ls\"", root_disk_path);
1436 wmemcpy(path, root_disk_path, path_nchars + 1);
1438 wmemcpy(path, L"\\\\?\\", 4);
1439 path_nchars = 4 + dret;
1440 /* Update pattern prefix */
1441 if (params->config != NULL)
1443 params->config->_prefix = TSTRDUP(path);
1444 params->config->_prefix_num_tchars = path_nchars;
1445 if (params->config->_prefix == NULL)
1447 ret = WIMLIB_ERR_NOMEM;
1450 need_prefix_free = true;
1454 wmemcpy(path, root_disk_path, path_nchars + 1);
1457 memset(&state, 0, sizeof(state));
1458 ret = win32_build_dentry_tree_recursive(root_ret, path,
1459 path_nchars, params,
1461 if (need_prefix_free)
1462 FREE(params->config->_prefix);
1466 win32_do_capture_warnings(root_disk_path, &state, params->add_flags);
1470 #endif /* __WIN32__ */