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,
92 HANDLE hFile = win32_open_existing_file(lte->file_on_disk,
94 if (hFile == INVALID_HANDLE_VALUE) {
95 set_errno_from_GetLastError();
96 ERROR_WITH_ERRNO("Failed to open \"%ls\"", lte->file_on_disk);
97 return WIMLIB_ERR_OPEN;
101 out_buf = alloca(WIM_CHUNK_SIZE);
103 out_buf = ctx_or_buf;
105 bytes_remaining = size;
106 while (bytes_remaining) {
107 DWORD bytesToRead, bytesRead;
109 bytesToRead = min(WIM_CHUNK_SIZE, bytes_remaining);
110 if (!ReadFile(hFile, out_buf, bytesToRead, &bytesRead, NULL) ||
111 bytesRead != bytesToRead)
113 set_errno_from_GetLastError();
114 ERROR_WITH_ERRNO("Failed to read data from \"%ls\"",
116 ret = WIMLIB_ERR_READ;
119 bytes_remaining -= bytesRead;
121 ret = (*cb)(out_buf, bytesRead, ctx_or_buf);
125 out_buf += bytesRead;
132 struct win32_encrypted_read_ctx {
133 consume_data_callback_t read_prefix_cb;
134 void *read_prefix_ctx_or_buf;
142 win32_encrypted_export_cb(unsigned char *_data, void *_ctx, unsigned long len)
144 const void *data = _data;
145 struct win32_encrypted_read_ctx *ctx = _ctx;
148 DEBUG("len = %lu", len);
149 if (ctx->read_prefix_cb) {
150 /* The length of the buffer passed to the ReadEncryptedFileRaw()
151 * export callback is undocumented, so we assume it may be of
153 size_t bytes_to_buffer = min(ctx->bytes_remaining - ctx->buf_filled,
155 while (bytes_to_buffer) {
156 size_t bytes_to_copy_to_buf =
157 min(bytes_to_buffer, WIM_CHUNK_SIZE - ctx->buf_filled);
159 memcpy(ctx->buf + ctx->buf_filled, data,
160 bytes_to_copy_to_buf);
161 ctx->buf_filled += bytes_to_copy_to_buf;
162 data += bytes_to_copy_to_buf;
163 bytes_to_buffer -= bytes_to_copy_to_buf;
165 if (ctx->buf_filled == WIM_CHUNK_SIZE ||
166 ctx->buf_filled == ctx->bytes_remaining)
168 ret = (*ctx->read_prefix_cb)(ctx->buf,
170 ctx->read_prefix_ctx_or_buf);
172 ctx->wimlib_err_code = ret;
173 /* Shouldn't matter what error code is returned
174 * here, as long as it isn't ERROR_SUCCESS. */
175 return ERROR_READ_FAULT;
177 ctx->bytes_remaining -= ctx->buf_filled;
182 size_t len_to_copy = min(len, ctx->bytes_remaining);
183 ctx->read_prefix_ctx_or_buf = mempcpy(ctx->read_prefix_ctx_or_buf,
186 ctx->bytes_remaining -= len_to_copy;
188 return ERROR_SUCCESS;
192 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
194 consume_data_callback_t cb,
198 struct win32_encrypted_read_ctx export_ctx;
203 DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
204 size, lte->file_on_disk);
206 export_ctx.read_prefix_cb = cb;
207 export_ctx.read_prefix_ctx_or_buf = ctx_or_buf;
208 export_ctx.wimlib_err_code = 0;
210 export_ctx.buf = MALLOC(WIM_CHUNK_SIZE);
212 return WIMLIB_ERR_NOMEM;
214 export_ctx.buf = NULL;
216 export_ctx.buf_filled = 0;
217 export_ctx.bytes_remaining = size;
219 err = OpenEncryptedFileRaw(lte->file_on_disk, 0, &file_ctx);
220 if (err != ERROR_SUCCESS) {
221 set_errno_from_win32_error(err);
222 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
223 "for raw read", lte->file_on_disk);
224 ret = WIMLIB_ERR_OPEN;
227 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
228 &export_ctx, file_ctx);
229 if (err != ERROR_SUCCESS) {
230 set_errno_from_win32_error(err);
231 ERROR_WITH_ERRNO("Failed to read encrypted file \"%ls\"",
233 ret = export_ctx.wimlib_err_code;
235 ret = WIMLIB_ERR_READ;
236 } else if (export_ctx.bytes_remaining != 0) {
237 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
238 "encryted file \"%ls\"",
239 size - export_ctx.bytes_remaining, size,
241 ret = WIMLIB_ERR_READ;
245 CloseEncryptedFileRaw(file_ctx);
247 FREE(export_ctx.buf);
253 FILETIME_to_u64(const FILETIME *ft)
255 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
258 /* Load the short name of a file into a WIM dentry.
260 * If we can't read the short filename for some reason, we just ignore the error
261 * and assume the file has no short name. This shouldn't be an issue, since the
262 * short names are essentially obsolete anyway.
265 win32_get_short_name(HANDLE hFile, const wchar_t *path, struct wim_dentry *dentry)
268 /* It's not any harder to just make the NtQueryInformationFile() system
269 * call ourselves, and it saves a dumb call to FindFirstFile() which of
270 * course has to create its own handle. */
273 IO_STATUS_BLOCK io_status;
274 u8 buf[128] _aligned_attribute(8);
275 const FILE_NAME_INFORMATION *info;
277 status = NtQueryInformationFile(hFile, &io_status, buf, sizeof(buf),
278 FileAlternateNameInformation);
279 info = (const FILE_NAME_INFORMATION*)buf;
280 if (status == STATUS_SUCCESS && info->FileNameLength != 0) {
281 dentry->short_name = MALLOC(info->FileNameLength + 2);
282 if (!dentry->short_name)
283 return WIMLIB_ERR_NOMEM;
284 memcpy(dentry->short_name, info->FileName,
285 info->FileNameLength);
286 dentry->short_name[info->FileNameLength / 2] = L'\0';
287 dentry->short_name_nbytes = info->FileNameLength;
291 WIN32_FIND_DATAW dat;
295 hFind = FindFirstFile(path, &dat);
296 if (hFind != INVALID_HANDLE_VALUE) {
297 if (dat.cAlternateFileName[0] != L'\0') {
298 DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
299 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
301 size_t n = short_name_nbytes + sizeof(wchar_t);
302 dentry->short_name = MALLOC(n);
303 if (dentry->short_name) {
304 memcpy(dentry->short_name, dat.cAlternateFileName, n);
305 dentry->short_name_nbytes = short_name_nbytes;
307 ret = WIMLIB_ERR_NOMEM;
317 * win32_query_security_descriptor() - Query a file's security descriptor
319 * We need the file's security descriptor in SECURITY_DESCRIPTOR_RELATIVE
320 * format, and we currently have a handle opened with as many relevant
321 * permissions as possible. At this point, on Windows there are a number of
322 * options for reading a file's security descriptor:
324 * GetFileSecurity(): This takes in a path and returns the
325 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle, not
326 * ours, and the handle created internally doesn't specify
327 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied errors on
328 * some files and directories, even when running as the Administrator.
330 * GetSecurityInfo(): This takes in a handle and returns the security
331 * descriptor split into a bunch of different parts. This should work, but it's
332 * dumb because we have to put the security descriptor back together again.
334 * BackupRead(): This can read the security descriptor, but this is a
335 * difficult-to-use API, probably only works as the Administrator, and the
336 * format of the returned data is not well documented.
338 * NtQuerySecurityObject(): This is exactly what we need, as it takes in a
339 * handle and returns the security descriptor in SECURITY_DESCRIPTOR_RELATIVE
340 * format. Only problem is that it's a ntdll function and therefore not
341 * officially part of the Win32 API. Oh well.
344 win32_query_security_descriptor(HANDLE hFile, const wchar_t *path,
345 SECURITY_INFORMATION requestedInformation,
346 SECURITY_DESCRIPTOR *buf,
347 DWORD bufsize, DWORD *lengthNeeded)
352 status = NtQuerySecurityObject(hFile, requestedInformation, buf,
353 bufsize, lengthNeeded);
354 /* Since it queries an already-open handle, NtQuerySecurityObject()
355 * apparently returns STATUS_ACCESS_DENIED rather than
356 * STATUS_PRIVILEGE_NOT_HELD. */
357 if (status == STATUS_ACCESS_DENIED)
358 return ERROR_PRIVILEGE_NOT_HELD;
360 return RtlNtStatusToDosError(status);
362 if (GetFileSecurity(path, requestedInformation, buf,
363 bufsize, lengthNeeded))
364 return ERROR_SUCCESS;
366 return GetLastError();
371 win32_get_security_descriptor(HANDLE hFile,
373 struct wim_inode *inode,
374 struct wim_sd_set *sd_set,
375 struct win32_capture_state *state,
378 SECURITY_INFORMATION requestedInformation;
386 requestedInformation = DACL_SECURITY_INFORMATION |
387 SACL_SECURITY_INFORMATION |
388 OWNER_SECURITY_INFORMATION |
389 GROUP_SECURITY_INFORMATION;
391 bufsize = sizeof(_buf);
393 err = win32_query_security_descriptor(hFile, path,
394 requestedInformation,
395 (SECURITY_DESCRIPTOR*)buf,
396 bufsize, &lenNeeded);
399 goto have_descriptor;
400 case ERROR_INSUFFICIENT_BUFFER:
401 wimlib_assert(buf == _buf);
402 buf = MALLOC(lenNeeded);
404 return WIMLIB_ERR_NOMEM;
407 case ERROR_PRIVILEGE_NOT_HELD:
408 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS)
410 if (requestedInformation & SACL_SECURITY_INFORMATION) {
411 state->num_get_sacl_priv_notheld++;
412 requestedInformation &= ~SACL_SECURITY_INFORMATION;
416 case ERROR_ACCESS_DENIED:
417 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS)
419 state->num_get_sd_access_denied++;
424 set_errno_from_win32_error(err);
425 ERROR("Failed to read security descriptor of \"%ls\"", path);
426 ret = WIMLIB_ERR_READ;
432 inode->i_security_id = sd_set_add_sd(sd_set, buf, lenNeeded);
433 if (inode->i_security_id < 0)
434 ret = WIMLIB_ERR_NOMEM;
444 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
446 size_t path_num_chars,
447 struct add_image_params *params,
448 struct win32_capture_state *state,
451 /* Reads the directory entries of directory and recursively calls
452 * win32_build_dentry_tree() on them. */
454 win32_recurse_directory(HANDLE hDir,
456 size_t dir_path_num_chars,
457 struct wim_dentry *root,
458 struct add_image_params *params,
459 struct win32_capture_state *state,
464 DEBUG("Recurse to directory \"%ls\"", dir_path);
466 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
467 * which we opened with FILE_FLAG_BACKUP_SEMANTICS (probably not the
468 * case for the FindFirstFile() API; it's not documented). */
471 IO_STATUS_BLOCK io_status;
472 const size_t bufsize = 8192;
474 BOOL restartScan = TRUE;
475 const FILE_NAMES_INFORMATION *info;
477 buf = MALLOC(bufsize);
479 return WIMLIB_ERR_NOMEM;
481 status = NtQueryDirectoryFile(hDir, NULL, NULL, NULL,
482 &io_status, buf, bufsize,
483 FileNamesInformation,
484 FALSE, NULL, restartScan);
486 if (status != STATUS_SUCCESS) {
487 if (status == STATUS_NO_MORE_FILES ||
488 status == STATUS_NO_MORE_ENTRIES ||
489 status == STATUS_NO_MORE_MATCHES) {
492 set_errno_from_nt_status(status);
493 ERROR_WITH_ERRNO("Failed to read directory "
494 "\"%ls\"", dir_path);
495 ret = WIMLIB_ERR_READ;
499 wimlib_assert(io_status.Information != 0);
500 info = (const FILE_NAMES_INFORMATION*)buf;
502 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
503 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
504 info->FileName[1] == L'.'))
507 struct wim_dentry *child;
509 p = dir_path + dir_path_num_chars;
511 p = wmempcpy(p, info->FileName,
512 info->FileNameLength / 2);
515 ret = win32_build_dentry_tree_recursive(
523 dir_path[dir_path_num_chars] = L'\0';
528 dentry_add_child(root, child);
530 if (info->NextEntryOffset == 0)
532 info = (const FILE_NAMES_INFORMATION*)
533 ((const u8*)info + info->NextEntryOffset);
540 WIN32_FIND_DATAW dat;
544 /* Begin reading the directory by calling FindFirstFileW. Unlike UNIX
545 * opendir(), FindFirstFileW has file globbing built into it. But this
546 * isn't what we actually want, so just add a dummy glob to get all
548 dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
549 dir_path[dir_path_num_chars + 1] = L'*';
550 dir_path[dir_path_num_chars + 2] = L'\0';
551 hFind = FindFirstFile(dir_path, &dat);
552 dir_path[dir_path_num_chars] = L'\0';
554 if (hFind == INVALID_HANDLE_VALUE) {
555 err = GetLastError();
556 if (err == ERROR_FILE_NOT_FOUND) {
559 set_errno_from_win32_error(err);
560 ERROR_WITH_ERRNO("Failed to read directory \"%ls\"",
562 return WIMLIB_ERR_READ;
567 /* Skip . and .. entries */
568 if (dat.cFileName[0] == L'.' &&
569 (dat.cFileName[1] == L'\0' ||
570 (dat.cFileName[1] == L'.' &&
571 dat.cFileName[2] == L'\0')))
573 size_t filename_len = wcslen(dat.cFileName);
575 dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
576 wmemcpy(dir_path + dir_path_num_chars + 1,
580 struct wim_dentry *child;
581 size_t path_len = dir_path_num_chars + 1 + filename_len;
582 ret = win32_build_dentry_tree_recursive(&child,
588 dir_path[dir_path_num_chars] = L'\0';
592 dentry_add_child(root, child);
593 } while (FindNextFile(hFind, &dat));
594 err = GetLastError();
595 if (err != ERROR_NO_MORE_FILES) {
596 set_errno_from_win32_error(err);
597 ERROR_WITH_ERRNO("Failed to read directory \"%ls\"", dir_path);
599 ret = WIMLIB_ERR_READ;
607 /* Reparse point fixup status code */
609 /* Reparse point corresponded to an absolute symbolic link or junction
610 * point that pointed outside the directory tree being captured, and
611 * therefore was excluded. */
614 /* Reparse point was not fixed as it was either a relative symbolic
615 * link, a mount point, or something else we could not understand. */
618 /* Reparse point corresponded to an absolute symbolic link or junction
619 * point that pointed inside the directory tree being captured, where
620 * the target was specified by a "full" \??\ prefixed path, and
621 * therefore was fixed to be relative to the root of the directory tree
623 RP_FIXED_FULLPATH = 0x2,
625 /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
626 * have the \??\ prefix. It may have begun with a drive letter though.
628 RP_FIXED_ABSPATH = 0x4,
630 /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
631 RP_FIXED = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
634 /* Given the "substitute name" target of a Windows reparse point, try doing a
635 * fixup where we change it to be absolute relative to the root of the directory
636 * tree being captured.
638 * Note that this is only executed when WIMLIB_ADD_FLAG_RPFIX has been
641 * @capture_root_ino and @capture_root_dev indicate the inode number and device
642 * of the root of the directory tree being captured. They are meant to identify
643 * this directory (as an alternative to its actual path, which could potentially
644 * be reached via multiple destinations due to other symbolic links). This may
645 * not work properly on FAT, which doesn't seem to supply proper inode numbers
646 * or file IDs. However, FAT doesn't support reparse points so this function
647 * wouldn't even be called anyway.
649 static enum rp_status
650 win32_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
651 u64 capture_root_ino, u64 capture_root_dev,
654 u16 target_nchars = *target_nbytes_p / 2;
655 size_t stripped_chars;
656 wchar_t *orig_target;
659 ret = parse_substitute_name(target, *target_nbytes_p, rptag);
662 stripped_chars = ret;
665 target[target_nchars] = L'\0';
666 orig_target = target;
667 target = capture_fixup_absolute_symlink(target + stripped_chars,
668 capture_root_ino, capture_root_dev);
671 target_nchars = wcslen(target);
672 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
673 *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
674 DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
676 return RP_FIXED_FULLPATH;
678 return RP_FIXED_ABSPATH;
681 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
684 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
685 u64 capture_root_ino, u64 capture_root_dev,
688 struct reparse_data rpdata;
690 enum rp_status rp_status;
692 ret = parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata);
696 rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
697 &rpdata.substitute_name_nbytes,
700 le32_to_cpu(*(le32*)rpbuf));
701 if (rp_status & RP_FIXED) {
702 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
703 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
704 wmemcpy(substitute_name_copy, rpdata.substitute_name,
705 rpdata.substitute_name_nbytes / 2);
706 rpdata.substitute_name = substitute_name_copy;
707 rpdata.print_name = substitute_name_copy;
708 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
709 if (rp_status == RP_FIXED_FULLPATH) {
710 /* "full path", meaning \??\ prefixed. We should not
711 * include this prefix in the print name, as it is
712 * apparently meant for the filesystem driver only. */
713 rpdata.print_name += 4;
714 rpdata.print_name_nbytes -= 8;
716 ret = make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
722 if (rp_status == RP_EXCLUDED) {
723 size_t print_name_nchars = rpdata.print_name_nbytes / 2;
724 wchar_t print_name0[print_name_nchars + 1];
725 print_name0[print_name_nchars] = L'\0';
726 wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
727 WARNING("Ignoring %ls pointing out of capture directory:\n"
728 " \"%ls\" -> \"%ls\"\n"
729 " (Use --norpfix to capture all symbolic links "
730 "and junction points as-is)",
731 (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK) ?
732 L"absolute symbolic link" : L"junction point",
741 * Loads the reparse point data from a reparse point into memory, optionally
742 * fixing the targets of absolute symbolic links and junction points to be
743 * relative to the root of capture.
745 * @hFile: Open handle to the reparse point.
746 * @path: Path to the reparse point. Used for error messages only.
747 * @params: Additional parameters, including whether to do reparse point fixups
749 * @rpbuf: Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
750 * the reparse point buffer will be loaded.
751 * @rpbuflen_ret: On success, the length of the reparse point buffer in bytes
752 * is written to this location.
755 * On success, returns an `enum rp_status' value that indicates if and/or
756 * how the reparse point fixup was done.
758 * On failure, returns a negative value that is a negated WIMLIB_ERR_*
762 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
763 struct add_image_params *params,
764 u8 *rpbuf, u16 *rpbuflen_ret)
771 DEBUG("Loading reparse data from \"%ls\"", path);
772 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
773 NULL, /* "Not used with this operation; set to NULL" */
774 0, /* "Not used with this operation; set to 0" */
775 rpbuf, /* "A pointer to a buffer that
776 receives the reparse point data */
777 REPARSE_POINT_MAX_SIZE, /* "The size of the output
782 set_errno_from_GetLastError();
783 ERROR_WITH_ERRNO("Failed to get reparse data of \"%ls\"", path);
784 return -WIMLIB_ERR_READ;
786 if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
787 ERROR("Reparse data on \"%ls\" is invalid", path);
788 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
791 rpbuflen = bytesReturned;
792 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
793 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
794 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
795 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
797 /* Try doing reparse point fixup */
798 ret = win32_capture_try_rpfix(rpbuf,
800 params->capture_root_ino,
801 params->capture_root_dev,
806 *rpbuflen_ret = rpbuflen;
811 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
814 *(u64*)_size_ret += len;
815 return ERROR_SUCCESS;
819 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
825 err = OpenEncryptedFileRaw(path, 0, &file_ctx);
826 if (err != ERROR_SUCCESS) {
827 set_errno_from_win32_error(err);
828 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
829 "for raw read", path);
830 return WIMLIB_ERR_OPEN;
833 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
835 if (err != ERROR_SUCCESS) {
836 set_errno_from_win32_error(err);
837 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
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_p,
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_p, &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 set_errno_from_nt_status(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 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1075 /* OpenEncryptedFileRaw() seems to fail with
1076 * ERROR_SHARING_VIOLATION if there are any handles opened to
1078 CloseHandle(*hFile_p);
1079 *hFile_p = INVALID_HANDLE_VALUE;
1082 /* Parse one or more stream information structures. */
1083 info = (const FILE_STREAM_INFORMATION*)buf;
1085 if (info->StreamNameLength <= sizeof(dat.cStreamName) - 2) {
1086 dat.StreamSize = info->StreamSize;
1087 memcpy(dat.cStreamName, info->StreamName, info->StreamNameLength);
1088 dat.cStreamName[info->StreamNameLength / 2] = L'\0';
1090 /* Capture the stream. */
1091 ret = win32_capture_stream(path, path_num_chars, inode,
1092 lookup_table, &dat);
1096 if (info->NextEntryOffset == 0) {
1097 /* No more stream information. */
1101 /* Advance to next stream information. */
1102 info = (const FILE_STREAM_INFORMATION*)
1103 ((const u8*)info + info->NextEntryOffset);
1106 /* Free buffer if allocated on heap. */
1111 #else /* WITH_NTDLL */
1112 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1113 if (hFind == INVALID_HANDLE_VALUE) {
1114 err = GetLastError();
1115 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1118 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1119 * points and directories */
1120 if ((inode->i_attributes &
1121 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1122 && err == ERROR_HANDLE_EOF)
1124 DEBUG("ERROR_HANDLE_EOF (ok)");
1127 if (err == ERROR_ACCESS_DENIED) {
1128 WARNING("Failed to look up data streams "
1129 "of \"%ls\": Access denied!\n%ls",
1130 path, capture_access_denied_msg);
1133 set_errno_from_win32_error(err);
1134 ERROR_WITH_ERRNO("Failed to look up data streams "
1135 "of \"%ls\"", path);
1136 return WIMLIB_ERR_READ;
1141 ret = win32_capture_stream(path,
1143 inode, lookup_table,
1146 goto out_find_close;
1147 } while (win32func_FindNextStreamW(hFind, &dat));
1148 err = GetLastError();
1149 if (err != ERROR_HANDLE_EOF) {
1150 set_errno_from_win32_error(err);
1151 ERROR_WITH_ERRNO("Error reading data streams from "
1153 ret = WIMLIB_ERR_READ;
1158 #endif /* !WITH_NTDLL */
1161 /* FindFirstStream() API is not available, or the volume does not
1162 * support named streams. Only capture the unnamed data stream. */
1163 DEBUG("Only capturing unnamed data stream");
1164 if (!(inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1165 FILE_ATTRIBUTE_REPARSE_POINT)))
1167 wcscpy(dat.cStreamName, L"::$DATA");
1168 dat.StreamSize.QuadPart = file_size;
1169 ret = win32_capture_stream(path,
1171 inode, lookup_table,
1180 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1182 size_t path_num_chars,
1183 struct add_image_params *params,
1184 struct win32_capture_state *state,
1187 struct wim_dentry *root = NULL;
1188 struct wim_inode *inode;
1196 DWORD desiredAccess;
1198 params->progress.scan.cur_path = path;
1200 if (exclude_path(path, path_num_chars, params->config, true)) {
1201 if (params->add_flags & WIMLIB_ADD_FLAG_ROOT) {
1202 ERROR("Cannot exclude the root directory from capture");
1203 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1206 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED);
1212 if (path_num_chars >= 4 &&
1213 !wmemcmp(path, L"\\\\?\\", 4) &&
1214 path_num_chars + 1 - 4 > MAX_PATH &&
1215 state->num_long_path_warnings < MAX_CAPTURE_LONG_PATH_WARNINGS)
1217 WARNING("Path \"%ls\" exceeds MAX_PATH", path);
1218 if (++state->num_long_path_warnings == MAX_CAPTURE_LONG_PATH_WARNINGS)
1219 WARNING("Suppressing further warnings about long paths.");
1223 do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK);
1225 desiredAccess = FILE_READ_DATA | FILE_READ_ATTRIBUTES |
1226 READ_CONTROL | ACCESS_SYSTEM_SECURITY;
1228 hFile = win32_open_existing_file(path, desiredAccess);
1229 if (hFile == INVALID_HANDLE_VALUE) {
1230 err = GetLastError();
1231 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD) {
1232 if (desiredAccess & ACCESS_SYSTEM_SECURITY) {
1233 desiredAccess &= ~ACCESS_SYSTEM_SECURITY;
1236 if (desiredAccess & READ_CONTROL) {
1237 desiredAccess &= ~READ_CONTROL;
1241 set_errno_from_GetLastError();
1242 ERROR_WITH_ERRNO("Failed to open \"%ls\" for reading", path);
1243 ret = WIMLIB_ERR_OPEN;
1247 BY_HANDLE_FILE_INFORMATION file_info;
1248 if (!GetFileInformationByHandle(hFile, &file_info)) {
1249 set_errno_from_GetLastError();
1250 ERROR_WITH_ERRNO("Failed to get file information for \"%ls\"",
1252 ret = WIMLIB_ERR_STAT;
1253 goto out_close_handle;
1256 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1257 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1258 ret = win32_get_reparse_data(hFile, path, params,
1261 /* WIMLIB_ERR_* (inverted) */
1263 goto out_close_handle;
1264 } else if (ret & RP_FIXED) {
1266 } else if (ret == RP_EXCLUDED) {
1268 goto out_close_handle;
1274 /* Create a WIM dentry with an associated inode, which may be shared.
1276 * However, we need to explicitly check for directories and files with
1277 * only 1 link and refuse to hard link them. This is because Windows
1278 * has a bug where it can return duplicate File IDs for files and
1279 * directories on the FAT filesystem. */
1280 ret = inode_table_new_dentry(¶ms->inode_table,
1281 path_basename_with_len(path, path_num_chars),
1282 ((u64)file_info.nFileIndexHigh << 32) |
1283 (u64)file_info.nFileIndexLow,
1284 file_info.dwVolumeSerialNumber,
1285 (file_info.nNumberOfLinks <= 1 ||
1286 (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1289 goto out_close_handle;
1291 ret = win32_get_short_name(hFile, path, root);
1293 goto out_close_handle;
1295 inode = root->d_inode;
1297 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1298 goto out_close_handle;
1300 inode->i_attributes = file_info.dwFileAttributes;
1301 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1302 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1303 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1304 inode->i_resolved = 1;
1306 params->add_flags &= ~WIMLIB_ADD_FLAG_ROOT;
1308 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1309 && (vol_flags & FILE_PERSISTENT_ACLS))
1311 ret = win32_get_security_descriptor(hFile, path, inode,
1312 ¶ms->sd_set, state,
1315 goto out_close_handle;
1318 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1319 (u64)file_info.nFileSizeLow;
1322 /* Capture the unnamed data stream (only should be present for regular
1323 * files) and any alternate data streams. */
1324 ret = win32_capture_streams(&hFile,
1328 params->lookup_table,
1332 goto out_close_handle;
1334 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1335 /* Reparse point: set the reparse data (which we read already)
1337 inode->i_not_rpfixed = not_rpfixed;
1338 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1339 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1340 params->lookup_table);
1341 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1342 /* Directory (not a reparse point) --- recurse to children */
1344 if (hFile == INVALID_HANDLE_VALUE) {
1345 /* Re-open handle that was closed to read raw encrypted
1347 hFile = win32_open_existing_file(path, FILE_READ_DATA);
1348 if (hFile == INVALID_HANDLE_VALUE) {
1349 set_errno_from_GetLastError();
1350 ERROR_WITH_ERRNO("Failed to reopen \"%ls\"",
1352 ret = WIMLIB_ERR_OPEN;
1353 goto out_close_handle;
1356 ret = win32_recurse_directory(hFile,
1370 free_dentry_tree(root, params->lookup_table);
1375 win32_do_capture_warnings(const wchar_t *path,
1376 const struct win32_capture_state *state,
1379 if (state->num_get_sacl_priv_notheld == 0 &&
1380 state->num_get_sd_access_denied == 0)
1383 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1384 if (state->num_get_sacl_priv_notheld != 0) {
1385 WARNING("- Could not capture SACL (System Access Control List)\n"
1386 " on %lu files or directories.",
1387 state->num_get_sacl_priv_notheld);
1389 if (state->num_get_sd_access_denied != 0) {
1390 WARNING("- Could not capture security descriptor at all\n"
1391 " on %lu files or directories.",
1392 state->num_get_sd_access_denied);
1394 WARNING("To fully capture all security descriptors, run the program\n"
1395 " with Administrator rights.");
1398 #define WINDOWS_NT_MAX_PATH 32768
1400 /* Win32 version of capturing a directory tree */
1402 win32_build_dentry_tree(struct wim_dentry **root_ret,
1403 const wchar_t *root_disk_path,
1404 struct add_image_params *params)
1409 struct win32_capture_state state;
1412 bool need_prefix_free = false;
1415 if (!win32func_FindFirstStreamW) {
1416 WARNING("Running on Windows XP or earlier; "
1417 "alternate data streams will not be captured.");
1421 path_nchars = wcslen(root_disk_path);
1422 if (path_nchars > WINDOWS_NT_MAX_PATH)
1423 return WIMLIB_ERR_INVALID_PARAM;
1425 ret = win32_get_file_and_vol_ids(root_disk_path,
1426 ¶ms->capture_root_ino,
1427 ¶ms->capture_root_dev);
1429 ERROR_WITH_ERRNO("Can't open %ls", root_disk_path);
1433 win32_get_vol_flags(root_disk_path, &vol_flags, NULL);
1435 /* WARNING: There is no check for overflow later when this buffer is
1436 * being used! But it's as long as the maximum path length understood
1437 * by Windows NT (which is NOT the same as MAX_PATH). */
1438 path = MALLOC(WINDOWS_NT_MAX_PATH * sizeof(wchar_t));
1440 return WIMLIB_ERR_NOMEM;
1442 /* Work around defective behavior in Windows where paths longer than 260
1443 * characters are not supported by default; instead they need to be
1444 * turned into absolute paths and prefixed with "\\?\". */
1446 if (wcsncmp(root_disk_path, L"\\\\?\\", 4)) {
1447 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 4,
1450 if (dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 4) {
1451 WARNING("Can't get full path name for \"%ls\"", root_disk_path);
1452 wmemcpy(path, root_disk_path, path_nchars + 1);
1454 wmemcpy(path, L"\\\\?\\", 4);
1455 path_nchars = 4 + dret;
1456 /* Update pattern prefix */
1457 if (params->config != NULL)
1459 params->config->_prefix = TSTRDUP(path);
1460 params->config->_prefix_num_tchars = path_nchars;
1461 if (params->config->_prefix == NULL)
1463 ret = WIMLIB_ERR_NOMEM;
1466 need_prefix_free = true;
1470 wmemcpy(path, root_disk_path, path_nchars + 1);
1473 memset(&state, 0, sizeof(state));
1474 ret = win32_build_dentry_tree_recursive(root_ret, path,
1475 path_nchars, params,
1477 if (need_prefix_free)
1478 FREE(params->config->_prefix);
1482 win32_do_capture_warnings(root_disk_path, &state, params->add_flags);
1486 #endif /* __WIN32__ */