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,
68 HANDLE hFile = win32_open_existing_file(lte->file_on_disk,
70 if (hFile == INVALID_HANDLE_VALUE) {
71 set_errno_from_GetLastError();
72 ERROR_WITH_ERRNO("Failed to open \"%ls\"", lte->file_on_disk);
73 return WIMLIB_ERR_OPEN;
77 out_buf = alloca(WIM_CHUNK_SIZE);
81 bytes_remaining = size;
82 while (bytes_remaining) {
83 DWORD bytesToRead, bytesRead;
85 bytesToRead = min(WIM_CHUNK_SIZE, bytes_remaining);
86 if (!ReadFile(hFile, out_buf, bytesToRead, &bytesRead, NULL) ||
87 bytesRead != bytesToRead)
89 set_errno_from_GetLastError();
90 ERROR_WITH_ERRNO("Failed to read data from \"%ls\"",
92 ret = WIMLIB_ERR_READ;
95 bytes_remaining -= bytesRead;
97 ret = (*cb)(out_buf, bytesRead, ctx_or_buf);
101 out_buf += bytesRead;
108 struct win32_encrypted_read_ctx {
109 consume_data_callback_t read_prefix_cb;
110 void *read_prefix_ctx_or_buf;
118 win32_encrypted_export_cb(unsigned char *_data, void *_ctx, unsigned long len)
120 const void *data = _data;
121 struct win32_encrypted_read_ctx *ctx = _ctx;
124 DEBUG("len = %lu", len);
125 if (ctx->read_prefix_cb) {
126 /* The length of the buffer passed to the ReadEncryptedFileRaw()
127 * export callback is undocumented, so we assume it may be of
129 size_t bytes_to_buffer = min(ctx->bytes_remaining - ctx->buf_filled,
131 while (bytes_to_buffer) {
132 size_t bytes_to_copy_to_buf =
133 min(bytes_to_buffer, WIM_CHUNK_SIZE - ctx->buf_filled);
135 memcpy(ctx->buf + ctx->buf_filled, data,
136 bytes_to_copy_to_buf);
137 ctx->buf_filled += bytes_to_copy_to_buf;
138 data += bytes_to_copy_to_buf;
139 bytes_to_buffer -= bytes_to_copy_to_buf;
141 if (ctx->buf_filled == WIM_CHUNK_SIZE ||
142 ctx->buf_filled == ctx->bytes_remaining)
144 ret = (*ctx->read_prefix_cb)(ctx->buf,
146 ctx->read_prefix_ctx_or_buf);
148 ctx->wimlib_err_code = ret;
149 /* Shouldn't matter what error code is returned
150 * here, as long as it isn't ERROR_SUCCESS. */
151 return ERROR_READ_FAULT;
153 ctx->bytes_remaining -= ctx->buf_filled;
158 size_t len_to_copy = min(len, ctx->bytes_remaining);
159 ctx->read_prefix_ctx_or_buf = mempcpy(ctx->read_prefix_ctx_or_buf,
162 ctx->bytes_remaining -= len_to_copy;
164 return ERROR_SUCCESS;
168 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
170 consume_data_callback_t cb,
174 struct win32_encrypted_read_ctx export_ctx;
179 DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
180 size, lte->file_on_disk);
182 export_ctx.read_prefix_cb = cb;
183 export_ctx.read_prefix_ctx_or_buf = ctx_or_buf;
184 export_ctx.wimlib_err_code = 0;
186 export_ctx.buf = MALLOC(WIM_CHUNK_SIZE);
188 return WIMLIB_ERR_NOMEM;
190 export_ctx.buf = NULL;
192 export_ctx.buf_filled = 0;
193 export_ctx.bytes_remaining = size;
195 err = OpenEncryptedFileRaw(lte->file_on_disk, 0, &file_ctx);
196 if (err != ERROR_SUCCESS) {
197 set_errno_from_win32_error(err);
198 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
199 "for raw read", lte->file_on_disk);
200 ret = WIMLIB_ERR_OPEN;
203 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
204 &export_ctx, file_ctx);
205 if (err != ERROR_SUCCESS) {
206 set_errno_from_win32_error(err);
207 ERROR_WITH_ERRNO("Failed to read encrypted file \"%ls\"",
209 ret = export_ctx.wimlib_err_code;
211 ret = WIMLIB_ERR_READ;
212 } else if (export_ctx.bytes_remaining != 0) {
213 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
214 "encryted file \"%ls\"",
215 size - export_ctx.bytes_remaining, size,
217 ret = WIMLIB_ERR_READ;
221 CloseEncryptedFileRaw(file_ctx);
223 FREE(export_ctx.buf);
229 FILETIME_to_u64(const FILETIME *ft)
231 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
234 /* Load the short name of a file into a WIM dentry.
236 * If we can't read the short filename for some reason, we just ignore the error
237 * and assume the file has no short name. This shouldn't be an issue, since the
238 * short names are essentially obsolete anyway.
241 win32_get_short_name(HANDLE hFile, const wchar_t *path, struct wim_dentry *dentry)
244 /* It's not any harder to just make the NtQueryInformationFile() system
245 * call ourselves, and it saves a dumb call to FindFirstFile() which of
246 * course has to create its own handle. */
248 if (func_NtQueryInformationFile) {
250 IO_STATUS_BLOCK io_status;
251 u8 buf[128] _aligned_attribute(8);
252 const FILE_NAME_INFORMATION *info;
254 status = (*func_NtQueryInformationFile)(hFile, &io_status, buf, sizeof(buf),
255 FileAlternateNameInformation);
256 info = (const FILE_NAME_INFORMATION*)buf;
257 if (status == STATUS_SUCCESS && info->FileNameLength != 0) {
258 dentry->short_name = MALLOC(info->FileNameLength + 2);
259 if (!dentry->short_name)
260 return WIMLIB_ERR_NOMEM;
261 memcpy(dentry->short_name, info->FileName,
262 info->FileNameLength);
263 dentry->short_name[info->FileNameLength / 2] = L'\0';
264 dentry->short_name_nbytes = info->FileNameLength;
270 WIN32_FIND_DATAW dat;
274 hFind = FindFirstFile(path, &dat);
275 if (hFind != INVALID_HANDLE_VALUE) {
276 if (dat.cAlternateFileName[0] != L'\0') {
277 DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
278 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
280 size_t n = short_name_nbytes + sizeof(wchar_t);
281 dentry->short_name = MALLOC(n);
282 if (dentry->short_name) {
283 memcpy(dentry->short_name, dat.cAlternateFileName, n);
284 dentry->short_name_nbytes = short_name_nbytes;
286 ret = WIMLIB_ERR_NOMEM;
295 * win32_query_security_descriptor() - Query a file's security descriptor
297 * We need the file's security descriptor in SECURITY_DESCRIPTOR_RELATIVE
298 * format, and we currently have a handle opened with as many relevant
299 * permissions as possible. At this point, on Windows there are a number of
300 * options for reading a file's security descriptor:
302 * GetFileSecurity(): This takes in a path and returns the
303 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle, not
304 * ours, and the handle created internally doesn't specify
305 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied errors on
306 * some files and directories, even when running as the Administrator.
308 * GetSecurityInfo(): This takes in a handle and returns the security
309 * descriptor split into a bunch of different parts. This should work, but it's
310 * dumb because we have to put the security descriptor back together again.
312 * BackupRead(): This can read the security descriptor, but this is a
313 * difficult-to-use API, probably only works as the Administrator, and the
314 * format of the returned data is not well documented.
316 * NtQuerySecurityObject(): This is exactly what we need, as it takes in a
317 * handle and returns the security descriptor in SECURITY_DESCRIPTOR_RELATIVE
318 * format. Only problem is that it's a ntdll function and therefore not
319 * officially part of the Win32 API. Oh well.
322 win32_query_security_descriptor(HANDLE hFile, const wchar_t *path,
323 SECURITY_INFORMATION requestedInformation,
324 SECURITY_DESCRIPTOR *buf,
325 DWORD bufsize, DWORD *lengthNeeded)
328 if (func_NtQuerySecurityObject) {
331 status = (*func_NtQuerySecurityObject)(hFile,
332 requestedInformation, buf,
333 bufsize, lengthNeeded);
334 /* Since it queries an already-open handle, NtQuerySecurityObject()
335 * apparently returns STATUS_ACCESS_DENIED rather than
336 * STATUS_PRIVILEGE_NOT_HELD. */
337 if (status == STATUS_ACCESS_DENIED)
338 return ERROR_PRIVILEGE_NOT_HELD;
340 return (*func_RtlNtStatusToDosError)(status);
343 if (GetFileSecurity(path, requestedInformation, buf,
344 bufsize, lengthNeeded))
345 return ERROR_SUCCESS;
347 return GetLastError();
351 win32_get_security_descriptor(HANDLE hFile,
353 struct wim_inode *inode,
354 struct wim_sd_set *sd_set,
355 struct win32_capture_state *state,
358 SECURITY_INFORMATION requestedInformation;
366 requestedInformation = DACL_SECURITY_INFORMATION |
367 SACL_SECURITY_INFORMATION |
368 OWNER_SECURITY_INFORMATION |
369 GROUP_SECURITY_INFORMATION;
371 bufsize = sizeof(_buf);
373 err = win32_query_security_descriptor(hFile, path,
374 requestedInformation,
375 (SECURITY_DESCRIPTOR*)buf,
376 bufsize, &lenNeeded);
379 goto have_descriptor;
380 case ERROR_INSUFFICIENT_BUFFER:
381 wimlib_assert(buf == _buf);
382 buf = MALLOC(lenNeeded);
384 return WIMLIB_ERR_NOMEM;
387 case ERROR_PRIVILEGE_NOT_HELD:
388 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS)
390 if (requestedInformation & SACL_SECURITY_INFORMATION) {
391 state->num_get_sacl_priv_notheld++;
392 requestedInformation &= ~SACL_SECURITY_INFORMATION;
396 case ERROR_ACCESS_DENIED:
397 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS)
399 state->num_get_sd_access_denied++;
404 set_errno_from_win32_error(err);
405 ERROR("Failed to read security descriptor of \"%ls\"", path);
406 ret = WIMLIB_ERR_READ;
412 inode->i_security_id = sd_set_add_sd(sd_set, buf, lenNeeded);
413 if (inode->i_security_id < 0)
414 ret = WIMLIB_ERR_NOMEM;
424 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
426 size_t path_num_chars,
427 struct add_image_params *params,
428 struct win32_capture_state *state,
431 /* Reads the directory entries of directory and recursively calls
432 * win32_build_dentry_tree() on them. */
434 win32_recurse_directory(HANDLE hDir,
436 size_t dir_path_num_chars,
437 struct wim_dentry *root,
438 struct add_image_params *params,
439 struct win32_capture_state *state,
444 DEBUG("Recurse to directory \"%ls\"", dir_path);
446 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
447 * which we opened with FILE_FLAG_BACKUP_SEMANTICS (probably not the
448 * case for the FindFirstFile() API; it's not documented). */
450 if (!func_NtQueryDirectoryFile)
451 goto use_FindFirstFile;
454 IO_STATUS_BLOCK io_status;
455 const size_t bufsize = 8192;
457 BOOL restartScan = TRUE;
458 const FILE_NAMES_INFORMATION *info;
460 buf = MALLOC(bufsize);
462 return WIMLIB_ERR_NOMEM;
464 status = (*func_NtQueryDirectoryFile)(hDir, NULL, NULL, NULL,
465 &io_status, buf, bufsize,
466 FileNamesInformation,
467 FALSE, NULL, restartScan);
469 if (status != STATUS_SUCCESS) {
470 if (status == STATUS_NO_MORE_FILES ||
471 status == STATUS_NO_MORE_ENTRIES ||
472 status == STATUS_NO_MORE_MATCHES) {
474 } else if (status == STATUS_NOT_IMPLEMENTED ||
475 status == STATUS_NOT_SUPPORTED ||
476 status == STATUS_INVALID_INFO_CLASS) {
478 goto use_FindFirstFile;
480 set_errno_from_nt_status(status);
481 ERROR_WITH_ERRNO("Failed to read directory "
482 "\"%ls\"", dir_path);
483 ret = WIMLIB_ERR_READ;
487 wimlib_assert(io_status.Information != 0);
488 info = (const FILE_NAMES_INFORMATION*)buf;
490 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
491 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
492 info->FileName[1] == L'.'))
495 struct wim_dentry *child;
497 p = dir_path + dir_path_num_chars;
499 p = wmempcpy(p, info->FileName,
500 info->FileNameLength / 2);
503 ret = win32_build_dentry_tree_recursive(
511 dir_path[dir_path_num_chars] = L'\0';
516 dentry_add_child(root, child);
518 if (info->NextEntryOffset == 0)
520 info = (const FILE_NAMES_INFORMATION*)
521 ((const u8*)info + info->NextEntryOffset);
531 WIN32_FIND_DATAW dat;
535 /* Begin reading the directory by calling FindFirstFileW. Unlike UNIX
536 * opendir(), FindFirstFileW has file globbing built into it. But this
537 * isn't what we actually want, so just add a dummy glob to get all
539 dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
540 dir_path[dir_path_num_chars + 1] = L'*';
541 dir_path[dir_path_num_chars + 2] = L'\0';
542 hFind = FindFirstFile(dir_path, &dat);
543 dir_path[dir_path_num_chars] = L'\0';
545 if (hFind == INVALID_HANDLE_VALUE) {
546 err = GetLastError();
547 if (err == ERROR_FILE_NOT_FOUND) {
550 set_errno_from_win32_error(err);
551 ERROR_WITH_ERRNO("Failed to read directory \"%ls\"",
553 return WIMLIB_ERR_READ;
558 /* Skip . and .. entries */
559 if (dat.cFileName[0] == L'.' &&
560 (dat.cFileName[1] == L'\0' ||
561 (dat.cFileName[1] == L'.' &&
562 dat.cFileName[2] == L'\0')))
564 size_t filename_len = wcslen(dat.cFileName);
566 dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
567 wmemcpy(dir_path + dir_path_num_chars + 1,
571 struct wim_dentry *child;
572 size_t path_len = dir_path_num_chars + 1 + filename_len;
573 ret = win32_build_dentry_tree_recursive(&child,
579 dir_path[dir_path_num_chars] = L'\0';
583 dentry_add_child(root, child);
584 } while (FindNextFile(hFind, &dat));
585 err = GetLastError();
586 if (err != ERROR_NO_MORE_FILES) {
587 set_errno_from_win32_error(err);
588 ERROR_WITH_ERRNO("Failed to read directory \"%ls\"", dir_path);
590 ret = WIMLIB_ERR_READ;
597 /* Reparse point fixup status code */
599 /* Reparse point corresponded to an absolute symbolic link or junction
600 * point that pointed outside the directory tree being captured, and
601 * therefore was excluded. */
604 /* Reparse point was not fixed as it was either a relative symbolic
605 * link, a mount point, or something else we could not understand. */
608 /* Reparse point corresponded to an absolute symbolic link or junction
609 * point that pointed inside the directory tree being captured, where
610 * the target was specified by a "full" \??\ prefixed path, and
611 * therefore was fixed to be relative to the root of the directory tree
613 RP_FIXED_FULLPATH = 0x2,
615 /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
616 * have the \??\ prefix. It may have begun with a drive letter though.
618 RP_FIXED_ABSPATH = 0x4,
620 /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
621 RP_FIXED = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
624 /* Given the "substitute name" target of a Windows reparse point, try doing a
625 * fixup where we change it to be absolute relative to the root of the directory
626 * tree being captured.
628 * Note that this is only executed when WIMLIB_ADD_FLAG_RPFIX has been
631 * @capture_root_ino and @capture_root_dev indicate the inode number and device
632 * of the root of the directory tree being captured. They are meant to identify
633 * this directory (as an alternative to its actual path, which could potentially
634 * be reached via multiple destinations due to other symbolic links). This may
635 * not work properly on FAT, which doesn't seem to supply proper inode numbers
636 * or file IDs. However, FAT doesn't support reparse points so this function
637 * wouldn't even be called anyway.
639 static enum rp_status
640 win32_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
641 u64 capture_root_ino, u64 capture_root_dev,
644 u16 target_nchars = *target_nbytes_p / 2;
645 size_t stripped_chars;
646 wchar_t *orig_target;
649 ret = parse_substitute_name(target, *target_nbytes_p, rptag);
652 stripped_chars = ret;
655 target[target_nchars] = L'\0';
656 orig_target = target;
657 target = capture_fixup_absolute_symlink(target + stripped_chars,
658 capture_root_ino, capture_root_dev);
661 target_nchars = wcslen(target);
662 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
663 *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
664 DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
666 return RP_FIXED_FULLPATH;
668 return RP_FIXED_ABSPATH;
671 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
674 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
675 u64 capture_root_ino, u64 capture_root_dev,
678 struct reparse_data rpdata;
680 enum rp_status rp_status;
682 ret = parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata);
686 rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
687 &rpdata.substitute_name_nbytes,
690 le32_to_cpu(*(le32*)rpbuf));
691 if (rp_status & RP_FIXED) {
692 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
693 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
694 wmemcpy(substitute_name_copy, rpdata.substitute_name,
695 rpdata.substitute_name_nbytes / 2);
696 rpdata.substitute_name = substitute_name_copy;
697 rpdata.print_name = substitute_name_copy;
698 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
699 if (rp_status == RP_FIXED_FULLPATH) {
700 /* "full path", meaning \??\ prefixed. We should not
701 * include this prefix in the print name, as it is
702 * apparently meant for the filesystem driver only. */
703 rpdata.print_name += 4;
704 rpdata.print_name_nbytes -= 8;
706 ret = make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
712 if (rp_status == RP_EXCLUDED) {
713 size_t print_name_nchars = rpdata.print_name_nbytes / 2;
714 wchar_t print_name0[print_name_nchars + 1];
715 print_name0[print_name_nchars] = L'\0';
716 wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
717 WARNING("Ignoring %ls pointing out of capture directory:\n"
718 " \"%ls\" -> \"%ls\"\n"
719 " (Use --norpfix to capture all symbolic links "
720 "and junction points as-is)",
721 (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK) ?
722 L"absolute symbolic link" : L"junction point",
731 * Loads the reparse point data from a reparse point into memory, optionally
732 * fixing the targets of absolute symbolic links and junction points to be
733 * relative to the root of capture.
735 * @hFile: Open handle to the reparse point.
736 * @path: Path to the reparse point. Used for error messages only.
737 * @params: Additional parameters, including whether to do reparse point fixups
739 * @rpbuf: Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
740 * the reparse point buffer will be loaded.
741 * @rpbuflen_ret: On success, the length of the reparse point buffer in bytes
742 * is written to this location.
745 * On success, returns an `enum rp_status' value that indicates if and/or
746 * how the reparse point fixup was done.
748 * On failure, returns a negative value that is a negated WIMLIB_ERR_*
752 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
753 struct add_image_params *params,
754 u8 *rpbuf, u16 *rpbuflen_ret)
761 DEBUG("Loading reparse data from \"%ls\"", path);
762 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
763 NULL, /* "Not used with this operation; set to NULL" */
764 0, /* "Not used with this operation; set to 0" */
765 rpbuf, /* "A pointer to a buffer that
766 receives the reparse point data */
767 REPARSE_POINT_MAX_SIZE, /* "The size of the output
772 set_errno_from_GetLastError();
773 ERROR_WITH_ERRNO("Failed to get reparse data of \"%ls\"", path);
774 return -WIMLIB_ERR_READ;
776 if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
777 ERROR("Reparse data on \"%ls\" is invalid", path);
778 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
781 rpbuflen = bytesReturned;
782 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
783 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
784 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
785 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
787 /* Try doing reparse point fixup */
788 ret = win32_capture_try_rpfix(rpbuf,
790 params->capture_root_ino,
791 params->capture_root_dev,
796 *rpbuflen_ret = rpbuflen;
801 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
804 *(u64*)_size_ret += len;
805 return ERROR_SUCCESS;
809 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
815 err = OpenEncryptedFileRaw(path, 0, &file_ctx);
816 if (err != ERROR_SUCCESS) {
817 set_errno_from_win32_error(err);
818 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
819 "for raw read", path);
820 return WIMLIB_ERR_OPEN;
823 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
825 if (err != ERROR_SUCCESS) {
826 set_errno_from_win32_error(err);
827 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
829 ret = WIMLIB_ERR_READ;
833 CloseEncryptedFileRaw(file_ctx);
837 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
838 * stream); calculates its SHA1 message digest and either creates a `struct
839 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
840 * wim_lookup_table_entry' for an identical stream.
842 * @path: Path to the file (UTF-16LE).
844 * @path_num_chars: Number of 2-byte characters in @path.
846 * @inode: WIM inode to save the stream into.
848 * @lookup_table: Stream lookup table for the WIM.
850 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
853 * Returns 0 on success; nonzero on failure.
856 win32_capture_stream(const wchar_t *path,
857 size_t path_num_chars,
858 struct wim_inode *inode,
859 struct wim_lookup_table *lookup_table,
860 WIN32_FIND_STREAM_DATA *dat)
862 struct wim_ads_entry *ads_entry;
863 struct wim_lookup_table_entry *lte;
865 wchar_t *stream_name, *colon;
866 size_t stream_name_nchars;
867 bool is_named_stream;
870 size_t spath_buf_nbytes;
871 const wchar_t *relpath_prefix;
872 const wchar_t *colonchar;
874 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
876 /* The stream name should be returned as :NAME:TYPE */
877 stream_name = dat->cStreamName;
878 if (*stream_name != L':')
879 goto out_invalid_stream_name;
881 colon = wcschr(stream_name, L':');
883 goto out_invalid_stream_name;
885 if (wcscmp(colon + 1, L"$DATA")) {
886 /* Not a DATA stream */
893 stream_name_nchars = colon - stream_name;
894 is_named_stream = (stream_name_nchars != 0);
896 if (is_named_stream) {
897 /* Allocate an ADS entry for the named stream. */
898 ads_entry = inode_add_ads_utf16le(inode, stream_name,
899 stream_name_nchars * sizeof(wchar_t));
901 ret = WIMLIB_ERR_NOMEM;
906 /* If zero length stream, no lookup table entry needed. */
907 if ((u64)dat->StreamSize.QuadPart == 0) {
912 /* Create a UTF-16LE string @spath that gives the filename, then a
913 * colon, then the stream name. Or, if it's an unnamed stream, just the
914 * filename. It is MALLOC()'ed so that it can be saved in the
915 * wim_lookup_table_entry if needed.
917 * As yet another special case, relative paths need to be changed to
918 * begin with an explicit "./" so that, for example, a file t:ads, where
919 * :ads is the part we added, is not interpreted as a file on the t:
921 spath_nchars = path_num_chars;
922 relpath_prefix = L"";
924 if (is_named_stream) {
925 spath_nchars += 1 + stream_name_nchars;
927 if (path_num_chars == 1 && !is_any_path_separator(path[0])) {
929 static const wchar_t _relpath_prefix[] =
930 {L'.', OS_PREFERRED_PATH_SEPARATOR, L'\0'};
931 relpath_prefix = _relpath_prefix;
935 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
936 spath = MALLOC(spath_buf_nbytes);
938 tsprintf(spath, L"%ls%ls%ls%ls",
939 relpath_prefix, path, colonchar, stream_name);
941 /* Make a new wim_lookup_table_entry */
942 lte = new_lookup_table_entry();
944 ret = WIMLIB_ERR_NOMEM;
947 lte->file_on_disk = spath;
949 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
951 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
952 ret = win32_get_encrypted_file_size(path, &encrypted_size);
955 lte->resource_entry.original_size = encrypted_size;
957 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
958 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
962 if (is_named_stream) {
963 stream_id = ads_entry->stream_id;
964 ads_entry->lte = lte;
969 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
975 out_invalid_stream_name:
976 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
977 ret = WIMLIB_ERR_READ;
981 /* Load information about the streams of an open file into a WIM inode.
983 * By default, we use the NtQueryInformationFile() system call instead of
984 * FindFirstStream() and FindNextStream(). This is done for two reasons:
986 * - FindFirstStream() opens its own handle to the file or directory and
987 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
988 * causing access denied errors on certain files (even when running as the
990 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
991 * and later, whereas the stream support in NtQueryInformationFile() was
992 * already present in Windows XP.
995 win32_capture_streams(HANDLE *hFile_p,
997 size_t path_num_chars,
998 struct wim_inode *inode,
999 struct wim_lookup_table *lookup_table,
1003 WIN32_FIND_STREAM_DATA dat;
1006 u8 _buf[8192] _aligned_attribute(8);
1009 IO_STATUS_BLOCK io_status;
1011 const FILE_STREAM_INFORMATION *info;
1016 DEBUG("Capturing streams from \"%ls\"", path);
1018 if (!(vol_flags & FILE_NAMED_STREAMS))
1022 if (!func_NtQueryInformationFile)
1023 goto use_FindFirstStream;
1026 bufsize = sizeof(_buf);
1028 /* Get a buffer containing the stream information. */
1030 status = (*func_NtQueryInformationFile)(*hFile_p, &io_status,
1032 FileStreamInformation);
1033 if (status == STATUS_SUCCESS) {
1035 } else if (status == STATUS_BUFFER_OVERFLOW) {
1040 newbuf = MALLOC(bufsize);
1042 newbuf = REALLOC(buf, bufsize);
1045 ret = WIMLIB_ERR_NOMEM;
1049 } else if (status == STATUS_NOT_IMPLEMENTED ||
1050 status == STATUS_NOT_SUPPORTED ||
1051 status == STATUS_INVALID_INFO_CLASS) {
1052 goto use_FindFirstStream;
1054 set_errno_from_nt_status(status);
1055 ERROR_WITH_ERRNO("Failed to read streams of %ls", path);
1056 ret = WIMLIB_ERR_READ;
1061 if (io_status.Information == 0) {
1062 /* No stream information. */
1067 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1068 /* OpenEncryptedFileRaw() seems to fail with
1069 * ERROR_SHARING_VIOLATION if there are any handles opened to
1071 CloseHandle(*hFile_p);
1072 *hFile_p = INVALID_HANDLE_VALUE;
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. */
1103 #endif /* WITH_NTDLL */
1105 use_FindFirstStream:
1106 if (win32func_FindFirstStreamW == NULL)
1108 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1109 if (hFind == INVALID_HANDLE_VALUE) {
1110 err = GetLastError();
1111 if (err == ERROR_CALL_NOT_IMPLEMENTED ||
1112 err == ERROR_NOT_SUPPORTED ||
1113 err == ERROR_INVALID_FUNCTION ||
1114 err == ERROR_INVALID_PARAMETER)
1117 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1118 * points and directories */
1119 if ((inode->i_attributes &
1120 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1121 && err == ERROR_HANDLE_EOF)
1123 DEBUG("ERROR_HANDLE_EOF (ok)");
1126 if (err == ERROR_ACCESS_DENIED) {
1127 WARNING("Failed to look up data streams "
1128 "of \"%ls\": Access denied!\n%ls",
1129 path, capture_access_denied_msg);
1132 set_errno_from_win32_error(err);
1133 ERROR_WITH_ERRNO("Failed to look up data streams "
1134 "of \"%ls\"", path);
1135 return WIMLIB_ERR_READ;
1140 ret = win32_capture_stream(path,
1142 inode, lookup_table,
1145 goto out_find_close;
1146 } while (win32func_FindNextStreamW(hFind, &dat));
1147 err = GetLastError();
1148 if (err != ERROR_HANDLE_EOF) {
1149 set_errno_from_win32_error(err);
1150 ERROR_WITH_ERRNO("Error reading data streams from "
1152 ret = WIMLIB_ERR_READ;
1159 /* FindFirstStream() API is not available, or the volume does not
1160 * support named streams. Only capture the unnamed data stream. */
1161 DEBUG("Only capturing unnamed data stream");
1162 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1163 FILE_ATTRIBUTE_REPARSE_POINT))
1166 wcscpy(dat.cStreamName, L"::$DATA");
1167 dat.StreamSize.QuadPart = file_size;
1168 return win32_capture_stream(path, path_num_chars,
1169 inode, lookup_table, &dat);
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 */
1337 if (hFile == INVALID_HANDLE_VALUE) {
1338 /* Re-open handle that was closed to read raw encrypted
1340 hFile = win32_open_existing_file(path, FILE_READ_DATA);
1341 if (hFile == INVALID_HANDLE_VALUE) {
1342 set_errno_from_GetLastError();
1343 ERROR_WITH_ERRNO("Failed to reopen \"%ls\"",
1345 ret = WIMLIB_ERR_OPEN;
1346 goto out_close_handle;
1349 ret = win32_recurse_directory(hFile,
1363 free_dentry_tree(root, params->lookup_table);
1368 win32_do_capture_warnings(const wchar_t *path,
1369 const struct win32_capture_state *state,
1372 if (state->num_get_sacl_priv_notheld == 0 &&
1373 state->num_get_sd_access_denied == 0)
1376 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1377 if (state->num_get_sacl_priv_notheld != 0) {
1378 WARNING("- Could not capture SACL (System Access Control List)\n"
1379 " on %lu files or directories.",
1380 state->num_get_sacl_priv_notheld);
1382 if (state->num_get_sd_access_denied != 0) {
1383 WARNING("- Could not capture security descriptor at all\n"
1384 " on %lu files or directories.",
1385 state->num_get_sd_access_denied);
1387 WARNING("To fully capture all security descriptors, run the program\n"
1388 " with Administrator rights.");
1391 #define WINDOWS_NT_MAX_PATH 32768
1393 /* Win32 version of capturing a directory tree */
1395 win32_build_dentry_tree(struct wim_dentry **root_ret,
1396 const wchar_t *root_disk_path,
1397 struct add_image_params *params)
1402 struct win32_capture_state state;
1405 bool need_prefix_free = false;
1407 if (!win32func_FindFirstStreamW
1409 && !func_NtQueryInformationFile
1413 WARNING("Running on Windows XP or earlier; "
1414 "alternate data streams will not be captured.");
1417 path_nchars = wcslen(root_disk_path);
1418 if (path_nchars > WINDOWS_NT_MAX_PATH)
1419 return WIMLIB_ERR_INVALID_PARAM;
1421 ret = win32_get_file_and_vol_ids(root_disk_path,
1422 ¶ms->capture_root_ino,
1423 ¶ms->capture_root_dev);
1425 ERROR_WITH_ERRNO("Can't open %ls", root_disk_path);
1429 win32_get_vol_flags(root_disk_path, &vol_flags, NULL);
1431 /* WARNING: There is no check for overflow later when this buffer is
1432 * being used! But it's as long as the maximum path length understood
1433 * by Windows NT (which is NOT the same as MAX_PATH). */
1434 path = MALLOC(WINDOWS_NT_MAX_PATH * sizeof(wchar_t));
1436 return WIMLIB_ERR_NOMEM;
1438 /* Work around defective behavior in Windows where paths longer than 260
1439 * characters are not supported by default; instead they need to be
1440 * turned into absolute paths and prefixed with "\\?\". */
1442 if (wcsncmp(root_disk_path, L"\\\\?\\", 4)) {
1443 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 4,
1446 if (dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 4) {
1447 WARNING("Can't get full path name for \"%ls\"", root_disk_path);
1448 wmemcpy(path, root_disk_path, path_nchars + 1);
1450 wmemcpy(path, L"\\\\?\\", 4);
1451 path_nchars = 4 + dret;
1452 /* Update pattern prefix */
1453 if (params->config != NULL)
1455 params->config->_prefix = TSTRDUP(path);
1456 params->config->_prefix_num_tchars = path_nchars;
1457 if (params->config->_prefix == NULL)
1459 ret = WIMLIB_ERR_NOMEM;
1462 need_prefix_free = true;
1466 wmemcpy(path, root_disk_path, path_nchars + 1);
1469 memset(&state, 0, sizeof(state));
1470 ret = win32_build_dentry_tree_recursive(root_ret, path,
1471 path_nchars, params,
1473 if (need_prefix_free)
1474 FREE(params->config->_prefix);
1478 win32_do_capture_warnings(root_disk_path, &state, params->add_flags);
1482 #endif /* __WIN32__ */