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 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
45 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
46 #define MAX_CAPTURE_LONG_PATH_WARNINGS 5
48 struct win32_capture_state {
49 unsigned long num_get_sd_access_denied;
50 unsigned long num_get_sacl_priv_notheld;
51 unsigned long num_long_path_warnings;
55 static const wchar_t *capture_access_denied_msg =
56 L" If you are not running this program as the administrator, you may\n"
57 " need to do so, so that all data and metadata can be backed up.\n"
58 " Otherwise, there may be no way to access the desired data or\n"
59 " metadata without taking ownership of the file or directory.\n"
63 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
65 consume_data_callback_t cb,
74 HANDLE hFile = win32_open_file_data_only(lte->file_on_disk);
75 if (hFile == INVALID_HANDLE_VALUE) {
77 ERROR("Failed to open \"%ls\"", lte->file_on_disk);
79 return WIMLIB_ERR_OPEN;
83 out_buf = alloca(WIM_CHUNK_SIZE);
87 bytes_remaining = size;
88 while (bytes_remaining) {
89 DWORD bytesToRead, bytesRead;
91 bytesToRead = min(WIM_CHUNK_SIZE, bytes_remaining);
92 if (!ReadFile(hFile, out_buf, bytesToRead, &bytesRead, NULL) ||
93 bytesRead != bytesToRead)
96 ERROR("Failed to read data from \"%ls\"", lte->file_on_disk);
98 ret = WIMLIB_ERR_READ;
101 bytes_remaining -= bytesRead;
103 ret = (*cb)(out_buf, bytesRead, ctx_or_buf);
107 out_buf += bytesRead;
114 struct win32_encrypted_read_ctx {
115 consume_data_callback_t read_prefix_cb;
116 void *read_prefix_ctx_or_buf;
124 win32_encrypted_export_cb(unsigned char *_data, void *_ctx, unsigned long len)
126 const void *data = _data;
127 struct win32_encrypted_read_ctx *ctx = _ctx;
130 DEBUG("len = %lu", len);
131 if (ctx->read_prefix_cb) {
132 /* The length of the buffer passed to the ReadEncryptedFileRaw()
133 * export callback is undocumented, so we assume it may be of
135 size_t bytes_to_buffer = min(ctx->bytes_remaining - ctx->buf_filled,
137 while (bytes_to_buffer) {
138 size_t bytes_to_copy_to_buf =
139 min(bytes_to_buffer, WIM_CHUNK_SIZE - ctx->buf_filled);
141 memcpy(ctx->buf + ctx->buf_filled, data,
142 bytes_to_copy_to_buf);
143 ctx->buf_filled += bytes_to_copy_to_buf;
144 data += bytes_to_copy_to_buf;
145 bytes_to_buffer -= bytes_to_copy_to_buf;
147 if (ctx->buf_filled == WIM_CHUNK_SIZE ||
148 ctx->buf_filled == ctx->bytes_remaining)
150 ret = (*ctx->read_prefix_cb)(ctx->buf,
152 ctx->read_prefix_ctx_or_buf);
154 ctx->wimlib_err_code = ret;
155 /* Shouldn't matter what error code is returned
156 * here, as long as it isn't ERROR_SUCCESS. */
157 return ERROR_READ_FAULT;
159 ctx->bytes_remaining -= ctx->buf_filled;
164 size_t len_to_copy = min(len, ctx->bytes_remaining);
165 ctx->read_prefix_ctx_or_buf = mempcpy(ctx->read_prefix_ctx_or_buf,
168 ctx->bytes_remaining -= len_to_copy;
170 return ERROR_SUCCESS;
174 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
176 consume_data_callback_t cb,
180 struct win32_encrypted_read_ctx export_ctx;
185 DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
186 size, lte->file_on_disk);
188 export_ctx.read_prefix_cb = cb;
189 export_ctx.read_prefix_ctx_or_buf = ctx_or_buf;
190 export_ctx.wimlib_err_code = 0;
192 export_ctx.buf = MALLOC(WIM_CHUNK_SIZE);
194 return WIMLIB_ERR_NOMEM;
196 export_ctx.buf = NULL;
198 export_ctx.buf_filled = 0;
199 export_ctx.bytes_remaining = size;
201 err = OpenEncryptedFileRawW(lte->file_on_disk, 0, &file_ctx);
202 if (err != ERROR_SUCCESS) {
203 ERROR("Failed to open encrypted file \"%ls\" for raw read",
206 ret = WIMLIB_ERR_OPEN;
209 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
210 &export_ctx, file_ctx);
211 if (err != ERROR_SUCCESS) {
212 ERROR("Failed to read encrypted file \"%ls\"",
215 ret = export_ctx.wimlib_err_code;
217 ret = WIMLIB_ERR_READ;
218 } else if (export_ctx.bytes_remaining != 0) {
219 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
220 "encryted file \"%ls\"",
221 size - export_ctx.bytes_remaining, size,
223 ret = WIMLIB_ERR_READ;
227 CloseEncryptedFileRaw(file_ctx);
229 FREE(export_ctx.buf);
235 FILETIME_to_u64(const FILETIME *ft)
237 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
241 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
243 WIN32_FIND_DATAW dat;
247 /* If we can't read the short filename for some reason, we just ignore
248 * the error and assume the file has no short name. I don't think this
249 * should be an issue, since the short names are essentially obsolete
251 hFind = FindFirstFileW(path, &dat);
252 if (hFind != INVALID_HANDLE_VALUE) {
253 if (dat.cAlternateFileName[0] != L'\0') {
254 DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
255 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
257 size_t n = short_name_nbytes + sizeof(wchar_t);
258 dentry->short_name = MALLOC(n);
259 if (dentry->short_name) {
260 memcpy(dentry->short_name, dat.cAlternateFileName, n);
261 dentry->short_name_nbytes = short_name_nbytes;
263 ret = WIMLIB_ERR_NOMEM;
272 win32_get_security_descriptor(struct wim_dentry *dentry,
273 struct wim_sd_set *sd_set,
275 struct win32_capture_state *state,
278 SECURITY_INFORMATION requestedInformation;
284 requestedInformation = DACL_SECURITY_INFORMATION |
285 SACL_SECURITY_INFORMATION |
286 OWNER_SECURITY_INFORMATION |
287 GROUP_SECURITY_INFORMATION;
289 /* Request length of security descriptor */
290 status = GetFileSecurityW(path, requestedInformation,
291 NULL, 0, &lenNeeded);
292 err = GetLastError();
293 if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
294 DWORD len = lenNeeded;
296 if (GetFileSecurityW(path, requestedInformation,
297 (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
299 int security_id = sd_set_add_sd(sd_set, buf, len);
301 return WIMLIB_ERR_NOMEM;
303 dentry->d_inode->i_security_id = security_id;
307 err = GetLastError();
311 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS)
315 case ERROR_PRIVILEGE_NOT_HELD:
316 if (requestedInformation & SACL_SECURITY_INFORMATION) {
317 n = state->num_get_sacl_priv_notheld++;
318 requestedInformation &= ~SACL_SECURITY_INFORMATION;
319 if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
321 "We don't have enough privileges to read the full security\n"
322 " descriptor of \"%ls\"!\n"
323 " Re-trying with SACL omitted.\n", path);
324 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
326 "Suppressing further privileges not held error messages when reading\n"
327 " security descriptors.");
332 case ERROR_ACCESS_DENIED:
333 n = state->num_get_sd_access_denied++;
334 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
335 WARNING("Failed to read security descriptor of \"%ls\": "
336 "Access denied!\n%ls", path, capture_access_denied_msg);
337 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
338 WARNING("Suppressing further access denied errors messages i"
339 "when reading security descriptors");
344 ERROR("Failed to read security descriptor of \"%ls\"", path);
346 return WIMLIB_ERR_READ;
351 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
353 size_t path_num_chars,
354 struct add_image_params *params,
355 struct win32_capture_state *state,
358 /* Reads the directory entries of directory using a Win32 API and recursively
359 * calls win32_build_dentry_tree() on them. */
361 win32_recurse_directory(struct wim_dentry *root,
363 size_t dir_path_num_chars,
364 struct add_image_params *params,
365 struct win32_capture_state *state,
368 WIN32_FIND_DATAW dat;
373 DEBUG("Recurse to directory \"%ls\"", dir_path);
375 /* Begin reading the directory by calling FindFirstFileW. Unlike UNIX
376 * opendir(), FindFirstFileW has file globbing built into it. But this
377 * isn't what we actually want, so just add a dummy glob to get all
379 dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
380 dir_path[dir_path_num_chars + 1] = L'*';
381 dir_path[dir_path_num_chars + 2] = L'\0';
382 hFind = FindFirstFileW(dir_path, &dat);
383 dir_path[dir_path_num_chars] = L'\0';
385 if (hFind == INVALID_HANDLE_VALUE) {
386 err = GetLastError();
387 if (err == ERROR_FILE_NOT_FOUND) {
390 ERROR("Failed to read directory \"%ls\"", dir_path);
392 return WIMLIB_ERR_READ;
397 /* Skip . and .. entries */
398 if (dat.cFileName[0] == L'.' &&
399 (dat.cFileName[1] == L'\0' ||
400 (dat.cFileName[1] == L'.' &&
401 dat.cFileName[2] == L'\0')))
403 size_t filename_len = wcslen(dat.cFileName);
405 dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
406 wmemcpy(dir_path + dir_path_num_chars + 1,
410 struct wim_dentry *child;
411 size_t path_len = dir_path_num_chars + 1 + filename_len;
412 ret = win32_build_dentry_tree_recursive(&child,
418 dir_path[dir_path_num_chars] = L'\0';
422 dentry_add_child(root, child);
423 } while (FindNextFileW(hFind, &dat));
424 err = GetLastError();
425 if (err != ERROR_NO_MORE_FILES) {
426 ERROR("Failed to read directory \"%ls\"", dir_path);
429 ret = WIMLIB_ERR_READ;
436 /* Reparse point fixup status code */
438 /* Reparse point corresponded to an absolute symbolic link or junction
439 * point that pointed outside the directory tree being captured, and
440 * therefore was excluded. */
443 /* Reparse point was not fixed as it was either a relative symbolic
444 * link, a mount point, or something else we could not understand. */
447 /* Reparse point corresponded to an absolute symbolic link or junction
448 * point that pointed inside the directory tree being captured, where
449 * the target was specified by a "full" \??\ prefixed path, and
450 * therefore was fixed to be relative to the root of the directory tree
452 RP_FIXED_FULLPATH = 0x2,
454 /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
455 * have the \??\ prefix. It may have begun with a drive letter though.
457 RP_FIXED_ABSPATH = 0x4,
459 /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
460 RP_FIXED = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
463 /* Given the "substitute name" target of a Windows reparse point, try doing a
464 * fixup where we change it to be absolute relative to the root of the directory
465 * tree being captured.
467 * Note that this is only executed when WIMLIB_ADD_FLAG_RPFIX has been
470 * @capture_root_ino and @capture_root_dev indicate the inode number and device
471 * of the root of the directory tree being captured. They are meant to identify
472 * this directory (as an alternative to its actual path, which could potentially
473 * be reached via multiple destinations due to other symbolic links). This may
474 * not work properly on FAT, which doesn't seem to supply proper inode numbers
475 * or file IDs. However, FAT doesn't support reparse points so this function
476 * wouldn't even be called anyway.
478 static enum rp_status
479 win32_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
480 u64 capture_root_ino, u64 capture_root_dev,
483 u16 target_nchars = *target_nbytes_p / 2;
484 size_t stripped_chars;
485 wchar_t *orig_target;
488 ret = parse_substitute_name(target, *target_nbytes_p, rptag);
491 stripped_chars = ret;
494 target[target_nchars] = L'\0';
495 orig_target = target;
496 target = capture_fixup_absolute_symlink(target + stripped_chars,
497 capture_root_ino, capture_root_dev);
500 target_nchars = wcslen(target);
501 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
502 *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
503 DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
505 return RP_FIXED_FULLPATH;
507 return RP_FIXED_ABSPATH;
510 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
513 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
514 u64 capture_root_ino, u64 capture_root_dev,
517 struct reparse_data rpdata;
519 enum rp_status rp_status;
521 ret = parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata);
525 rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
526 &rpdata.substitute_name_nbytes,
529 le32_to_cpu(*(le32*)rpbuf));
530 if (rp_status & RP_FIXED) {
531 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
532 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
533 wmemcpy(substitute_name_copy, rpdata.substitute_name,
534 rpdata.substitute_name_nbytes / 2);
535 rpdata.substitute_name = substitute_name_copy;
536 rpdata.print_name = substitute_name_copy;
537 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
538 if (rp_status == RP_FIXED_FULLPATH) {
539 /* "full path", meaning \??\ prefixed. We should not
540 * include this prefix in the print name, as it is
541 * apparently meant for the filesystem driver only. */
542 rpdata.print_name += 4;
543 rpdata.print_name_nbytes -= 8;
545 ret = make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
551 if (rp_status == RP_EXCLUDED) {
552 size_t print_name_nchars = rpdata.print_name_nbytes / 2;
553 wchar_t print_name0[print_name_nchars + 1];
554 print_name0[print_name_nchars] = L'\0';
555 wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
556 WARNING("Ignoring %ls pointing out of capture directory:\n"
557 " \"%ls\" -> \"%ls\"\n"
558 " (Use --norpfix to capture all symbolic links "
559 "and junction points as-is)",
560 (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK) ?
561 L"absolute symbolic link" : L"junction point",
570 * Loads the reparse point data from a reparse point into memory, optionally
571 * fixing the targets of absolute symbolic links and junction points to be
572 * relative to the root of capture.
574 * @hFile: Open handle to the reparse point.
575 * @path: Path to the reparse point. Used for error messages only.
576 * @params: Additional parameters, including whether to do reparse point fixups
578 * @rpbuf: Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
579 * the reparse point buffer will be loaded.
580 * @rpbuflen_ret: On success, the length of the reparse point buffer in bytes
581 * is written to this location.
584 * On success, returns an `enum rp_status' value that indicates if and/or
585 * how the reparse point fixup was done.
587 * On failure, returns a negative value that is a negated WIMLIB_ERR_*
591 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
592 struct add_image_params *params,
593 u8 *rpbuf, u16 *rpbuflen_ret)
600 DEBUG("Loading reparse data from \"%ls\"", path);
601 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
602 NULL, /* "Not used with this operation; set to NULL" */
603 0, /* "Not used with this operation; set to 0" */
604 rpbuf, /* "A pointer to a buffer that
605 receives the reparse point data */
606 REPARSE_POINT_MAX_SIZE, /* "The size of the output
611 DWORD err = GetLastError();
612 ERROR("Failed to get reparse data of \"%ls\"", path);
614 return -WIMLIB_ERR_READ;
616 if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
617 ERROR("Reparse data on \"%ls\" is invalid", path);
618 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
621 rpbuflen = bytesReturned;
622 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
623 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
624 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
625 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
627 /* Try doing reparse point fixup */
628 ret = win32_capture_try_rpfix(rpbuf,
630 params->capture_root_ino,
631 params->capture_root_dev,
636 *rpbuflen_ret = rpbuflen;
641 win32_tally_encrypted_size_cb(unsigned char *_data, void *_ctx,
645 return ERROR_SUCCESS;
649 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
656 err = OpenEncryptedFileRawW(path, 0, &file_ctx);
657 if (err != ERROR_SUCCESS) {
658 ERROR("Failed to open encrypted file \"%ls\" for raw read", path);
660 return WIMLIB_ERR_OPEN;
662 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
664 if (err != ERROR_SUCCESS) {
665 ERROR("Failed to read raw encrypted data from \"%ls\"", path);
667 ret = WIMLIB_ERR_READ;
671 CloseEncryptedFileRaw(file_ctx);
675 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
676 * stream); calculates its SHA1 message digest and either creates a `struct
677 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
678 * wim_lookup_table_entry' for an identical stream.
680 * @path: Path to the file (UTF-16LE).
682 * @path_num_chars: Number of 2-byte characters in @path.
684 * @inode: WIM inode to save the stream into.
686 * @lookup_table: Stream lookup table for the WIM.
688 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
691 * Returns 0 on success; nonzero on failure.
694 win32_capture_stream(const wchar_t *path,
695 size_t path_num_chars,
696 struct wim_inode *inode,
697 struct wim_lookup_table *lookup_table,
698 WIN32_FIND_STREAM_DATA *dat)
700 struct wim_ads_entry *ads_entry;
701 struct wim_lookup_table_entry *lte;
703 wchar_t *stream_name, *colon;
704 size_t stream_name_nchars;
705 bool is_named_stream;
708 size_t spath_buf_nbytes;
709 const wchar_t *relpath_prefix;
710 const wchar_t *colonchar;
712 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
714 /* The stream name should be returned as :NAME:TYPE */
715 stream_name = dat->cStreamName;
716 if (*stream_name != L':')
717 goto out_invalid_stream_name;
719 colon = wcschr(stream_name, L':');
721 goto out_invalid_stream_name;
723 if (wcscmp(colon + 1, L"$DATA")) {
724 /* Not a DATA stream */
731 stream_name_nchars = colon - stream_name;
732 is_named_stream = (stream_name_nchars != 0);
734 if (is_named_stream) {
735 /* Allocate an ADS entry for the named stream. */
736 ads_entry = inode_add_ads_utf16le(inode, stream_name,
737 stream_name_nchars * sizeof(wchar_t));
739 ret = WIMLIB_ERR_NOMEM;
744 /* If zero length stream, no lookup table entry needed. */
745 if ((u64)dat->StreamSize.QuadPart == 0) {
750 /* Create a UTF-16LE string @spath that gives the filename, then a
751 * colon, then the stream name. Or, if it's an unnamed stream, just the
752 * filename. It is MALLOC()'ed so that it can be saved in the
753 * wim_lookup_table_entry if needed.
755 * As yet another special case, relative paths need to be changed to
756 * begin with an explicit "./" so that, for example, a file t:ads, where
757 * :ads is the part we added, is not interpreted as a file on the t:
759 spath_nchars = path_num_chars;
760 relpath_prefix = L"";
762 if (is_named_stream) {
763 spath_nchars += 1 + stream_name_nchars;
765 if (path_num_chars == 1 && !is_any_path_separator(path[0])) {
767 static const wchar_t _relpath_prefix[] =
768 {L'.', OS_PREFERRED_PATH_SEPARATOR, L'\0'};
769 relpath_prefix = _relpath_prefix;
773 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
774 spath = MALLOC(spath_buf_nbytes);
776 swprintf(spath, L"%ls%ls%ls%ls",
777 relpath_prefix, path, colonchar, stream_name);
779 /* Make a new wim_lookup_table_entry */
780 lte = new_lookup_table_entry();
782 ret = WIMLIB_ERR_NOMEM;
785 lte->file_on_disk = spath;
787 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
789 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
790 ret = win32_get_encrypted_file_size(path, &encrypted_size);
793 lte->resource_entry.original_size = encrypted_size;
795 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
796 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
800 if (is_named_stream) {
801 stream_id = ads_entry->stream_id;
802 ads_entry->lte = lte;
807 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
813 out_invalid_stream_name:
814 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
815 ret = WIMLIB_ERR_READ;
819 /* Load information about the streams of an open file into a WIM inode.
821 * By default, we use the NtQueryInformationFile() system call instead of
822 * FindFirstStream() and FindNextStream(). This is done for two reasons:
824 * - FindFirstStream() opens its own handle to the file or directory and
825 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
826 * causing access denied errors on certain files (even when running as the
828 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
829 * and later, whereas the stream support in NtQueryInformationFile() was
830 * already present in Windows XP.
833 win32_capture_streams(HANDLE hFile,
835 size_t path_num_chars,
836 struct wim_inode *inode,
837 struct wim_lookup_table *lookup_table,
841 WIN32_FIND_STREAM_DATA dat;
844 u8 _buf[8192] _aligned_attribute(8);
847 IO_STATUS_BLOCK io_status;
849 const FILE_STREAM_INFORMATION *info;
855 DEBUG("Capturing streams from \"%ls\"", path);
857 if (!(vol_flags & FILE_NAMED_STREAMS))
860 if (win32func_FindFirstStreamW == NULL)
866 bufsize = sizeof(_buf);
868 /* Get a buffer containing the stream information. */
870 status = NtQueryInformationFile(hFile, &io_status, buf, bufsize,
871 FileStreamInformation);
872 if (status == STATUS_SUCCESS) {
874 } else if (status == STATUS_BUFFER_OVERFLOW) {
879 newbuf = MALLOC(bufsize);
881 newbuf = REALLOC(buf, bufsize);
884 ret = WIMLIB_ERR_NOMEM;
889 errno = win32_error_to_errno(RtlNtStatusToDosError(status));
890 ERROR_WITH_ERRNO("Failed to read streams of %ls", path);
891 ret = WIMLIB_ERR_READ;
896 if (io_status.Information == 0) {
897 /* No stream information. */
902 /* Parse one or more stream information structures. */
903 info = (const FILE_STREAM_INFORMATION*)buf;
905 if (info->StreamNameLength <= sizeof(dat.cStreamName) - 2) {
906 dat.StreamSize = info->StreamSize;
907 memcpy(dat.cStreamName, info->StreamName, info->StreamNameLength);
908 dat.cStreamName[info->StreamNameLength / 2] = L'\0';
910 /* Capture the stream. */
911 ret = win32_capture_stream(path, path_num_chars, inode,
916 if (info->NextEntryOffset == 0) {
917 /* No more stream information. */
921 /* Advance to next stream information. */
922 info = (const FILE_STREAM_INFORMATION*)
923 ((const u8*)info + info->NextEntryOffset);
926 /* Free buffer if allocated on heap. */
931 #else /* WITH_NTDLL */
932 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
933 if (hFind == INVALID_HANDLE_VALUE) {
934 err = GetLastError();
935 if (err == ERROR_CALL_NOT_IMPLEMENTED)
938 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
939 * points and directories */
940 if ((inode->i_attributes &
941 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
942 && err == ERROR_HANDLE_EOF)
944 DEBUG("ERROR_HANDLE_EOF (ok)");
947 if (err == ERROR_ACCESS_DENIED) {
948 WARNING("Failed to look up data streams "
949 "of \"%ls\": Access denied!\n%ls",
950 path, capture_access_denied_msg);
953 ERROR("Failed to look up data streams "
956 return WIMLIB_ERR_READ;
961 ret = win32_capture_stream(path,
967 } while (win32func_FindNextStreamW(hFind, &dat));
968 err = GetLastError();
969 if (err != ERROR_HANDLE_EOF) {
970 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
972 ret = WIMLIB_ERR_READ;
977 #endif /* !WITH_NTDLL */
980 /* FindFirstStreamW() API is not available, or the volume does not
981 * support named streams. Only capture the unnamed data stream. */
982 DEBUG("Only capturing unnamed data stream");
983 if (!(inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
984 FILE_ATTRIBUTE_REPARSE_POINT)))
986 wcscpy(dat.cStreamName, L"::$DATA");
987 dat.StreamSize.QuadPart = file_size;
988 ret = win32_capture_stream(path,
999 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1001 size_t path_num_chars,
1002 struct add_image_params *params,
1003 struct win32_capture_state *state,
1006 struct wim_dentry *root = NULL;
1007 struct wim_inode *inode;
1015 params->progress.scan.cur_path = path;
1017 if (exclude_path(path, path_num_chars, params->config, true)) {
1018 if (params->add_flags & WIMLIB_ADD_FLAG_ROOT) {
1019 ERROR("Cannot exclude the root directory from capture");
1020 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1023 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED);
1029 if (path_num_chars >= 4 &&
1030 !wmemcmp(path, L"\\\\?\\", 4) &&
1031 path_num_chars + 1 - 4 > MAX_PATH &&
1032 state->num_long_path_warnings < MAX_CAPTURE_LONG_PATH_WARNINGS)
1034 WARNING("Path \"%ls\" exceeds MAX_PATH", path);
1035 if (++state->num_long_path_warnings == MAX_CAPTURE_LONG_PATH_WARNINGS)
1036 WARNING("Suppressing further warnings about long paths.");
1040 do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK);
1042 HANDLE hFile = win32_open_existing_file(path,
1043 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1044 if (hFile == INVALID_HANDLE_VALUE) {
1045 err = GetLastError();
1046 ERROR("Win32 API: Failed to open \"%ls\"", path);
1048 ret = WIMLIB_ERR_OPEN;
1052 BY_HANDLE_FILE_INFORMATION file_info;
1053 if (!GetFileInformationByHandle(hFile, &file_info)) {
1054 err = GetLastError();
1055 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1058 ret = WIMLIB_ERR_STAT;
1059 goto out_close_handle;
1062 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1063 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1064 ret = win32_get_reparse_data(hFile, path, params,
1067 /* WIMLIB_ERR_* (inverted) */
1069 goto out_close_handle;
1070 } else if (ret & RP_FIXED) {
1072 } else if (ret == RP_EXCLUDED) {
1074 goto out_close_handle;
1080 /* Create a WIM dentry with an associated inode, which may be shared.
1082 * However, we need to explicitly check for directories and files with
1083 * only 1 link and refuse to hard link them. This is because Windows
1084 * has a bug where it can return duplicate File IDs for files and
1085 * directories on the FAT filesystem. */
1086 ret = inode_table_new_dentry(¶ms->inode_table,
1087 path_basename_with_len(path, path_num_chars),
1088 ((u64)file_info.nFileIndexHigh << 32) |
1089 (u64)file_info.nFileIndexLow,
1090 file_info.dwVolumeSerialNumber,
1091 (file_info.nNumberOfLinks <= 1 ||
1092 (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1095 goto out_close_handle;
1097 ret = win32_get_short_name(root, path);
1099 goto out_close_handle;
1101 inode = root->d_inode;
1103 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1104 goto out_close_handle;
1106 inode->i_attributes = file_info.dwFileAttributes;
1107 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1108 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1109 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1110 inode->i_resolved = 1;
1112 params->add_flags &= ~WIMLIB_ADD_FLAG_ROOT;
1114 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1115 && (vol_flags & FILE_PERSISTENT_ACLS))
1117 ret = win32_get_security_descriptor(root, ¶ms->sd_set,
1121 goto out_close_handle;
1124 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1125 (u64)file_info.nFileSizeLow;
1128 /* Capture the unnamed data stream (only should be present for regular
1129 * files) and any alternate data streams. */
1130 ret = win32_capture_streams(hFile,
1134 params->lookup_table,
1138 goto out_close_handle;
1142 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1143 /* Reparse point: set the reparse data (which we read already)
1145 inode->i_not_rpfixed = not_rpfixed;
1146 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1147 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1148 params->lookup_table);
1149 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1150 /* Directory (not a reparse point) --- recurse to children */
1151 ret = win32_recurse_directory(root,
1165 free_dentry_tree(root, params->lookup_table);
1170 win32_do_capture_warnings(const struct win32_capture_state *state,
1173 if (state->num_get_sacl_priv_notheld == 0 &&
1174 state->num_get_sd_access_denied == 0)
1178 WARNING("Built dentry tree successfully, but with the following problem(s):");
1179 if (state->num_get_sacl_priv_notheld != 0) {
1180 WARNING("Could not capture SACL (System Access Control List)\n"
1181 " on %lu files or directories.",
1182 state->num_get_sacl_priv_notheld);
1184 if (state->num_get_sd_access_denied != 0) {
1185 WARNING("Could not capture security descriptor at all\n"
1186 " on %lu files or directories.",
1187 state->num_get_sd_access_denied);
1190 "Try running the program as the Administrator to make sure all the\n"
1191 " desired metadata has been captured exactly. However, if you\n"
1192 " do not care about capturing security descriptors correctly, then\n"
1193 " nothing more needs to be done%ls\n",
1194 (add_flags & WIMLIB_ADD_FLAG_NO_ACLS) ? L"." :
1195 L", although you might consider\n"
1196 " using the --no-acls option to explicitly capture no security\n"
1200 #define WINDOWS_NT_MAX_PATH 32768
1202 /* Win32 version of capturing a directory tree */
1204 win32_build_dentry_tree(struct wim_dentry **root_ret,
1205 const wchar_t *root_disk_path,
1206 struct add_image_params *params)
1211 struct win32_capture_state state;
1214 bool need_prefix_free = false;
1217 if (!win32func_FindFirstStreamW) {
1218 WARNING("Running on Windows XP or earlier; "
1219 "alternate data streams will not be captured.");
1223 path_nchars = wcslen(root_disk_path);
1224 if (path_nchars > WINDOWS_NT_MAX_PATH)
1225 return WIMLIB_ERR_INVALID_PARAM;
1227 if (GetFileAttributesW(root_disk_path) == INVALID_FILE_ATTRIBUTES &&
1228 GetLastError() == ERROR_FILE_NOT_FOUND)
1230 ERROR("Capture directory \"%ls\" does not exist!",
1232 return WIMLIB_ERR_OPENDIR;
1235 ret = win32_get_file_and_vol_ids(root_disk_path,
1236 ¶ms->capture_root_ino,
1237 ¶ms->capture_root_dev);
1241 win32_get_vol_flags(root_disk_path, &vol_flags, NULL);
1243 /* WARNING: There is no check for overflow later when this buffer is
1244 * being used! But it's as long as the maximum path length understood
1245 * by Windows NT (which is NOT the same as MAX_PATH). */
1246 path = MALLOC(WINDOWS_NT_MAX_PATH * sizeof(wchar_t));
1248 return WIMLIB_ERR_NOMEM;
1250 /* Work around defective behavior in Windows where paths longer than 260
1251 * characters are not supported by default; instead they need to be
1252 * turned into absolute paths and prefixed with "\\?\". */
1254 if (wcsncmp(root_disk_path, L"\\\\?\\", 4)) {
1255 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 4,
1258 if (dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 4) {
1259 WARNING("Can't get full path name for \"%ls\"", root_disk_path);
1260 wmemcpy(path, root_disk_path, path_nchars + 1);
1262 wmemcpy(path, L"\\\\?\\", 4);
1263 path_nchars = 4 + dret;
1264 /* Update pattern prefix */
1265 if (params->config != NULL)
1267 params->config->_prefix = TSTRDUP(path);
1268 params->config->_prefix_num_tchars = path_nchars;
1269 if (params->config->_prefix == NULL)
1271 ret = WIMLIB_ERR_NOMEM;
1274 need_prefix_free = true;
1278 wmemcpy(path, root_disk_path, path_nchars + 1);
1281 memset(&state, 0, sizeof(state));
1282 ret = win32_build_dentry_tree_recursive(root_ret, path,
1283 path_nchars, params,
1285 if (need_prefix_free)
1286 FREE(params->config->_prefix);
1290 win32_do_capture_warnings(&state, params->add_flags);
1294 #endif /* __WIN32__ */