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"
39 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
40 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
41 #define MAX_CAPTURE_LONG_PATH_WARNINGS 5
43 struct win32_capture_state {
44 unsigned long num_get_sd_access_denied;
45 unsigned long num_get_sacl_priv_notheld;
46 unsigned long num_long_path_warnings;
50 static const wchar_t *capture_access_denied_msg =
51 L" If you are not running this program as the administrator, you may\n"
52 " need to do so, so that all data and metadata can be backed up.\n"
53 " Otherwise, there may be no way to access the desired data or\n"
54 " metadata without taking ownership of the file or directory.\n"
58 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
60 consume_data_callback_t cb,
67 bool out_buf_malloced;
70 HANDLE hFile = win32_open_existing_file(lte->file_on_disk,
72 if (hFile == INVALID_HANDLE_VALUE) {
73 set_errno_from_GetLastError();
74 ERROR_WITH_ERRNO("Failed to open \"%ls\"", lte->file_on_disk);
75 return WIMLIB_ERR_OPEN;
78 out_buf_malloced = false;
80 if (in_chunk_size <= STACK_MAX) {
81 out_buf = alloca(in_chunk_size);
83 out_buf = MALLOC(in_chunk_size);
84 if (out_buf == NULL) {
85 ret = WIMLIB_ERR_NOMEM;
86 goto out_close_handle;
88 out_buf_malloced = true;
94 bytes_remaining = size;
95 while (bytes_remaining) {
96 DWORD bytesToRead, bytesRead;
98 bytesToRead = min(in_chunk_size, bytes_remaining);
99 if (!ReadFile(hFile, out_buf, bytesToRead, &bytesRead, NULL) ||
100 bytesRead != bytesToRead)
102 set_errno_from_GetLastError();
103 ERROR_WITH_ERRNO("Failed to read data from \"%ls\"",
105 ret = WIMLIB_ERR_READ;
108 bytes_remaining -= bytesRead;
110 ret = (*cb)(out_buf, bytesRead, ctx_or_buf);
114 out_buf += bytesRead;
117 if (out_buf_malloced)
124 struct win32_encrypted_read_ctx {
125 consume_data_callback_t read_prefix_cb;
126 void *read_prefix_ctx_or_buf;
135 win32_encrypted_export_cb(unsigned char *_data, void *_ctx, unsigned long len)
137 const void *data = _data;
138 struct win32_encrypted_read_ctx *ctx = _ctx;
139 u32 in_chunk_size = ctx->in_chunk_size;
142 DEBUG("len = %lu", len);
143 if (ctx->read_prefix_cb) {
144 /* The length of the buffer passed to the ReadEncryptedFileRaw()
145 * export callback is undocumented, so we assume it may be of
147 size_t bytes_to_buffer = min(ctx->bytes_remaining - ctx->buf_filled,
149 while (bytes_to_buffer) {
150 size_t bytes_to_copy_to_buf =
151 min(bytes_to_buffer, in_chunk_size - ctx->buf_filled);
153 memcpy(ctx->buf + ctx->buf_filled, data,
154 bytes_to_copy_to_buf);
155 ctx->buf_filled += bytes_to_copy_to_buf;
156 data += bytes_to_copy_to_buf;
157 bytes_to_buffer -= bytes_to_copy_to_buf;
159 if (ctx->buf_filled == in_chunk_size ||
160 ctx->buf_filled == ctx->bytes_remaining)
162 ret = (*ctx->read_prefix_cb)(ctx->buf,
164 ctx->read_prefix_ctx_or_buf);
166 ctx->wimlib_err_code = ret;
167 /* Shouldn't matter what error code is returned
168 * here, as long as it isn't ERROR_SUCCESS. */
169 return ERROR_READ_FAULT;
171 ctx->bytes_remaining -= ctx->buf_filled;
176 size_t len_to_copy = min(len, ctx->bytes_remaining);
177 ctx->read_prefix_ctx_or_buf = mempcpy(ctx->read_prefix_ctx_or_buf,
180 ctx->bytes_remaining -= len_to_copy;
182 return ERROR_SUCCESS;
186 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
188 consume_data_callback_t cb,
193 struct win32_encrypted_read_ctx export_ctx;
198 DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
199 size, lte->file_on_disk);
201 export_ctx.read_prefix_cb = cb;
202 export_ctx.read_prefix_ctx_or_buf = ctx_or_buf;
203 export_ctx.wimlib_err_code = 0;
205 export_ctx.buf = MALLOC(in_chunk_size);
207 return WIMLIB_ERR_NOMEM;
209 export_ctx.buf = NULL;
211 export_ctx.buf_filled = 0;
212 export_ctx.bytes_remaining = size;
214 err = OpenEncryptedFileRaw(lte->file_on_disk, 0, &file_ctx);
215 if (err != ERROR_SUCCESS) {
216 set_errno_from_win32_error(err);
217 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
218 "for raw read", lte->file_on_disk);
219 ret = WIMLIB_ERR_OPEN;
222 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
223 &export_ctx, file_ctx);
224 if (err != ERROR_SUCCESS) {
225 set_errno_from_win32_error(err);
226 ERROR_WITH_ERRNO("Failed to read encrypted file \"%ls\"",
228 ret = export_ctx.wimlib_err_code;
230 ret = WIMLIB_ERR_READ;
231 } else if (export_ctx.bytes_remaining != 0) {
232 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
233 "encryted file \"%ls\"",
234 size - export_ctx.bytes_remaining, size,
236 ret = WIMLIB_ERR_READ;
240 CloseEncryptedFileRaw(file_ctx);
242 FREE(export_ctx.buf);
248 FILETIME_to_u64(const FILETIME *ft)
250 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
253 /* Load the short name of a file into a WIM dentry.
255 * If we can't read the short filename for some reason, we just ignore the error
256 * and assume the file has no short name. This shouldn't be an issue, since the
257 * short names are essentially obsolete anyway.
260 win32_get_short_name(HANDLE hFile, const wchar_t *path, struct wim_dentry *dentry)
263 /* It's not any harder to just make the NtQueryInformationFile() system
264 * call ourselves, and it saves a dumb call to FindFirstFile() which of
265 * course has to create its own handle. */
267 if (func_NtQueryInformationFile) {
269 IO_STATUS_BLOCK io_status;
270 u8 buf[128] _aligned_attribute(8);
271 const FILE_NAME_INFORMATION *info;
273 status = (*func_NtQueryInformationFile)(hFile, &io_status, buf, sizeof(buf),
274 FileAlternateNameInformation);
275 info = (const FILE_NAME_INFORMATION*)buf;
276 if (status == STATUS_SUCCESS && info->FileNameLength != 0) {
277 dentry->short_name = MALLOC(info->FileNameLength + 2);
278 if (!dentry->short_name)
279 return WIMLIB_ERR_NOMEM;
280 memcpy(dentry->short_name, info->FileName,
281 info->FileNameLength);
282 dentry->short_name[info->FileNameLength / 2] = L'\0';
283 dentry->short_name_nbytes = info->FileNameLength;
289 WIN32_FIND_DATAW dat;
293 hFind = FindFirstFile(path, &dat);
294 if (hFind != INVALID_HANDLE_VALUE) {
295 if (dat.cAlternateFileName[0] != L'\0') {
296 DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
297 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
299 size_t n = short_name_nbytes + sizeof(wchar_t);
300 dentry->short_name = MALLOC(n);
301 if (dentry->short_name) {
302 memcpy(dentry->short_name, dat.cAlternateFileName, n);
303 dentry->short_name_nbytes = short_name_nbytes;
305 ret = WIMLIB_ERR_NOMEM;
314 * win32_query_security_descriptor() - Query a file's security descriptor
316 * We need the file's security descriptor in SECURITY_DESCRIPTOR_RELATIVE
317 * format, and we currently have a handle opened with as many relevant
318 * permissions as possible. At this point, on Windows there are a number of
319 * options for reading a file's security descriptor:
321 * GetFileSecurity(): This takes in a path and returns the
322 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle, not
323 * ours, and the handle created internally doesn't specify
324 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied errors on
325 * some files and directories, even when running as the Administrator.
327 * GetSecurityInfo(): This takes in a handle and returns the security
328 * descriptor split into a bunch of different parts. This should work, but it's
329 * dumb because we have to put the security descriptor back together again.
331 * BackupRead(): This can read the security descriptor, but this is a
332 * difficult-to-use API, probably only works as the Administrator, and the
333 * format of the returned data is not well documented.
335 * NtQuerySecurityObject(): This is exactly what we need, as it takes in a
336 * handle and returns the security descriptor in SECURITY_DESCRIPTOR_RELATIVE
337 * format. Only problem is that it's a ntdll function and therefore not
338 * officially part of the Win32 API. Oh well.
341 win32_query_security_descriptor(HANDLE hFile, const wchar_t *path,
342 SECURITY_INFORMATION requestedInformation,
343 SECURITY_DESCRIPTOR *buf,
344 DWORD bufsize, DWORD *lengthNeeded)
347 if (func_NtQuerySecurityObject) {
350 status = (*func_NtQuerySecurityObject)(hFile,
351 requestedInformation, buf,
352 bufsize, lengthNeeded);
353 /* Since it queries an already-open handle, NtQuerySecurityObject()
354 * apparently returns STATUS_ACCESS_DENIED rather than
355 * STATUS_PRIVILEGE_NOT_HELD. */
356 if (status == STATUS_ACCESS_DENIED)
357 return ERROR_PRIVILEGE_NOT_HELD;
359 return (*func_RtlNtStatusToDosError)(status);
362 if (GetFileSecurity(path, requestedInformation, buf,
363 bufsize, lengthNeeded))
364 return ERROR_SUCCESS;
366 return GetLastError();
370 win32_get_security_descriptor(HANDLE hFile,
372 struct wim_inode *inode,
373 struct wim_sd_set *sd_set,
374 struct win32_capture_state *state,
377 SECURITY_INFORMATION requestedInformation;
385 requestedInformation = DACL_SECURITY_INFORMATION |
386 SACL_SECURITY_INFORMATION |
387 OWNER_SECURITY_INFORMATION |
388 GROUP_SECURITY_INFORMATION;
390 bufsize = sizeof(_buf);
392 err = win32_query_security_descriptor(hFile, path,
393 requestedInformation,
394 (SECURITY_DESCRIPTOR*)buf,
395 bufsize, &lenNeeded);
398 goto have_descriptor;
399 case ERROR_INSUFFICIENT_BUFFER:
400 wimlib_assert(buf == _buf);
401 buf = MALLOC(lenNeeded);
403 return WIMLIB_ERR_NOMEM;
406 case ERROR_PRIVILEGE_NOT_HELD:
407 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS)
409 if (requestedInformation & SACL_SECURITY_INFORMATION) {
410 state->num_get_sacl_priv_notheld++;
411 requestedInformation &= ~SACL_SECURITY_INFORMATION;
415 case ERROR_ACCESS_DENIED:
416 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS)
418 state->num_get_sd_access_denied++;
423 set_errno_from_win32_error(err);
424 ERROR_WITH_ERRNO("Failed to read security descriptor of \"%ls\"", path);
425 ret = WIMLIB_ERR_READ;
431 inode->i_security_id = sd_set_add_sd(sd_set, buf, lenNeeded);
432 if (inode->i_security_id < 0)
433 ret = WIMLIB_ERR_NOMEM;
443 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
445 size_t path_num_chars,
446 struct add_image_params *params,
447 struct win32_capture_state *state,
450 /* Reads the directory entries of directory and recursively calls
451 * win32_build_dentry_tree() on them. */
453 win32_recurse_directory(HANDLE hDir,
455 size_t dir_path_num_chars,
456 struct wim_dentry *root,
457 struct add_image_params *params,
458 struct win32_capture_state *state,
463 DEBUG("Recurse to directory \"%ls\"", dir_path);
465 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
466 * which we opened with FILE_FLAG_BACKUP_SEMANTICS (probably not the
467 * case for the FindFirstFile() API; it's not documented). */
469 if (!func_NtQueryDirectoryFile)
470 goto use_FindFirstFile;
473 IO_STATUS_BLOCK io_status;
474 const size_t bufsize = 8192;
476 BOOL restartScan = TRUE;
477 const FILE_NAMES_INFORMATION *info;
479 buf = MALLOC(bufsize);
481 return WIMLIB_ERR_NOMEM;
483 status = (*func_NtQueryDirectoryFile)(hDir, NULL, NULL, NULL,
484 &io_status, buf, bufsize,
485 FileNamesInformation,
486 FALSE, NULL, restartScan);
488 if (status != STATUS_SUCCESS) {
489 if (status == STATUS_NO_MORE_FILES ||
490 status == STATUS_NO_MORE_ENTRIES ||
491 status == STATUS_NO_MORE_MATCHES) {
493 } else if (status == STATUS_NOT_IMPLEMENTED ||
494 status == STATUS_NOT_SUPPORTED ||
495 status == STATUS_INVALID_INFO_CLASS) {
497 goto use_FindFirstFile;
499 set_errno_from_nt_status(status);
500 ERROR_WITH_ERRNO("Failed to read directory "
501 "\"%ls\"", dir_path);
502 ret = WIMLIB_ERR_READ;
506 wimlib_assert(io_status.Information != 0);
507 info = (const FILE_NAMES_INFORMATION*)buf;
509 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
510 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
511 info->FileName[1] == L'.'))
514 struct wim_dentry *child;
516 p = dir_path + dir_path_num_chars;
518 p = wmempcpy(p, info->FileName,
519 info->FileNameLength / 2);
522 ret = win32_build_dentry_tree_recursive(
530 dir_path[dir_path_num_chars] = L'\0';
535 dentry_add_child(root, child);
537 if (info->NextEntryOffset == 0)
539 info = (const FILE_NAMES_INFORMATION*)
540 ((const u8*)info + info->NextEntryOffset);
550 WIN32_FIND_DATAW dat;
554 /* Begin reading the directory by calling FindFirstFileW. Unlike UNIX
555 * opendir(), FindFirstFileW has file globbing built into it. But this
556 * isn't what we actually want, so just add a dummy glob to get all
558 dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
559 dir_path[dir_path_num_chars + 1] = L'*';
560 dir_path[dir_path_num_chars + 2] = L'\0';
561 hFind = FindFirstFile(dir_path, &dat);
562 dir_path[dir_path_num_chars] = L'\0';
564 if (hFind == INVALID_HANDLE_VALUE) {
565 err = GetLastError();
566 if (err == ERROR_FILE_NOT_FOUND) {
569 set_errno_from_win32_error(err);
570 ERROR_WITH_ERRNO("Failed to read directory \"%ls\"",
572 return WIMLIB_ERR_READ;
577 /* Skip . and .. entries */
578 if (dat.cFileName[0] == L'.' &&
579 (dat.cFileName[1] == L'\0' ||
580 (dat.cFileName[1] == L'.' &&
581 dat.cFileName[2] == L'\0')))
583 size_t filename_len = wcslen(dat.cFileName);
585 dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
586 wmemcpy(dir_path + dir_path_num_chars + 1,
590 struct wim_dentry *child;
591 size_t path_len = dir_path_num_chars + 1 + filename_len;
592 ret = win32_build_dentry_tree_recursive(&child,
598 dir_path[dir_path_num_chars] = L'\0';
602 dentry_add_child(root, child);
603 } while (FindNextFile(hFind, &dat));
604 err = GetLastError();
605 if (err != ERROR_NO_MORE_FILES) {
606 set_errno_from_win32_error(err);
607 ERROR_WITH_ERRNO("Failed to read directory \"%ls\"", dir_path);
609 ret = WIMLIB_ERR_READ;
616 /* Reparse point fixup status code */
618 /* Reparse point corresponded to an absolute symbolic link or junction
619 * point that pointed outside the directory tree being captured, and
620 * therefore was excluded. */
623 /* Reparse point was not fixed as it was either a relative symbolic
624 * link, a mount point, or something else we could not understand. */
627 /* Reparse point corresponded to an absolute symbolic link or junction
628 * point that pointed inside the directory tree being captured, where
629 * the target was specified by a "full" \??\ prefixed path, and
630 * therefore was fixed to be relative to the root of the directory tree
632 RP_FIXED_FULLPATH = 0x2,
634 /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
635 * have the \??\ prefix. It may have begun with a drive letter though.
637 RP_FIXED_ABSPATH = 0x4,
639 /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
640 RP_FIXED = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
643 /* Given the "substitute name" target of a Windows reparse point, try doing a
644 * fixup where we change it to be absolute relative to the root of the directory
645 * tree being captured.
647 * Note that this is only executed when WIMLIB_ADD_FLAG_RPFIX has been
650 * @capture_root_ino and @capture_root_dev indicate the inode number and device
651 * of the root of the directory tree being captured. They are meant to identify
652 * this directory (as an alternative to its actual path, which could potentially
653 * be reached via multiple destinations due to other symbolic links). This may
654 * not work properly on FAT, which doesn't seem to supply proper inode numbers
655 * or file IDs. However, FAT doesn't support reparse points so this function
656 * wouldn't even be called anyway.
658 static enum rp_status
659 win32_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
660 u64 capture_root_ino, u64 capture_root_dev,
663 u16 target_nchars = *target_nbytes_p / 2;
664 size_t stripped_chars;
665 wchar_t *orig_target;
668 ret = parse_substitute_name(target, *target_nbytes_p, rptag);
671 stripped_chars = ret;
674 target[target_nchars] = L'\0';
675 orig_target = target;
676 target = capture_fixup_absolute_symlink(target + stripped_chars,
677 capture_root_ino, capture_root_dev);
680 target_nchars = wcslen(target);
681 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
682 *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
683 DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
685 return RP_FIXED_FULLPATH;
687 return RP_FIXED_ABSPATH;
690 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
693 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
694 u64 capture_root_ino, u64 capture_root_dev,
697 struct reparse_data rpdata;
699 enum rp_status rp_status;
701 ret = parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata);
705 rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
706 &rpdata.substitute_name_nbytes,
709 le32_to_cpu(*(le32*)rpbuf));
710 if (rp_status & RP_FIXED) {
711 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
712 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
713 wmemcpy(substitute_name_copy, rpdata.substitute_name,
714 rpdata.substitute_name_nbytes / 2);
715 rpdata.substitute_name = substitute_name_copy;
716 rpdata.print_name = substitute_name_copy;
717 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
718 if (rp_status == RP_FIXED_FULLPATH) {
719 /* "full path", meaning \??\ prefixed. We should not
720 * include this prefix in the print name, as it is
721 * apparently meant for the filesystem driver only. */
722 rpdata.print_name += 4;
723 rpdata.print_name_nbytes -= 8;
725 ret = make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
731 if (rp_status == RP_EXCLUDED) {
732 size_t print_name_nchars = rpdata.print_name_nbytes / 2;
733 wchar_t print_name0[print_name_nchars + 1];
734 print_name0[print_name_nchars] = L'\0';
735 wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
736 WARNING("Ignoring %ls pointing out of capture directory:\n"
737 " \"%ls\" -> \"%ls\"\n"
738 " (Use --norpfix to capture all symbolic links "
739 "and junction points as-is)",
740 (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK) ?
741 L"absolute symbolic link" : L"junction point",
750 * Loads the reparse point data from a reparse point into memory, optionally
751 * fixing the targets of absolute symbolic links and junction points to be
752 * relative to the root of capture.
754 * @hFile: Open handle to the reparse point.
755 * @path: Path to the reparse point. Used for error messages only.
756 * @params: Additional parameters, including whether to do reparse point fixups
758 * @rpbuf: Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
759 * the reparse point buffer will be loaded.
760 * @rpbuflen_ret: On success, the length of the reparse point buffer in bytes
761 * is written to this location.
764 * On success, returns an `enum rp_status' value that indicates if and/or
765 * how the reparse point fixup was done.
767 * On failure, returns a negative value that is a negated WIMLIB_ERR_*
771 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
772 struct add_image_params *params,
773 u8 *rpbuf, u16 *rpbuflen_ret)
780 DEBUG("Loading reparse data from \"%ls\"", path);
781 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
782 NULL, /* "Not used with this operation; set to NULL" */
783 0, /* "Not used with this operation; set to 0" */
784 rpbuf, /* "A pointer to a buffer that
785 receives the reparse point data */
786 REPARSE_POINT_MAX_SIZE, /* "The size of the output
791 set_errno_from_GetLastError();
792 ERROR_WITH_ERRNO("Failed to get reparse data of \"%ls\"", path);
793 return -WIMLIB_ERR_READ;
795 if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
796 ERROR("Reparse data on \"%ls\" is invalid", path);
797 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
800 rpbuflen = bytesReturned;
801 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
802 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
803 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
804 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
806 /* Try doing reparse point fixup */
807 ret = win32_capture_try_rpfix(rpbuf,
809 params->capture_root_ino,
810 params->capture_root_dev,
815 *rpbuflen_ret = rpbuflen;
820 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
823 *(u64*)_size_ret += len;
824 return ERROR_SUCCESS;
828 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
834 err = OpenEncryptedFileRaw(path, 0, &file_ctx);
835 if (err != ERROR_SUCCESS) {
836 set_errno_from_win32_error(err);
837 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
838 "for raw read", path);
839 return WIMLIB_ERR_OPEN;
842 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
844 if (err != ERROR_SUCCESS) {
845 set_errno_from_win32_error(err);
846 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
848 ret = WIMLIB_ERR_READ;
852 CloseEncryptedFileRaw(file_ctx);
856 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
857 * stream); calculates its SHA1 message digest and either creates a `struct
858 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
859 * wim_lookup_table_entry' for an identical stream.
861 * @path: Path to the file (UTF-16LE).
863 * @path_num_chars: Number of 2-byte characters in @path.
865 * @inode: WIM inode to save the stream into.
867 * @lookup_table: Stream lookup table for the WIM.
869 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
872 * Returns 0 on success; nonzero on failure.
875 win32_capture_stream(const wchar_t *path,
876 size_t path_num_chars,
877 struct wim_inode *inode,
878 struct wim_lookup_table *lookup_table,
879 WIN32_FIND_STREAM_DATA *dat)
881 struct wim_ads_entry *ads_entry;
882 struct wim_lookup_table_entry *lte;
884 wchar_t *stream_name, *colon;
885 size_t stream_name_nchars;
886 bool is_named_stream;
889 size_t spath_buf_nbytes;
890 const wchar_t *relpath_prefix;
891 const wchar_t *colonchar;
893 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
895 /* The stream name should be returned as :NAME:TYPE */
896 stream_name = dat->cStreamName;
897 if (*stream_name != L':')
898 goto out_invalid_stream_name;
900 colon = wcschr(stream_name, L':');
902 goto out_invalid_stream_name;
904 if (wcscmp(colon + 1, L"$DATA")) {
905 /* Not a DATA stream */
912 stream_name_nchars = colon - stream_name;
913 is_named_stream = (stream_name_nchars != 0);
915 if (is_named_stream) {
916 /* Allocate an ADS entry for the named stream. */
917 ads_entry = inode_add_ads_utf16le(inode, stream_name,
918 stream_name_nchars * sizeof(wchar_t));
920 ret = WIMLIB_ERR_NOMEM;
925 /* If zero length stream, no lookup table entry needed. */
926 if ((u64)dat->StreamSize.QuadPart == 0) {
931 /* Create a UTF-16LE string @spath that gives the filename, then a
932 * colon, then the stream name. Or, if it's an unnamed stream, just the
933 * filename. It is MALLOC()'ed so that it can be saved in the
934 * wim_lookup_table_entry if needed.
936 * As yet another special case, relative paths need to be changed to
937 * begin with an explicit "./" so that, for example, a file t:ads, where
938 * :ads is the part we added, is not interpreted as a file on the t:
940 spath_nchars = path_num_chars;
941 relpath_prefix = L"";
943 if (is_named_stream) {
944 spath_nchars += 1 + stream_name_nchars;
946 if (path_num_chars == 1 && !is_any_path_separator(path[0])) {
948 static const wchar_t _relpath_prefix[] =
949 {L'.', OS_PREFERRED_PATH_SEPARATOR, L'\0'};
950 relpath_prefix = _relpath_prefix;
954 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
955 spath = MALLOC(spath_buf_nbytes);
957 tsprintf(spath, L"%ls%ls%ls%ls",
958 relpath_prefix, path, colonchar, stream_name);
960 /* Make a new wim_lookup_table_entry */
961 lte = new_lookup_table_entry();
963 ret = WIMLIB_ERR_NOMEM;
966 lte->file_on_disk = spath;
968 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
970 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
971 ret = win32_get_encrypted_file_size(path, &encrypted_size);
974 lte->size = encrypted_size;
976 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
977 lte->size = (u64)dat->StreamSize.QuadPart;
981 if (is_named_stream) {
982 stream_id = ads_entry->stream_id;
983 ads_entry->lte = lte;
988 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
994 out_invalid_stream_name:
995 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
996 ret = WIMLIB_ERR_READ;
1000 /* Load information about the streams of an open file into a WIM inode.
1002 * By default, we use the NtQueryInformationFile() system call instead of
1003 * FindFirstStream() and FindNextStream(). This is done for two reasons:
1005 * - FindFirstStream() opens its own handle to the file or directory and
1006 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
1007 * causing access denied errors on certain files (even when running as the
1009 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
1010 * and later, whereas the stream support in NtQueryInformationFile() was
1011 * already present in Windows XP.
1014 win32_capture_streams(HANDLE *hFile_p,
1015 const wchar_t *path,
1016 size_t path_num_chars,
1017 struct wim_inode *inode,
1018 struct wim_lookup_table *lookup_table,
1022 WIN32_FIND_STREAM_DATA dat;
1025 u8 _buf[8192] _aligned_attribute(8);
1028 IO_STATUS_BLOCK io_status;
1030 const FILE_STREAM_INFORMATION *info;
1035 DEBUG("Capturing streams from \"%ls\"", path);
1037 if (!(vol_flags & FILE_NAMED_STREAMS))
1041 if (!func_NtQueryInformationFile)
1042 goto use_FindFirstStream;
1045 bufsize = sizeof(_buf);
1047 /* Get a buffer containing the stream information. */
1049 status = (*func_NtQueryInformationFile)(*hFile_p, &io_status,
1051 FileStreamInformation);
1052 if (status == STATUS_SUCCESS) {
1054 } else if (status == STATUS_BUFFER_OVERFLOW) {
1059 newbuf = MALLOC(bufsize);
1061 newbuf = REALLOC(buf, bufsize);
1064 ret = WIMLIB_ERR_NOMEM;
1068 } else if (status == STATUS_NOT_IMPLEMENTED ||
1069 status == STATUS_NOT_SUPPORTED ||
1070 status == STATUS_INVALID_INFO_CLASS) {
1071 goto use_FindFirstStream;
1073 set_errno_from_nt_status(status);
1074 ERROR_WITH_ERRNO("Failed to read streams of %ls", path);
1075 ret = WIMLIB_ERR_READ;
1080 if (io_status.Information == 0) {
1081 /* No stream information. */
1086 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1087 /* OpenEncryptedFileRaw() seems to fail with
1088 * ERROR_SHARING_VIOLATION if there are any handles opened to
1090 CloseHandle(*hFile_p);
1091 *hFile_p = INVALID_HANDLE_VALUE;
1094 /* Parse one or more stream information structures. */
1095 info = (const FILE_STREAM_INFORMATION*)buf;
1097 if (info->StreamNameLength <= sizeof(dat.cStreamName) - 2) {
1098 dat.StreamSize = info->StreamSize;
1099 memcpy(dat.cStreamName, info->StreamName, info->StreamNameLength);
1100 dat.cStreamName[info->StreamNameLength / 2] = L'\0';
1102 /* Capture the stream. */
1103 ret = win32_capture_stream(path, path_num_chars, inode,
1104 lookup_table, &dat);
1108 if (info->NextEntryOffset == 0) {
1109 /* No more stream information. */
1113 /* Advance to next stream information. */
1114 info = (const FILE_STREAM_INFORMATION*)
1115 ((const u8*)info + info->NextEntryOffset);
1118 /* Free buffer if allocated on heap. */
1122 #endif /* WITH_NTDLL */
1124 use_FindFirstStream:
1125 if (win32func_FindFirstStreamW == NULL)
1127 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1128 if (hFind == INVALID_HANDLE_VALUE) {
1129 err = GetLastError();
1130 if (err == ERROR_CALL_NOT_IMPLEMENTED ||
1131 err == ERROR_NOT_SUPPORTED ||
1132 err == ERROR_INVALID_FUNCTION ||
1133 err == ERROR_INVALID_PARAMETER)
1136 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1137 * points and directories */
1138 if ((inode->i_attributes &
1139 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1140 && err == ERROR_HANDLE_EOF)
1142 DEBUG("ERROR_HANDLE_EOF (ok)");
1145 if (err == ERROR_ACCESS_DENIED) {
1146 WARNING("Failed to look up data streams "
1147 "of \"%ls\": Access denied!\n%ls",
1148 path, capture_access_denied_msg);
1151 set_errno_from_win32_error(err);
1152 ERROR_WITH_ERRNO("Failed to look up data streams "
1153 "of \"%ls\"", path);
1154 return WIMLIB_ERR_READ;
1159 ret = win32_capture_stream(path,
1161 inode, lookup_table,
1164 goto out_find_close;
1165 } while (win32func_FindNextStreamW(hFind, &dat));
1166 err = GetLastError();
1167 if (err != ERROR_HANDLE_EOF) {
1168 set_errno_from_win32_error(err);
1169 ERROR_WITH_ERRNO("Error reading data streams from "
1171 ret = WIMLIB_ERR_READ;
1178 /* FindFirstStream() API is not available, or the volume does not
1179 * support named streams. Only capture the unnamed data stream. */
1180 DEBUG("Only capturing unnamed data stream");
1181 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1182 FILE_ATTRIBUTE_REPARSE_POINT))
1185 wcscpy(dat.cStreamName, L"::$DATA");
1186 dat.StreamSize.QuadPart = file_size;
1187 return win32_capture_stream(path, path_num_chars,
1188 inode, lookup_table, &dat);
1192 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1194 size_t path_num_chars,
1195 struct add_image_params *params,
1196 struct win32_capture_state *state,
1199 struct wim_dentry *root = NULL;
1200 struct wim_inode *inode;
1208 DWORD desiredAccess;
1210 params->progress.scan.cur_path = path;
1212 if (exclude_path(path, path_num_chars, params->config, true)) {
1213 if (params->add_flags & WIMLIB_ADD_FLAG_ROOT) {
1214 ERROR("Cannot exclude the root directory from capture");
1215 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1218 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED);
1224 if (path_num_chars >= 4 &&
1225 !wmemcmp(path, L"\\\\?\\", 4) &&
1226 path_num_chars + 1 - 4 > MAX_PATH &&
1227 state->num_long_path_warnings < MAX_CAPTURE_LONG_PATH_WARNINGS)
1229 WARNING("Path \"%ls\" exceeds MAX_PATH", path);
1230 if (++state->num_long_path_warnings == MAX_CAPTURE_LONG_PATH_WARNINGS)
1231 WARNING("Suppressing further warnings about long paths.");
1235 do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK);
1237 desiredAccess = FILE_READ_DATA | FILE_READ_ATTRIBUTES |
1238 READ_CONTROL | ACCESS_SYSTEM_SECURITY;
1240 hFile = win32_open_existing_file(path, desiredAccess);
1241 if (hFile == INVALID_HANDLE_VALUE) {
1242 err = GetLastError();
1243 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD) {
1244 if (desiredAccess & ACCESS_SYSTEM_SECURITY) {
1245 desiredAccess &= ~ACCESS_SYSTEM_SECURITY;
1248 if (desiredAccess & READ_CONTROL) {
1249 desiredAccess &= ~READ_CONTROL;
1253 set_errno_from_GetLastError();
1254 ERROR_WITH_ERRNO("Failed to open \"%ls\" for reading", path);
1255 ret = WIMLIB_ERR_OPEN;
1259 BY_HANDLE_FILE_INFORMATION file_info;
1260 if (!GetFileInformationByHandle(hFile, &file_info)) {
1261 set_errno_from_GetLastError();
1262 ERROR_WITH_ERRNO("Failed to get file information for \"%ls\"",
1264 ret = WIMLIB_ERR_STAT;
1265 goto out_close_handle;
1268 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1269 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1270 ret = win32_get_reparse_data(hFile, path, params,
1273 /* WIMLIB_ERR_* (inverted) */
1275 goto out_close_handle;
1276 } else if (ret & RP_FIXED) {
1278 } else if (ret == RP_EXCLUDED) {
1280 goto out_close_handle;
1286 /* Create a WIM dentry with an associated inode, which may be shared.
1288 * However, we need to explicitly check for directories and files with
1289 * only 1 link and refuse to hard link them. This is because Windows
1290 * has a bug where it can return duplicate File IDs for files and
1291 * directories on the FAT filesystem. */
1292 ret = inode_table_new_dentry(¶ms->inode_table,
1293 path_basename_with_len(path, path_num_chars),
1294 ((u64)file_info.nFileIndexHigh << 32) |
1295 (u64)file_info.nFileIndexLow,
1296 file_info.dwVolumeSerialNumber,
1297 (file_info.nNumberOfLinks <= 1 ||
1298 (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1301 goto out_close_handle;
1303 ret = win32_get_short_name(hFile, path, root);
1305 goto out_close_handle;
1307 inode = root->d_inode;
1309 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1310 goto out_close_handle;
1312 inode->i_attributes = file_info.dwFileAttributes;
1313 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1314 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1315 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1316 inode->i_resolved = 1;
1318 params->add_flags &= ~WIMLIB_ADD_FLAG_ROOT;
1320 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1321 && (vol_flags & FILE_PERSISTENT_ACLS))
1323 ret = win32_get_security_descriptor(hFile, path, inode,
1324 ¶ms->sd_set, state,
1327 goto out_close_handle;
1330 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1331 (u64)file_info.nFileSizeLow;
1334 /* Capture the unnamed data stream (only should be present for regular
1335 * files) and any alternate data streams. */
1336 ret = win32_capture_streams(&hFile,
1340 params->lookup_table,
1344 goto out_close_handle;
1346 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1347 /* Reparse point: set the reparse data (which we read already)
1349 inode->i_not_rpfixed = not_rpfixed;
1350 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1351 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1352 params->lookup_table);
1353 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1354 /* Directory (not a reparse point) --- recurse to children */
1356 if (hFile == INVALID_HANDLE_VALUE) {
1357 /* Re-open handle that was closed to read raw encrypted
1359 hFile = win32_open_existing_file(path, FILE_READ_DATA);
1360 if (hFile == INVALID_HANDLE_VALUE) {
1361 set_errno_from_GetLastError();
1362 ERROR_WITH_ERRNO("Failed to reopen \"%ls\"",
1364 ret = WIMLIB_ERR_OPEN;
1365 goto out_close_handle;
1368 ret = win32_recurse_directory(hFile,
1382 free_dentry_tree(root, params->lookup_table);
1387 win32_do_capture_warnings(const wchar_t *path,
1388 const struct win32_capture_state *state,
1391 if (state->num_get_sacl_priv_notheld == 0 &&
1392 state->num_get_sd_access_denied == 0)
1395 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1396 if (state->num_get_sacl_priv_notheld != 0) {
1397 WARNING("- Could not capture SACL (System Access Control List)\n"
1398 " on %lu files or directories.",
1399 state->num_get_sacl_priv_notheld);
1401 if (state->num_get_sd_access_denied != 0) {
1402 WARNING("- Could not capture security descriptor at all\n"
1403 " on %lu files or directories.",
1404 state->num_get_sd_access_denied);
1406 WARNING("To fully capture all security descriptors, run the program\n"
1407 " with Administrator rights.");
1410 #define WINDOWS_NT_MAX_PATH 32768
1412 /* Win32 version of capturing a directory tree */
1414 win32_build_dentry_tree(struct wim_dentry **root_ret,
1415 const wchar_t *root_disk_path,
1416 struct add_image_params *params)
1421 struct win32_capture_state state;
1424 bool need_prefix_free = false;
1426 if (!win32func_FindFirstStreamW
1428 && !func_NtQueryInformationFile
1432 WARNING("Running on Windows XP or earlier; "
1433 "alternate data streams will not be captured.");
1436 path_nchars = wcslen(root_disk_path);
1437 if (path_nchars > WINDOWS_NT_MAX_PATH)
1438 return WIMLIB_ERR_INVALID_PARAM;
1440 ret = win32_get_file_and_vol_ids(root_disk_path,
1441 ¶ms->capture_root_ino,
1442 ¶ms->capture_root_dev);
1444 ERROR_WITH_ERRNO("Can't open %ls", root_disk_path);
1448 win32_get_vol_flags(root_disk_path, &vol_flags, NULL);
1450 /* WARNING: There is no check for overflow later when this buffer is
1451 * being used! But it's as long as the maximum path length understood
1452 * by Windows NT (which is NOT the same as MAX_PATH). */
1453 path = MALLOC(WINDOWS_NT_MAX_PATH * sizeof(wchar_t));
1455 return WIMLIB_ERR_NOMEM;
1457 /* Work around defective behavior in Windows where paths longer than 260
1458 * characters are not supported by default; instead they need to be
1459 * turned into absolute paths and prefixed with "\\?\". */
1461 if (wcsncmp(root_disk_path, L"\\\\?\\", 4)) {
1462 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 4,
1465 if (dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 4) {
1466 WARNING("Can't get full path name for \"%ls\"", root_disk_path);
1467 wmemcpy(path, root_disk_path, path_nchars + 1);
1469 wmemcpy(path, L"\\\\?\\", 4);
1470 path_nchars = 4 + dret;
1471 /* Update pattern prefix */
1472 if (params->config != NULL)
1474 params->config->_prefix = TSTRDUP(path);
1475 params->config->_prefix_num_tchars = path_nchars;
1476 if (params->config->_prefix == NULL)
1478 ret = WIMLIB_ERR_NOMEM;
1481 need_prefix_free = true;
1485 wmemcpy(path, root_disk_path, path_nchars + 1);
1488 memset(&state, 0, sizeof(state));
1489 ret = win32_build_dentry_tree_recursive(root_ret, path,
1490 path_nchars, params,
1492 if (need_prefix_free)
1493 FREE(params->config->_prefix);
1497 win32_do_capture_warnings(root_disk_path, &state, params->add_flags);
1501 #endif /* __WIN32__ */