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) {
452 IO_STATUS_BLOCK io_status;
453 const size_t bufsize = 8192;
455 BOOL restartScan = TRUE;
456 const FILE_NAMES_INFORMATION *info;
458 buf = MALLOC(bufsize);
460 return WIMLIB_ERR_NOMEM;
462 status = (*func_NtQueryDirectoryFile)(hDir, NULL, NULL, NULL,
463 &io_status, buf, bufsize,
464 FileNamesInformation,
465 FALSE, NULL, restartScan);
467 if (status != STATUS_SUCCESS) {
468 if (status == STATUS_NO_MORE_FILES ||
469 status == STATUS_NO_MORE_ENTRIES ||
470 status == STATUS_NO_MORE_MATCHES) {
473 set_errno_from_nt_status(status);
474 ERROR_WITH_ERRNO("Failed to read directory "
475 "\"%ls\"", dir_path);
476 ret = WIMLIB_ERR_READ;
480 wimlib_assert(io_status.Information != 0);
481 info = (const FILE_NAMES_INFORMATION*)buf;
483 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
484 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
485 info->FileName[1] == L'.'))
488 struct wim_dentry *child;
490 p = dir_path + dir_path_num_chars;
492 p = wmempcpy(p, info->FileName,
493 info->FileNameLength / 2);
496 ret = win32_build_dentry_tree_recursive(
504 dir_path[dir_path_num_chars] = L'\0';
509 dentry_add_child(root, child);
511 if (info->NextEntryOffset == 0)
513 info = (const FILE_NAMES_INFORMATION*)
514 ((const u8*)info + info->NextEntryOffset);
522 WIN32_FIND_DATAW dat;
526 /* Begin reading the directory by calling FindFirstFileW. Unlike UNIX
527 * opendir(), FindFirstFileW has file globbing built into it. But this
528 * isn't what we actually want, so just add a dummy glob to get all
530 dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
531 dir_path[dir_path_num_chars + 1] = L'*';
532 dir_path[dir_path_num_chars + 2] = L'\0';
533 hFind = FindFirstFile(dir_path, &dat);
534 dir_path[dir_path_num_chars] = L'\0';
536 if (hFind == INVALID_HANDLE_VALUE) {
537 err = GetLastError();
538 if (err == ERROR_FILE_NOT_FOUND) {
541 set_errno_from_win32_error(err);
542 ERROR_WITH_ERRNO("Failed to read directory \"%ls\"",
544 return WIMLIB_ERR_READ;
549 /* Skip . and .. entries */
550 if (dat.cFileName[0] == L'.' &&
551 (dat.cFileName[1] == L'\0' ||
552 (dat.cFileName[1] == L'.' &&
553 dat.cFileName[2] == L'\0')))
555 size_t filename_len = wcslen(dat.cFileName);
557 dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
558 wmemcpy(dir_path + dir_path_num_chars + 1,
562 struct wim_dentry *child;
563 size_t path_len = dir_path_num_chars + 1 + filename_len;
564 ret = win32_build_dentry_tree_recursive(&child,
570 dir_path[dir_path_num_chars] = L'\0';
574 dentry_add_child(root, child);
575 } while (FindNextFile(hFind, &dat));
576 err = GetLastError();
577 if (err != ERROR_NO_MORE_FILES) {
578 set_errno_from_win32_error(err);
579 ERROR_WITH_ERRNO("Failed to read directory \"%ls\"", dir_path);
581 ret = WIMLIB_ERR_READ;
588 /* Reparse point fixup status code */
590 /* Reparse point corresponded to an absolute symbolic link or junction
591 * point that pointed outside the directory tree being captured, and
592 * therefore was excluded. */
595 /* Reparse point was not fixed as it was either a relative symbolic
596 * link, a mount point, or something else we could not understand. */
599 /* Reparse point corresponded to an absolute symbolic link or junction
600 * point that pointed inside the directory tree being captured, where
601 * the target was specified by a "full" \??\ prefixed path, and
602 * therefore was fixed to be relative to the root of the directory tree
604 RP_FIXED_FULLPATH = 0x2,
606 /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
607 * have the \??\ prefix. It may have begun with a drive letter though.
609 RP_FIXED_ABSPATH = 0x4,
611 /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
612 RP_FIXED = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
615 /* Given the "substitute name" target of a Windows reparse point, try doing a
616 * fixup where we change it to be absolute relative to the root of the directory
617 * tree being captured.
619 * Note that this is only executed when WIMLIB_ADD_FLAG_RPFIX has been
622 * @capture_root_ino and @capture_root_dev indicate the inode number and device
623 * of the root of the directory tree being captured. They are meant to identify
624 * this directory (as an alternative to its actual path, which could potentially
625 * be reached via multiple destinations due to other symbolic links). This may
626 * not work properly on FAT, which doesn't seem to supply proper inode numbers
627 * or file IDs. However, FAT doesn't support reparse points so this function
628 * wouldn't even be called anyway.
630 static enum rp_status
631 win32_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
632 u64 capture_root_ino, u64 capture_root_dev,
635 u16 target_nchars = *target_nbytes_p / 2;
636 size_t stripped_chars;
637 wchar_t *orig_target;
640 ret = parse_substitute_name(target, *target_nbytes_p, rptag);
643 stripped_chars = ret;
646 target[target_nchars] = L'\0';
647 orig_target = target;
648 target = capture_fixup_absolute_symlink(target + stripped_chars,
649 capture_root_ino, capture_root_dev);
652 target_nchars = wcslen(target);
653 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
654 *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
655 DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
657 return RP_FIXED_FULLPATH;
659 return RP_FIXED_ABSPATH;
662 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
665 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
666 u64 capture_root_ino, u64 capture_root_dev,
669 struct reparse_data rpdata;
671 enum rp_status rp_status;
673 ret = parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata);
677 rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
678 &rpdata.substitute_name_nbytes,
681 le32_to_cpu(*(le32*)rpbuf));
682 if (rp_status & RP_FIXED) {
683 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
684 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
685 wmemcpy(substitute_name_copy, rpdata.substitute_name,
686 rpdata.substitute_name_nbytes / 2);
687 rpdata.substitute_name = substitute_name_copy;
688 rpdata.print_name = substitute_name_copy;
689 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
690 if (rp_status == RP_FIXED_FULLPATH) {
691 /* "full path", meaning \??\ prefixed. We should not
692 * include this prefix in the print name, as it is
693 * apparently meant for the filesystem driver only. */
694 rpdata.print_name += 4;
695 rpdata.print_name_nbytes -= 8;
697 ret = make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
703 if (rp_status == RP_EXCLUDED) {
704 size_t print_name_nchars = rpdata.print_name_nbytes / 2;
705 wchar_t print_name0[print_name_nchars + 1];
706 print_name0[print_name_nchars] = L'\0';
707 wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
708 WARNING("Ignoring %ls pointing out of capture directory:\n"
709 " \"%ls\" -> \"%ls\"\n"
710 " (Use --norpfix to capture all symbolic links "
711 "and junction points as-is)",
712 (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK) ?
713 L"absolute symbolic link" : L"junction point",
722 * Loads the reparse point data from a reparse point into memory, optionally
723 * fixing the targets of absolute symbolic links and junction points to be
724 * relative to the root of capture.
726 * @hFile: Open handle to the reparse point.
727 * @path: Path to the reparse point. Used for error messages only.
728 * @params: Additional parameters, including whether to do reparse point fixups
730 * @rpbuf: Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
731 * the reparse point buffer will be loaded.
732 * @rpbuflen_ret: On success, the length of the reparse point buffer in bytes
733 * is written to this location.
736 * On success, returns an `enum rp_status' value that indicates if and/or
737 * how the reparse point fixup was done.
739 * On failure, returns a negative value that is a negated WIMLIB_ERR_*
743 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
744 struct add_image_params *params,
745 u8 *rpbuf, u16 *rpbuflen_ret)
752 DEBUG("Loading reparse data from \"%ls\"", path);
753 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
754 NULL, /* "Not used with this operation; set to NULL" */
755 0, /* "Not used with this operation; set to 0" */
756 rpbuf, /* "A pointer to a buffer that
757 receives the reparse point data */
758 REPARSE_POINT_MAX_SIZE, /* "The size of the output
763 set_errno_from_GetLastError();
764 ERROR_WITH_ERRNO("Failed to get reparse data of \"%ls\"", path);
765 return -WIMLIB_ERR_READ;
767 if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
768 ERROR("Reparse data on \"%ls\" is invalid", path);
769 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
772 rpbuflen = bytesReturned;
773 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
774 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
775 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
776 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
778 /* Try doing reparse point fixup */
779 ret = win32_capture_try_rpfix(rpbuf,
781 params->capture_root_ino,
782 params->capture_root_dev,
787 *rpbuflen_ret = rpbuflen;
792 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
795 *(u64*)_size_ret += len;
796 return ERROR_SUCCESS;
800 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
806 err = OpenEncryptedFileRaw(path, 0, &file_ctx);
807 if (err != ERROR_SUCCESS) {
808 set_errno_from_win32_error(err);
809 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
810 "for raw read", path);
811 return WIMLIB_ERR_OPEN;
814 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
816 if (err != ERROR_SUCCESS) {
817 set_errno_from_win32_error(err);
818 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
820 ret = WIMLIB_ERR_READ;
824 CloseEncryptedFileRaw(file_ctx);
828 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
829 * stream); calculates its SHA1 message digest and either creates a `struct
830 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
831 * wim_lookup_table_entry' for an identical stream.
833 * @path: Path to the file (UTF-16LE).
835 * @path_num_chars: Number of 2-byte characters in @path.
837 * @inode: WIM inode to save the stream into.
839 * @lookup_table: Stream lookup table for the WIM.
841 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
844 * Returns 0 on success; nonzero on failure.
847 win32_capture_stream(const wchar_t *path,
848 size_t path_num_chars,
849 struct wim_inode *inode,
850 struct wim_lookup_table *lookup_table,
851 WIN32_FIND_STREAM_DATA *dat)
853 struct wim_ads_entry *ads_entry;
854 struct wim_lookup_table_entry *lte;
856 wchar_t *stream_name, *colon;
857 size_t stream_name_nchars;
858 bool is_named_stream;
861 size_t spath_buf_nbytes;
862 const wchar_t *relpath_prefix;
863 const wchar_t *colonchar;
865 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
867 /* The stream name should be returned as :NAME:TYPE */
868 stream_name = dat->cStreamName;
869 if (*stream_name != L':')
870 goto out_invalid_stream_name;
872 colon = wcschr(stream_name, L':');
874 goto out_invalid_stream_name;
876 if (wcscmp(colon + 1, L"$DATA")) {
877 /* Not a DATA stream */
884 stream_name_nchars = colon - stream_name;
885 is_named_stream = (stream_name_nchars != 0);
887 if (is_named_stream) {
888 /* Allocate an ADS entry for the named stream. */
889 ads_entry = inode_add_ads_utf16le(inode, stream_name,
890 stream_name_nchars * sizeof(wchar_t));
892 ret = WIMLIB_ERR_NOMEM;
897 /* If zero length stream, no lookup table entry needed. */
898 if ((u64)dat->StreamSize.QuadPart == 0) {
903 /* Create a UTF-16LE string @spath that gives the filename, then a
904 * colon, then the stream name. Or, if it's an unnamed stream, just the
905 * filename. It is MALLOC()'ed so that it can be saved in the
906 * wim_lookup_table_entry if needed.
908 * As yet another special case, relative paths need to be changed to
909 * begin with an explicit "./" so that, for example, a file t:ads, where
910 * :ads is the part we added, is not interpreted as a file on the t:
912 spath_nchars = path_num_chars;
913 relpath_prefix = L"";
915 if (is_named_stream) {
916 spath_nchars += 1 + stream_name_nchars;
918 if (path_num_chars == 1 && !is_any_path_separator(path[0])) {
920 static const wchar_t _relpath_prefix[] =
921 {L'.', OS_PREFERRED_PATH_SEPARATOR, L'\0'};
922 relpath_prefix = _relpath_prefix;
926 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
927 spath = MALLOC(spath_buf_nbytes);
929 tsprintf(spath, L"%ls%ls%ls%ls",
930 relpath_prefix, path, colonchar, stream_name);
932 /* Make a new wim_lookup_table_entry */
933 lte = new_lookup_table_entry();
935 ret = WIMLIB_ERR_NOMEM;
938 lte->file_on_disk = spath;
940 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
942 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
943 ret = win32_get_encrypted_file_size(path, &encrypted_size);
946 lte->resource_entry.original_size = encrypted_size;
948 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
949 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
953 if (is_named_stream) {
954 stream_id = ads_entry->stream_id;
955 ads_entry->lte = lte;
960 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
966 out_invalid_stream_name:
967 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
968 ret = WIMLIB_ERR_READ;
972 /* Load information about the streams of an open file into a WIM inode.
974 * By default, we use the NtQueryInformationFile() system call instead of
975 * FindFirstStream() and FindNextStream(). This is done for two reasons:
977 * - FindFirstStream() opens its own handle to the file or directory and
978 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
979 * causing access denied errors on certain files (even when running as the
981 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
982 * and later, whereas the stream support in NtQueryInformationFile() was
983 * already present in Windows XP.
986 win32_capture_streams(HANDLE *hFile_p,
988 size_t path_num_chars,
989 struct wim_inode *inode,
990 struct wim_lookup_table *lookup_table,
994 WIN32_FIND_STREAM_DATA dat;
997 u8 _buf[8192] _aligned_attribute(8);
1000 IO_STATUS_BLOCK io_status;
1002 const FILE_STREAM_INFORMATION *info;
1007 DEBUG("Capturing streams from \"%ls\"", path);
1009 if (!(vol_flags & FILE_NAMED_STREAMS))
1013 if (func_NtQueryInformationFile) {
1015 bufsize = sizeof(_buf);
1017 /* Get a buffer containing the stream information. */
1019 status = (*func_NtQueryInformationFile)(*hFile_p, &io_status,
1021 FileStreamInformation);
1022 if (status == STATUS_SUCCESS) {
1024 } else if (status == STATUS_BUFFER_OVERFLOW) {
1029 newbuf = MALLOC(bufsize);
1031 newbuf = REALLOC(buf, bufsize);
1034 ret = WIMLIB_ERR_NOMEM;
1039 set_errno_from_nt_status(status);
1040 ERROR_WITH_ERRNO("Failed to read streams of %ls", path);
1041 ret = WIMLIB_ERR_READ;
1046 if (io_status.Information == 0) {
1047 /* No stream information. */
1052 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1053 /* OpenEncryptedFileRaw() seems to fail with
1054 * ERROR_SHARING_VIOLATION if there are any handles opened to
1056 CloseHandle(*hFile_p);
1057 *hFile_p = INVALID_HANDLE_VALUE;
1060 /* Parse one or more stream information structures. */
1061 info = (const FILE_STREAM_INFORMATION*)buf;
1063 if (info->StreamNameLength <= sizeof(dat.cStreamName) - 2) {
1064 dat.StreamSize = info->StreamSize;
1065 memcpy(dat.cStreamName, info->StreamName, info->StreamNameLength);
1066 dat.cStreamName[info->StreamNameLength / 2] = L'\0';
1068 /* Capture the stream. */
1069 ret = win32_capture_stream(path, path_num_chars, inode,
1070 lookup_table, &dat);
1074 if (info->NextEntryOffset == 0) {
1075 /* No more stream information. */
1079 /* Advance to next stream information. */
1080 info = (const FILE_STREAM_INFORMATION*)
1081 ((const u8*)info + info->NextEntryOffset);
1084 /* Free buffer if allocated on heap. */
1089 #endif /* WITH_NTDLL */
1091 if (win32func_FindFirstStreamW == NULL)
1093 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1094 if (hFind == INVALID_HANDLE_VALUE) {
1095 err = GetLastError();
1096 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1099 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1100 * points and directories */
1101 if ((inode->i_attributes &
1102 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1103 && err == ERROR_HANDLE_EOF)
1105 DEBUG("ERROR_HANDLE_EOF (ok)");
1108 if (err == ERROR_ACCESS_DENIED) {
1109 WARNING("Failed to look up data streams "
1110 "of \"%ls\": Access denied!\n%ls",
1111 path, capture_access_denied_msg);
1114 set_errno_from_win32_error(err);
1115 ERROR_WITH_ERRNO("Failed to look up data streams "
1116 "of \"%ls\"", path);
1117 return WIMLIB_ERR_READ;
1122 ret = win32_capture_stream(path,
1124 inode, lookup_table,
1127 goto out_find_close;
1128 } while (win32func_FindNextStreamW(hFind, &dat));
1129 err = GetLastError();
1130 if (err != ERROR_HANDLE_EOF) {
1131 set_errno_from_win32_error(err);
1132 ERROR_WITH_ERRNO("Error reading data streams from "
1134 ret = WIMLIB_ERR_READ;
1141 /* FindFirstStream() API is not available, or the volume does not
1142 * support named streams. Only capture the unnamed data stream. */
1143 DEBUG("Only capturing unnamed data stream");
1144 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1145 FILE_ATTRIBUTE_REPARSE_POINT))
1148 wcscpy(dat.cStreamName, L"::$DATA");
1149 dat.StreamSize.QuadPart = file_size;
1150 return win32_capture_stream(path, path_num_chars,
1151 inode, lookup_table, &dat);
1155 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1157 size_t path_num_chars,
1158 struct add_image_params *params,
1159 struct win32_capture_state *state,
1162 struct wim_dentry *root = NULL;
1163 struct wim_inode *inode;
1171 DWORD desiredAccess;
1173 params->progress.scan.cur_path = path;
1175 if (exclude_path(path, path_num_chars, params->config, true)) {
1176 if (params->add_flags & WIMLIB_ADD_FLAG_ROOT) {
1177 ERROR("Cannot exclude the root directory from capture");
1178 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1181 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED);
1187 if (path_num_chars >= 4 &&
1188 !wmemcmp(path, L"\\\\?\\", 4) &&
1189 path_num_chars + 1 - 4 > MAX_PATH &&
1190 state->num_long_path_warnings < MAX_CAPTURE_LONG_PATH_WARNINGS)
1192 WARNING("Path \"%ls\" exceeds MAX_PATH", path);
1193 if (++state->num_long_path_warnings == MAX_CAPTURE_LONG_PATH_WARNINGS)
1194 WARNING("Suppressing further warnings about long paths.");
1198 do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK);
1200 desiredAccess = FILE_READ_DATA | FILE_READ_ATTRIBUTES |
1201 READ_CONTROL | ACCESS_SYSTEM_SECURITY;
1203 hFile = win32_open_existing_file(path, desiredAccess);
1204 if (hFile == INVALID_HANDLE_VALUE) {
1205 err = GetLastError();
1206 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD) {
1207 if (desiredAccess & ACCESS_SYSTEM_SECURITY) {
1208 desiredAccess &= ~ACCESS_SYSTEM_SECURITY;
1211 if (desiredAccess & READ_CONTROL) {
1212 desiredAccess &= ~READ_CONTROL;
1216 set_errno_from_GetLastError();
1217 ERROR_WITH_ERRNO("Failed to open \"%ls\" for reading", path);
1218 ret = WIMLIB_ERR_OPEN;
1222 BY_HANDLE_FILE_INFORMATION file_info;
1223 if (!GetFileInformationByHandle(hFile, &file_info)) {
1224 set_errno_from_GetLastError();
1225 ERROR_WITH_ERRNO("Failed to get file information for \"%ls\"",
1227 ret = WIMLIB_ERR_STAT;
1228 goto out_close_handle;
1231 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1232 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1233 ret = win32_get_reparse_data(hFile, path, params,
1236 /* WIMLIB_ERR_* (inverted) */
1238 goto out_close_handle;
1239 } else if (ret & RP_FIXED) {
1241 } else if (ret == RP_EXCLUDED) {
1243 goto out_close_handle;
1249 /* Create a WIM dentry with an associated inode, which may be shared.
1251 * However, we need to explicitly check for directories and files with
1252 * only 1 link and refuse to hard link them. This is because Windows
1253 * has a bug where it can return duplicate File IDs for files and
1254 * directories on the FAT filesystem. */
1255 ret = inode_table_new_dentry(¶ms->inode_table,
1256 path_basename_with_len(path, path_num_chars),
1257 ((u64)file_info.nFileIndexHigh << 32) |
1258 (u64)file_info.nFileIndexLow,
1259 file_info.dwVolumeSerialNumber,
1260 (file_info.nNumberOfLinks <= 1 ||
1261 (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1264 goto out_close_handle;
1266 ret = win32_get_short_name(hFile, path, root);
1268 goto out_close_handle;
1270 inode = root->d_inode;
1272 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1273 goto out_close_handle;
1275 inode->i_attributes = file_info.dwFileAttributes;
1276 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1277 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1278 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1279 inode->i_resolved = 1;
1281 params->add_flags &= ~WIMLIB_ADD_FLAG_ROOT;
1283 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1284 && (vol_flags & FILE_PERSISTENT_ACLS))
1286 ret = win32_get_security_descriptor(hFile, path, inode,
1287 ¶ms->sd_set, state,
1290 goto out_close_handle;
1293 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1294 (u64)file_info.nFileSizeLow;
1297 /* Capture the unnamed data stream (only should be present for regular
1298 * files) and any alternate data streams. */
1299 ret = win32_capture_streams(&hFile,
1303 params->lookup_table,
1307 goto out_close_handle;
1309 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1310 /* Reparse point: set the reparse data (which we read already)
1312 inode->i_not_rpfixed = not_rpfixed;
1313 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1314 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1315 params->lookup_table);
1316 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1317 /* Directory (not a reparse point) --- recurse to children */
1319 if (hFile == INVALID_HANDLE_VALUE) {
1320 /* Re-open handle that was closed to read raw encrypted
1322 hFile = win32_open_existing_file(path, FILE_READ_DATA);
1323 if (hFile == INVALID_HANDLE_VALUE) {
1324 set_errno_from_GetLastError();
1325 ERROR_WITH_ERRNO("Failed to reopen \"%ls\"",
1327 ret = WIMLIB_ERR_OPEN;
1328 goto out_close_handle;
1331 ret = win32_recurse_directory(hFile,
1345 free_dentry_tree(root, params->lookup_table);
1350 win32_do_capture_warnings(const wchar_t *path,
1351 const struct win32_capture_state *state,
1354 if (state->num_get_sacl_priv_notheld == 0 &&
1355 state->num_get_sd_access_denied == 0)
1358 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1359 if (state->num_get_sacl_priv_notheld != 0) {
1360 WARNING("- Could not capture SACL (System Access Control List)\n"
1361 " on %lu files or directories.",
1362 state->num_get_sacl_priv_notheld);
1364 if (state->num_get_sd_access_denied != 0) {
1365 WARNING("- Could not capture security descriptor at all\n"
1366 " on %lu files or directories.",
1367 state->num_get_sd_access_denied);
1369 WARNING("To fully capture all security descriptors, run the program\n"
1370 " with Administrator rights.");
1373 #define WINDOWS_NT_MAX_PATH 32768
1375 /* Win32 version of capturing a directory tree */
1377 win32_build_dentry_tree(struct wim_dentry **root_ret,
1378 const wchar_t *root_disk_path,
1379 struct add_image_params *params)
1384 struct win32_capture_state state;
1387 bool need_prefix_free = false;
1389 if (!win32func_FindFirstStreamW
1391 && !func_NtQueryInformationFile
1395 WARNING("Running on Windows XP or earlier; "
1396 "alternate data streams will not be captured.");
1399 path_nchars = wcslen(root_disk_path);
1400 if (path_nchars > WINDOWS_NT_MAX_PATH)
1401 return WIMLIB_ERR_INVALID_PARAM;
1403 ret = win32_get_file_and_vol_ids(root_disk_path,
1404 ¶ms->capture_root_ino,
1405 ¶ms->capture_root_dev);
1407 ERROR_WITH_ERRNO("Can't open %ls", root_disk_path);
1411 win32_get_vol_flags(root_disk_path, &vol_flags, NULL);
1413 /* WARNING: There is no check for overflow later when this buffer is
1414 * being used! But it's as long as the maximum path length understood
1415 * by Windows NT (which is NOT the same as MAX_PATH). */
1416 path = MALLOC(WINDOWS_NT_MAX_PATH * sizeof(wchar_t));
1418 return WIMLIB_ERR_NOMEM;
1420 /* Work around defective behavior in Windows where paths longer than 260
1421 * characters are not supported by default; instead they need to be
1422 * turned into absolute paths and prefixed with "\\?\". */
1424 if (wcsncmp(root_disk_path, L"\\\\?\\", 4)) {
1425 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 4,
1428 if (dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 4) {
1429 WARNING("Can't get full path name for \"%ls\"", root_disk_path);
1430 wmemcpy(path, root_disk_path, path_nchars + 1);
1432 wmemcpy(path, L"\\\\?\\", 4);
1433 path_nchars = 4 + dret;
1434 /* Update pattern prefix */
1435 if (params->config != NULL)
1437 params->config->_prefix = TSTRDUP(path);
1438 params->config->_prefix_num_tchars = path_nchars;
1439 if (params->config->_prefix == NULL)
1441 ret = WIMLIB_ERR_NOMEM;
1444 need_prefix_free = true;
1448 wmemcpy(path, root_disk_path, path_nchars + 1);
1451 memset(&state, 0, sizeof(state));
1452 ret = win32_build_dentry_tree_recursive(root_ret, path,
1453 path_nchars, params,
1455 if (need_prefix_free)
1456 FREE(params->config->_prefix);
1460 win32_do_capture_warnings(root_disk_path, &state, params->add_flags);
1464 #endif /* __WIN32__ */