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_existing_file(lte->file_on_disk,
95 if (hFile == INVALID_HANDLE_VALUE) {
96 set_errno_from_GetLastError();
97 ERROR_WITH_ERRNO("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 set_errno_from_GetLastError();
115 ERROR_WITH_ERRNO("Failed to read data from \"%ls\"",
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 set_errno_from_win32_error(err);
223 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
224 "for raw read", lte->file_on_disk);
225 ret = WIMLIB_ERR_OPEN;
228 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
229 &export_ctx, file_ctx);
230 if (err != ERROR_SUCCESS) {
231 set_errno_from_win32_error(err);
232 ERROR_WITH_ERRNO("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 * 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 SECURITY_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 (SECURITY_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 set_errno_from_win32_error(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 set_errno_from_nt_status(status);
494 ERROR_WITH_ERRNO("Failed to read directory "
495 "\"%ls\"", dir_path);
496 ret = WIMLIB_ERR_READ;
500 wimlib_assert(io_status.Information != 0);
501 info = (const FILE_NAMES_INFORMATION*)buf;
503 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
504 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
505 info->FileName[1] == L'.'))
508 struct wim_dentry *child;
510 p = dir_path + dir_path_num_chars;
512 p = wmempcpy(p, info->FileName,
513 info->FileNameLength / 2);
516 ret = win32_build_dentry_tree_recursive(
524 dir_path[dir_path_num_chars] = L'\0';
529 dentry_add_child(root, child);
531 if (info->NextEntryOffset == 0)
533 info = (const FILE_NAMES_INFORMATION*)
534 ((const u8*)info + info->NextEntryOffset);
541 WIN32_FIND_DATAW dat;
545 /* Begin reading the directory by calling FindFirstFileW. Unlike UNIX
546 * opendir(), FindFirstFileW has file globbing built into it. But this
547 * isn't what we actually want, so just add a dummy glob to get all
549 dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
550 dir_path[dir_path_num_chars + 1] = L'*';
551 dir_path[dir_path_num_chars + 2] = L'\0';
552 hFind = FindFirstFileW(dir_path, &dat);
553 dir_path[dir_path_num_chars] = L'\0';
555 if (hFind == INVALID_HANDLE_VALUE) {
556 err = GetLastError();
557 if (err == ERROR_FILE_NOT_FOUND) {
560 set_errno_from_win32_error(err);
561 ERROR_WITH_ERRNO("Failed to read directory \"%ls\"",
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 set_errno_from_win32_error(err);
598 ERROR_WITH_ERRNO("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 set_errno_from_GetLastError();
784 ERROR_WITH_ERRNO("Failed to get reparse data of \"%ls\"", path);
785 return -WIMLIB_ERR_READ;
787 if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
788 ERROR("Reparse data on \"%ls\" is invalid", path);
789 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
792 rpbuflen = bytesReturned;
793 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
794 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
795 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
796 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
798 /* Try doing reparse point fixup */
799 ret = win32_capture_try_rpfix(rpbuf,
801 params->capture_root_ino,
802 params->capture_root_dev,
807 *rpbuflen_ret = rpbuflen;
812 win32_tally_encrypted_size_cb(unsigned char *_data, void *_ctx,
816 return ERROR_SUCCESS;
820 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
827 err = OpenEncryptedFileRawW(path, 0, &file_ctx);
828 if (err != ERROR_SUCCESS) {
829 set_errno_from_win32_error(err);
830 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
831 "for raw read", path);
832 return WIMLIB_ERR_OPEN;
834 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
836 if (err != ERROR_SUCCESS) {
837 set_errno_from_win32_error(err);
838 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
840 ret = WIMLIB_ERR_READ;
844 CloseEncryptedFileRaw(file_ctx);
848 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
849 * stream); calculates its SHA1 message digest and either creates a `struct
850 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
851 * wim_lookup_table_entry' for an identical stream.
853 * @path: Path to the file (UTF-16LE).
855 * @path_num_chars: Number of 2-byte characters in @path.
857 * @inode: WIM inode to save the stream into.
859 * @lookup_table: Stream lookup table for the WIM.
861 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
864 * Returns 0 on success; nonzero on failure.
867 win32_capture_stream(const wchar_t *path,
868 size_t path_num_chars,
869 struct wim_inode *inode,
870 struct wim_lookup_table *lookup_table,
871 WIN32_FIND_STREAM_DATA *dat)
873 struct wim_ads_entry *ads_entry;
874 struct wim_lookup_table_entry *lte;
876 wchar_t *stream_name, *colon;
877 size_t stream_name_nchars;
878 bool is_named_stream;
881 size_t spath_buf_nbytes;
882 const wchar_t *relpath_prefix;
883 const wchar_t *colonchar;
885 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
887 /* The stream name should be returned as :NAME:TYPE */
888 stream_name = dat->cStreamName;
889 if (*stream_name != L':')
890 goto out_invalid_stream_name;
892 colon = wcschr(stream_name, L':');
894 goto out_invalid_stream_name;
896 if (wcscmp(colon + 1, L"$DATA")) {
897 /* Not a DATA stream */
904 stream_name_nchars = colon - stream_name;
905 is_named_stream = (stream_name_nchars != 0);
907 if (is_named_stream) {
908 /* Allocate an ADS entry for the named stream. */
909 ads_entry = inode_add_ads_utf16le(inode, stream_name,
910 stream_name_nchars * sizeof(wchar_t));
912 ret = WIMLIB_ERR_NOMEM;
917 /* If zero length stream, no lookup table entry needed. */
918 if ((u64)dat->StreamSize.QuadPart == 0) {
923 /* Create a UTF-16LE string @spath that gives the filename, then a
924 * colon, then the stream name. Or, if it's an unnamed stream, just the
925 * filename. It is MALLOC()'ed so that it can be saved in the
926 * wim_lookup_table_entry if needed.
928 * As yet another special case, relative paths need to be changed to
929 * begin with an explicit "./" so that, for example, a file t:ads, where
930 * :ads is the part we added, is not interpreted as a file on the t:
932 spath_nchars = path_num_chars;
933 relpath_prefix = L"";
935 if (is_named_stream) {
936 spath_nchars += 1 + stream_name_nchars;
938 if (path_num_chars == 1 && !is_any_path_separator(path[0])) {
940 static const wchar_t _relpath_prefix[] =
941 {L'.', OS_PREFERRED_PATH_SEPARATOR, L'\0'};
942 relpath_prefix = _relpath_prefix;
946 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
947 spath = MALLOC(spath_buf_nbytes);
949 swprintf(spath, L"%ls%ls%ls%ls",
950 relpath_prefix, path, colonchar, stream_name);
952 /* Make a new wim_lookup_table_entry */
953 lte = new_lookup_table_entry();
955 ret = WIMLIB_ERR_NOMEM;
958 lte->file_on_disk = spath;
960 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
962 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
963 ret = win32_get_encrypted_file_size(path, &encrypted_size);
966 lte->resource_entry.original_size = encrypted_size;
968 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
969 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
973 if (is_named_stream) {
974 stream_id = ads_entry->stream_id;
975 ads_entry->lte = lte;
980 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
986 out_invalid_stream_name:
987 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
988 ret = WIMLIB_ERR_READ;
992 /* Load information about the streams of an open file into a WIM inode.
994 * By default, we use the NtQueryInformationFile() system call instead of
995 * FindFirstStream() and FindNextStream(). This is done for two reasons:
997 * - FindFirstStream() opens its own handle to the file or directory and
998 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
999 * causing access denied errors on certain files (even when running as the
1001 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
1002 * and later, whereas the stream support in NtQueryInformationFile() was
1003 * already present in Windows XP.
1006 win32_capture_streams(HANDLE hFile,
1007 const wchar_t *path,
1008 size_t path_num_chars,
1009 struct wim_inode *inode,
1010 struct wim_lookup_table *lookup_table,
1014 WIN32_FIND_STREAM_DATA dat;
1017 u8 _buf[8192] _aligned_attribute(8);
1020 IO_STATUS_BLOCK io_status;
1022 const FILE_STREAM_INFORMATION *info;
1028 DEBUG("Capturing streams from \"%ls\"", path);
1030 if (!(vol_flags & FILE_NAMED_STREAMS))
1033 if (win32func_FindFirstStreamW == NULL)
1039 bufsize = sizeof(_buf);
1041 /* Get a buffer containing the stream information. */
1043 status = NtQueryInformationFile(hFile, &io_status, buf, bufsize,
1044 FileStreamInformation);
1045 if (status == STATUS_SUCCESS) {
1047 } else if (status == STATUS_BUFFER_OVERFLOW) {
1052 newbuf = MALLOC(bufsize);
1054 newbuf = REALLOC(buf, bufsize);
1057 ret = WIMLIB_ERR_NOMEM;
1062 set_errno_from_nt_status(status);
1063 ERROR_WITH_ERRNO("Failed to read streams of %ls", path);
1064 ret = WIMLIB_ERR_READ;
1069 if (io_status.Information == 0) {
1070 /* No stream information. */
1075 /* Parse one or more stream information structures. */
1076 info = (const FILE_STREAM_INFORMATION*)buf;
1078 if (info->StreamNameLength <= sizeof(dat.cStreamName) - 2) {
1079 dat.StreamSize = info->StreamSize;
1080 memcpy(dat.cStreamName, info->StreamName, info->StreamNameLength);
1081 dat.cStreamName[info->StreamNameLength / 2] = L'\0';
1083 /* Capture the stream. */
1084 ret = win32_capture_stream(path, path_num_chars, inode,
1085 lookup_table, &dat);
1089 if (info->NextEntryOffset == 0) {
1090 /* No more stream information. */
1094 /* Advance to next stream information. */
1095 info = (const FILE_STREAM_INFORMATION*)
1096 ((const u8*)info + info->NextEntryOffset);
1099 /* Free buffer if allocated on heap. */
1104 #else /* WITH_NTDLL */
1105 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1106 if (hFind == INVALID_HANDLE_VALUE) {
1107 err = GetLastError();
1108 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1111 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1112 * points and directories */
1113 if ((inode->i_attributes &
1114 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1115 && err == ERROR_HANDLE_EOF)
1117 DEBUG("ERROR_HANDLE_EOF (ok)");
1120 if (err == ERROR_ACCESS_DENIED) {
1121 WARNING("Failed to look up data streams "
1122 "of \"%ls\": Access denied!\n%ls",
1123 path, capture_access_denied_msg);
1126 set_errno_from_win32_error(err);
1127 ERROR_WITH_ERRNO("Failed to look up data streams "
1128 "of \"%ls\"", path);
1129 return WIMLIB_ERR_READ;
1134 ret = win32_capture_stream(path,
1136 inode, lookup_table,
1139 goto out_find_close;
1140 } while (win32func_FindNextStreamW(hFind, &dat));
1141 err = GetLastError();
1142 if (err != ERROR_HANDLE_EOF) {
1143 set_errno_from_win32_error(err);
1144 ERROR_WITH_ERRNO("Error reading data streams from "
1146 ret = WIMLIB_ERR_READ;
1151 #endif /* !WITH_NTDLL */
1154 /* FindFirstStreamW() API is not available, or the volume does not
1155 * support named streams. Only capture the unnamed data stream. */
1156 DEBUG("Only capturing unnamed data stream");
1157 if (!(inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1158 FILE_ATTRIBUTE_REPARSE_POINT)))
1160 wcscpy(dat.cStreamName, L"::$DATA");
1161 dat.StreamSize.QuadPart = file_size;
1162 ret = win32_capture_stream(path,
1164 inode, lookup_table,
1173 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1175 size_t path_num_chars,
1176 struct add_image_params *params,
1177 struct win32_capture_state *state,
1180 struct wim_dentry *root = NULL;
1181 struct wim_inode *inode;
1189 DWORD desiredAccess;
1191 params->progress.scan.cur_path = path;
1193 if (exclude_path(path, path_num_chars, params->config, true)) {
1194 if (params->add_flags & WIMLIB_ADD_FLAG_ROOT) {
1195 ERROR("Cannot exclude the root directory from capture");
1196 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1199 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED);
1205 if (path_num_chars >= 4 &&
1206 !wmemcmp(path, L"\\\\?\\", 4) &&
1207 path_num_chars + 1 - 4 > MAX_PATH &&
1208 state->num_long_path_warnings < MAX_CAPTURE_LONG_PATH_WARNINGS)
1210 WARNING("Path \"%ls\" exceeds MAX_PATH", path);
1211 if (++state->num_long_path_warnings == MAX_CAPTURE_LONG_PATH_WARNINGS)
1212 WARNING("Suppressing further warnings about long paths.");
1216 do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK);
1218 desiredAccess = FILE_READ_DATA | FILE_READ_ATTRIBUTES |
1219 READ_CONTROL | ACCESS_SYSTEM_SECURITY;
1221 hFile = win32_open_existing_file(path, desiredAccess);
1222 if (hFile == INVALID_HANDLE_VALUE) {
1223 err = GetLastError();
1224 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD) {
1225 if (desiredAccess & ACCESS_SYSTEM_SECURITY) {
1226 desiredAccess &= ~ACCESS_SYSTEM_SECURITY;
1229 if (desiredAccess & READ_CONTROL) {
1230 desiredAccess &= ~READ_CONTROL;
1234 set_errno_from_GetLastError();
1235 ERROR_WITH_ERRNO("Failed to open \"%ls\" for reading", path);
1236 ret = WIMLIB_ERR_OPEN;
1240 BY_HANDLE_FILE_INFORMATION file_info;
1241 if (!GetFileInformationByHandle(hFile, &file_info)) {
1242 set_errno_from_GetLastError();
1243 ERROR_WITH_ERRNO("Failed to get file information for \"%ls\"",
1245 ret = WIMLIB_ERR_STAT;
1246 goto out_close_handle;
1249 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1250 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1251 ret = win32_get_reparse_data(hFile, path, params,
1254 /* WIMLIB_ERR_* (inverted) */
1256 goto out_close_handle;
1257 } else if (ret & RP_FIXED) {
1259 } else if (ret == RP_EXCLUDED) {
1261 goto out_close_handle;
1267 /* Create a WIM dentry with an associated inode, which may be shared.
1269 * However, we need to explicitly check for directories and files with
1270 * only 1 link and refuse to hard link them. This is because Windows
1271 * has a bug where it can return duplicate File IDs for files and
1272 * directories on the FAT filesystem. */
1273 ret = inode_table_new_dentry(¶ms->inode_table,
1274 path_basename_with_len(path, path_num_chars),
1275 ((u64)file_info.nFileIndexHigh << 32) |
1276 (u64)file_info.nFileIndexLow,
1277 file_info.dwVolumeSerialNumber,
1278 (file_info.nNumberOfLinks <= 1 ||
1279 (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1282 goto out_close_handle;
1284 ret = win32_get_short_name(hFile, path, root);
1286 goto out_close_handle;
1288 inode = root->d_inode;
1290 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1291 goto out_close_handle;
1293 inode->i_attributes = file_info.dwFileAttributes;
1294 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1295 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1296 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1297 inode->i_resolved = 1;
1299 params->add_flags &= ~WIMLIB_ADD_FLAG_ROOT;
1301 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1302 && (vol_flags & FILE_PERSISTENT_ACLS))
1304 ret = win32_get_security_descriptor(hFile, path, inode,
1305 ¶ms->sd_set, state,
1308 goto out_close_handle;
1311 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1312 (u64)file_info.nFileSizeLow;
1315 /* Capture the unnamed data stream (only should be present for regular
1316 * files) and any alternate data streams. */
1317 ret = win32_capture_streams(hFile,
1321 params->lookup_table,
1325 goto out_close_handle;
1327 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1328 /* Reparse point: set the reparse data (which we read already)
1330 inode->i_not_rpfixed = not_rpfixed;
1331 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1332 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1333 params->lookup_table);
1334 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1335 /* Directory (not a reparse point) --- recurse to children */
1336 ret = win32_recurse_directory(hFile,
1350 free_dentry_tree(root, params->lookup_table);
1355 win32_do_capture_warnings(const wchar_t *path,
1356 const struct win32_capture_state *state,
1359 if (state->num_get_sacl_priv_notheld == 0 &&
1360 state->num_get_sd_access_denied == 0)
1363 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1364 if (state->num_get_sacl_priv_notheld != 0) {
1365 WARNING("- Could not capture SACL (System Access Control List)\n"
1366 " on %lu files or directories.",
1367 state->num_get_sacl_priv_notheld);
1369 if (state->num_get_sd_access_denied != 0) {
1370 WARNING("- Could not capture security descriptor at all\n"
1371 " on %lu files or directories.",
1372 state->num_get_sd_access_denied);
1374 WARNING("To fully capture all security descriptors, run the program\n"
1375 " with Administrator rights.");
1378 #define WINDOWS_NT_MAX_PATH 32768
1380 /* Win32 version of capturing a directory tree */
1382 win32_build_dentry_tree(struct wim_dentry **root_ret,
1383 const wchar_t *root_disk_path,
1384 struct add_image_params *params)
1389 struct win32_capture_state state;
1392 bool need_prefix_free = false;
1395 if (!win32func_FindFirstStreamW) {
1396 WARNING("Running on Windows XP or earlier; "
1397 "alternate data streams will not be captured.");
1401 path_nchars = wcslen(root_disk_path);
1402 if (path_nchars > WINDOWS_NT_MAX_PATH)
1403 return WIMLIB_ERR_INVALID_PARAM;
1405 ret = win32_get_file_and_vol_ids(root_disk_path,
1406 ¶ms->capture_root_ino,
1407 ¶ms->capture_root_dev);
1409 ERROR_WITH_ERRNO("Can't open %ls", root_disk_path);
1413 win32_get_vol_flags(root_disk_path, &vol_flags, NULL);
1415 /* WARNING: There is no check for overflow later when this buffer is
1416 * being used! But it's as long as the maximum path length understood
1417 * by Windows NT (which is NOT the same as MAX_PATH). */
1418 path = MALLOC(WINDOWS_NT_MAX_PATH * sizeof(wchar_t));
1420 return WIMLIB_ERR_NOMEM;
1422 /* Work around defective behavior in Windows where paths longer than 260
1423 * characters are not supported by default; instead they need to be
1424 * turned into absolute paths and prefixed with "\\?\". */
1426 if (wcsncmp(root_disk_path, L"\\\\?\\", 4)) {
1427 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 4,
1430 if (dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 4) {
1431 WARNING("Can't get full path name for \"%ls\"", root_disk_path);
1432 wmemcpy(path, root_disk_path, path_nchars + 1);
1434 wmemcpy(path, L"\\\\?\\", 4);
1435 path_nchars = 4 + dret;
1436 /* Update pattern prefix */
1437 if (params->config != NULL)
1439 params->config->_prefix = TSTRDUP(path);
1440 params->config->_prefix_num_tchars = path_nchars;
1441 if (params->config->_prefix == NULL)
1443 ret = WIMLIB_ERR_NOMEM;
1446 need_prefix_free = true;
1450 wmemcpy(path, root_disk_path, path_nchars + 1);
1453 memset(&state, 0, sizeof(state));
1454 ret = win32_build_dentry_tree_recursive(root_ret, path,
1455 path_nchars, params,
1457 if (need_prefix_free)
1458 FREE(params->config->_prefix);
1462 win32_do_capture_warnings(root_disk_path, &state, params->add_flags);
1466 #endif /* __WIN32__ */