2 * win32_capture.c - Windows-specific code for capturing files into a WIM image.
6 * Copyright (C) 2013, 2014 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/dentry.h"
34 #include "wimlib/encoding.h"
35 #include "wimlib/endianness.h"
36 #include "wimlib/error.h"
37 #include "wimlib/lookup_table.h"
38 #include "wimlib/paths.h"
39 #include "wimlib/reparse.h"
41 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
42 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
43 #define MAX_CAPTURE_LONG_PATH_WARNINGS 5
45 struct win32_capture_state {
46 unsigned long num_get_sd_access_denied;
47 unsigned long num_get_sacl_priv_notheld;
48 unsigned long num_long_path_warnings;
53 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
55 consume_data_callback_t cb,
62 HANDLE hFile = win32_open_existing_file(lte->file_on_disk,
64 if (hFile == INVALID_HANDLE_VALUE) {
65 set_errno_from_GetLastError();
66 ERROR_WITH_ERRNO("Failed to open \"%ls\"", lte->file_on_disk);
67 return WIMLIB_ERR_OPEN;
70 bytes_remaining = size;
71 while (bytes_remaining) {
72 DWORD bytesToRead, bytesRead;
74 bytesToRead = min(sizeof(buf), bytes_remaining);
75 if (!ReadFile(hFile, buf, bytesToRead, &bytesRead, NULL) ||
76 bytesRead != bytesToRead)
78 set_errno_from_GetLastError();
79 ERROR_WITH_ERRNO("Failed to read data from \"%ls\"",
81 ret = WIMLIB_ERR_READ;
84 bytes_remaining -= bytesRead;
85 ret = (*cb)(buf, bytesRead, cb_ctx);
93 struct win32_encrypted_read_ctx {
94 consume_data_callback_t read_prefix_cb;
95 void *read_prefix_ctx;
101 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
103 struct win32_encrypted_read_ctx *ctx = _ctx;
105 size_t bytes_to_consume = min(len, ctx->bytes_remaining);
107 if (bytes_to_consume == 0)
108 return ERROR_SUCCESS;
110 ret = (*ctx->read_prefix_cb)(data, bytes_to_consume, ctx->read_prefix_ctx);
112 ctx->wimlib_err_code = ret;
113 /* Shouldn't matter what error code is returned here, as long as
114 * it isn't ERROR_SUCCESS. */
115 return ERROR_READ_FAULT;
117 ctx->bytes_remaining -= bytes_to_consume;
118 return ERROR_SUCCESS;
122 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
124 consume_data_callback_t cb,
127 struct win32_encrypted_read_ctx export_ctx;
132 DEBUG("Reading %"PRIu64" bytes from encrypted file \"%ls\"",
133 size, lte->file_on_disk);
135 export_ctx.read_prefix_cb = cb;
136 export_ctx.read_prefix_ctx = cb_ctx;
137 export_ctx.wimlib_err_code = 0;
138 export_ctx.bytes_remaining = size;
140 err = OpenEncryptedFileRaw(lte->file_on_disk, 0, &file_ctx);
141 if (err != ERROR_SUCCESS) {
142 set_errno_from_win32_error(err);
143 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
144 "for raw read", lte->file_on_disk);
145 return WIMLIB_ERR_OPEN;
147 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
148 &export_ctx, file_ctx);
149 if (err != ERROR_SUCCESS) {
150 set_errno_from_win32_error(err);
151 ERROR_WITH_ERRNO("Failed to read encrypted file \"%ls\"",
153 ret = export_ctx.wimlib_err_code;
155 ret = WIMLIB_ERR_READ;
156 } else if (export_ctx.bytes_remaining != 0) {
157 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
158 "encryted file \"%ls\"",
159 size - export_ctx.bytes_remaining, size,
161 ret = WIMLIB_ERR_READ;
165 CloseEncryptedFileRaw(file_ctx);
171 FILETIME_to_u64(const FILETIME *ft)
173 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
176 /* Load the short name of a file into a WIM dentry.
178 * If we can't read the short filename for some reason, we just ignore the error
179 * and assume the file has no short name. This shouldn't be an issue, since the
180 * short names are essentially obsolete anyway.
183 win32_get_short_name(HANDLE hFile, struct wim_dentry *dentry)
186 /* It's not any harder to just make the NtQueryInformationFile() system
187 * call ourselves, and it saves a dumb call to FindFirstFile() which of
188 * course has to create its own handle. */
190 IO_STATUS_BLOCK io_status;
191 u8 buf[128] _aligned_attribute(8);
192 const FILE_NAME_INFORMATION *info;
194 status = (*func_NtQueryInformationFile)(hFile, &io_status, buf, sizeof(buf),
195 FileAlternateNameInformation);
196 info = (const FILE_NAME_INFORMATION*)buf;
197 if (NT_SUCCESS(status) && info->FileNameLength != 0) {
198 dentry->short_name = utf16le_dupz(info->FileName,
199 info->FileNameLength);
200 if (!dentry->short_name)
201 return WIMLIB_ERR_NOMEM;
202 dentry->short_name_nbytes = info->FileNameLength;
208 win32_get_security_descriptor(HANDLE hFile,
210 struct wim_inode *inode,
211 struct wim_sd_set *sd_set,
212 struct win32_capture_state *state,
215 SECURITY_INFORMATION requestedInformation;
223 requestedInformation = DACL_SECURITY_INFORMATION |
224 SACL_SECURITY_INFORMATION |
225 OWNER_SECURITY_INFORMATION |
226 GROUP_SECURITY_INFORMATION;
228 bufsize = sizeof(_buf);
231 * We need the file's security descriptor in SECURITY_DESCRIPTOR_RELATIVE
232 * format, and we currently have a handle opened with as many relevant
233 * permissions as possible. At this point, on Windows there are a number of
234 * options for reading a file's security descriptor:
236 * GetFileSecurity(): This takes in a path and returns the
237 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle, not
238 * ours, and the handle created internally doesn't specify
239 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied errors on
240 * some files and directories, even when running as the Administrator.
242 * GetSecurityInfo(): This takes in a handle and returns the security
243 * descriptor split into a bunch of different parts. This should work, but it's
244 * dumb because we have to put the security descriptor back together again.
246 * BackupRead(): This can read the security descriptor, but this is a
247 * difficult-to-use API, probably only works as the Administrator, and the
248 * format of the returned data is not well documented.
250 * NtQuerySecurityObject(): This is exactly what we need, as it takes in a
251 * handle and returns the security descriptor in SECURITY_DESCRIPTOR_RELATIVE
252 * format. Only problem is that it's a ntdll function and therefore not
253 * officially part of the Win32 API. Oh well.
255 while (!(NT_SUCCESS(status = (*func_NtQuerySecurityObject)(hFile,
256 requestedInformation,
257 (PSECURITY_DESCRIPTOR)buf,
262 case STATUS_BUFFER_OVERFLOW:
263 wimlib_assert(buf == _buf);
264 buf = MALLOC(lenNeeded);
266 return WIMLIB_ERR_NOMEM;
269 case STATUS_PRIVILEGE_NOT_HELD:
270 case STATUS_ACCESS_DENIED:
271 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
273 set_errno_from_nt_status(status);
274 ERROR_WITH_ERRNO("\"%ls\": Failed to "
275 "read security descriptor", path);
276 ret = WIMLIB_ERR_READ;
279 if (requestedInformation & SACL_SECURITY_INFORMATION) {
280 state->num_get_sacl_priv_notheld++;
281 requestedInformation &= ~SACL_SECURITY_INFORMATION;
284 state->num_get_sd_access_denied++;
290 inode->i_security_id = sd_set_add_sd(sd_set, buf, lenNeeded);
291 if (inode->i_security_id < 0)
292 ret = WIMLIB_ERR_NOMEM;
302 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
304 size_t path_num_chars,
305 struct add_image_params *params,
306 struct win32_capture_state *state,
309 /* Reads the directory entries of directory and recursively calls
310 * win32_build_dentry_tree() on them. */
312 win32_recurse_directory(HANDLE hDir,
314 size_t dir_path_num_chars,
315 struct wim_dentry *root,
316 struct add_image_params *params,
317 struct win32_capture_state *state,
322 DEBUG("Recurse to directory \"%ls\"", dir_path);
324 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
325 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
328 IO_STATUS_BLOCK io_status;
329 const size_t bufsize = 8192;
332 buf = MALLOC(bufsize);
334 return WIMLIB_ERR_NOMEM;
336 while (NT_SUCCESS(status = (*func_NtQueryDirectoryFile)(hDir, NULL, NULL, NULL,
337 &io_status, buf, bufsize,
338 FileNamesInformation,
339 FALSE, NULL, FALSE)))
341 const FILE_NAMES_INFORMATION *info = buf;
343 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
344 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
345 info->FileName[1] == L'.'))
348 struct wim_dentry *child;
350 p = dir_path + dir_path_num_chars;
352 p = wmempcpy(p, info->FileName,
353 info->FileNameLength / 2);
356 ret = win32_build_dentry_tree_recursive(
364 dir_path[dir_path_num_chars] = L'\0';
369 dentry_add_child(root, child);
371 if (info->NextEntryOffset == 0)
373 info = (const FILE_NAMES_INFORMATION *)
374 ((const u8 *)info + info->NextEntryOffset);
378 if (status != STATUS_NO_MORE_FILES) {
379 set_errno_from_nt_status(status);
380 ERROR_WITH_ERRNO("Failed to read directory \"%ls\"", dir_path);
381 ret = WIMLIB_ERR_READ;
388 /* Reparse point fixup status code */
390 /* Reparse point corresponded to an absolute symbolic link or junction
391 * point that pointed outside the directory tree being captured, and
392 * therefore was excluded. */
395 /* Reparse point was not fixed as it was either a relative symbolic
396 * link, a mount point, or something else we could not understand. */
399 /* Reparse point corresponded to an absolute symbolic link or junction
400 * point that pointed inside the directory tree being captured, where
401 * the target was specified by a "full" \??\ prefixed path, and
402 * therefore was fixed to be relative to the root of the directory tree
404 RP_FIXED_FULLPATH = 0x2,
406 /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
407 * have the \??\ prefix. It may have begun with a drive letter though.
409 RP_FIXED_ABSPATH = 0x4,
411 /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
412 RP_FIXED = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
415 /* Given the "substitute name" target of a Windows reparse point, try doing a
416 * fixup where we change it to be absolute relative to the root of the directory
417 * tree being captured.
419 * Note that this is only executed when WIMLIB_ADD_FLAG_RPFIX has been
422 * @capture_root_ino and @capture_root_dev indicate the inode number and device
423 * of the root of the directory tree being captured. They are meant to identify
424 * this directory (as an alternative to its actual path, which could potentially
425 * be reached via multiple destinations due to other symbolic links). This may
426 * not work properly on FAT, which doesn't seem to supply proper inode numbers
427 * or file IDs. However, FAT doesn't support reparse points so this function
428 * wouldn't even be called anyway.
430 static enum rp_status
431 win32_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
432 u64 capture_root_ino, u64 capture_root_dev,
435 u16 target_nchars = *target_nbytes_p / 2;
436 size_t stripped_chars;
437 wchar_t *orig_target;
440 ret = parse_substitute_name(target, *target_nbytes_p, rptag);
443 stripped_chars = ret;
446 target[target_nchars] = L'\0';
447 orig_target = target;
448 target = capture_fixup_absolute_symlink(target + stripped_chars,
449 capture_root_ino, capture_root_dev);
452 target_nchars = wcslen(target);
453 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
454 *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
455 DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
457 return RP_FIXED_FULLPATH;
459 return RP_FIXED_ABSPATH;
462 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
465 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
466 u64 capture_root_ino, u64 capture_root_dev,
467 const wchar_t *path, struct add_image_params *params)
469 struct reparse_data rpdata;
471 enum rp_status rp_status;
473 ret = parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata);
477 rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
478 &rpdata.substitute_name_nbytes,
481 le32_to_cpu(*(le32*)rpbuf));
482 if (rp_status & RP_FIXED) {
483 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
484 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
485 wmemcpy(substitute_name_copy, rpdata.substitute_name,
486 rpdata.substitute_name_nbytes / 2);
487 rpdata.substitute_name = substitute_name_copy;
488 rpdata.print_name = substitute_name_copy;
489 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
490 if (rp_status == RP_FIXED_FULLPATH) {
491 /* "full path", meaning \??\ prefixed. We should not
492 * include this prefix in the print name, as it is
493 * apparently meant for the filesystem driver only. */
494 rpdata.print_name += 4;
495 rpdata.print_name_nbytes -= 8;
497 ret = make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
503 if (rp_status == RP_EXCLUDED) {
504 /* Ignoring absolute symbolic link or junction point
505 * that points out of the tree to be captured. */
506 size_t print_name_nchars = rpdata.print_name_nbytes / 2;
507 wchar_t print_name0[print_name_nchars + 1];
508 print_name0[print_name_nchars] = L'\0';
509 wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
511 params->progress.scan.cur_path = path;
512 params->progress.scan.symlink_target = print_name0;
513 do_capture_progress(params,
514 WIMLIB_SCAN_DENTRY_EXCLUDED_SYMLINK,
523 * Loads the reparse point data from a reparse point into memory, optionally
524 * fixing the targets of absolute symbolic links and junction points to be
525 * relative to the root of capture.
527 * @hFile: Open handle to the reparse point.
528 * @path: Path to the reparse point. Used for error messages only.
529 * @params: Additional parameters, including whether to do reparse point fixups
531 * @rpbuf: Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
532 * the reparse point buffer will be loaded.
533 * @rpbuflen_ret: On success, the length of the reparse point buffer in bytes
534 * is written to this location.
537 * On success, returns an `enum rp_status' value that indicates if and/or
538 * how the reparse point fixup was done.
540 * On failure, returns a negative value that is a negated WIMLIB_ERR_*
544 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
545 struct add_image_params *params,
546 u8 *rpbuf, u16 *rpbuflen_ret)
553 DEBUG("Loading reparse data from \"%ls\"", path);
554 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
555 NULL, /* "Not used with this operation; set to NULL" */
556 0, /* "Not used with this operation; set to 0" */
557 rpbuf, /* "A pointer to a buffer that
558 receives the reparse point data */
559 REPARSE_POINT_MAX_SIZE, /* "The size of the output
564 set_errno_from_GetLastError();
565 ERROR_WITH_ERRNO("Failed to get reparse data of \"%ls\"", path);
566 return -WIMLIB_ERR_READ;
568 if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
569 ERROR("Reparse data on \"%ls\" is invalid", path);
570 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
573 rpbuflen = bytesReturned;
574 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
575 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
576 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
577 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
579 /* Try doing reparse point fixup */
580 ret = win32_capture_try_rpfix(rpbuf,
582 params->capture_root_ino,
583 params->capture_root_dev,
589 *rpbuflen_ret = rpbuflen;
594 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
597 *(u64*)_size_ret += len;
598 return ERROR_SUCCESS;
602 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
608 err = OpenEncryptedFileRaw(path, 0, &file_ctx);
609 if (err != ERROR_SUCCESS) {
610 set_errno_from_win32_error(err);
611 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
612 "for raw read", path);
613 return WIMLIB_ERR_OPEN;
616 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
618 if (err != ERROR_SUCCESS) {
619 set_errno_from_win32_error(err);
620 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
622 ret = WIMLIB_ERR_READ;
626 CloseEncryptedFileRaw(file_ctx);
630 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
631 * stream); calculates its SHA1 message digest and either creates a `struct
632 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
633 * wim_lookup_table_entry' for an identical stream.
635 * @path: Path to the file (UTF-16LE).
637 * @path_num_chars: Number of 2-byte characters in @path.
639 * @inode: WIM inode to save the stream into.
641 * @unhashed_streams: List of unhashed streams that have been added to the WIM
644 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
647 * Returns 0 on success; nonzero on failure.
650 win32_capture_stream(const wchar_t *path,
651 size_t path_num_chars,
652 struct wim_inode *inode,
653 struct list_head *unhashed_streams,
654 WIN32_FIND_STREAM_DATA *dat)
656 struct wim_ads_entry *ads_entry;
657 struct wim_lookup_table_entry *lte;
659 wchar_t *stream_name, *colon;
660 size_t stream_name_nchars;
661 bool is_named_stream;
664 size_t spath_buf_nbytes;
665 const wchar_t *relpath_prefix;
666 const wchar_t *colonchar;
668 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
670 /* The stream name should be returned as :NAME:TYPE */
671 stream_name = dat->cStreamName;
672 if (*stream_name != L':')
673 goto out_invalid_stream_name;
675 colon = wcschr(stream_name, L':');
677 goto out_invalid_stream_name;
679 if (wcscmp(colon + 1, L"$DATA")) {
680 /* Not a DATA stream */
687 stream_name_nchars = colon - stream_name;
688 is_named_stream = (stream_name_nchars != 0);
690 if (is_named_stream) {
691 /* Allocate an ADS entry for the named stream. */
692 ads_entry = inode_add_ads_utf16le(inode, stream_name,
693 stream_name_nchars * sizeof(wchar_t));
695 ret = WIMLIB_ERR_NOMEM;
700 /* If zero length stream, no lookup table entry needed. */
701 if ((u64)dat->StreamSize.QuadPart == 0) {
706 /* Create a UTF-16LE string @spath that gives the filename, then a
707 * colon, then the stream name. Or, if it's an unnamed stream, just the
708 * filename. It is MALLOC()'ed so that it can be saved in the
709 * wim_lookup_table_entry if needed.
711 * As yet another special case, relative paths need to be changed to
712 * begin with an explicit "./" so that, for example, a file t:ads, where
713 * :ads is the part we added, is not interpreted as a file on the t:
715 spath_nchars = path_num_chars;
716 relpath_prefix = L"";
718 if (is_named_stream) {
719 spath_nchars += 1 + stream_name_nchars;
721 if (path_num_chars == 1 && !is_any_path_separator(path[0])) {
723 static const wchar_t _relpath_prefix[] =
724 {L'.', OS_PREFERRED_PATH_SEPARATOR, L'\0'};
725 relpath_prefix = _relpath_prefix;
729 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
730 spath = MALLOC(spath_buf_nbytes);
732 tsprintf(spath, L"%ls%ls%ls%ls",
733 relpath_prefix, path, colonchar, stream_name);
735 /* Make a new wim_lookup_table_entry */
736 lte = new_lookup_table_entry();
738 ret = WIMLIB_ERR_NOMEM;
741 lte->file_on_disk = spath;
743 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
745 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
746 ret = win32_get_encrypted_file_size(path, &encrypted_size);
749 lte->size = encrypted_size;
751 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
752 lte->size = (u64)dat->StreamSize.QuadPart;
756 if (is_named_stream) {
757 stream_id = ads_entry->stream_id;
758 ads_entry->lte = lte;
763 add_unhashed_stream(lte, inode, stream_id, unhashed_streams);
769 out_invalid_stream_name:
770 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
771 ret = WIMLIB_ERR_READ;
775 /* Load information about the streams of an open file into a WIM inode.
777 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
778 * and FindNextStream(). This is done for two reasons:
780 * - FindFirstStream() opens its own handle to the file or directory and
781 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
782 * causing access denied errors on certain files (even when running as the
784 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
785 * and later, whereas the stream support in NtQueryInformationFile() was
786 * already present in Windows XP.
789 win32_capture_streams(HANDLE *hFile_p,
791 size_t path_num_chars,
792 struct wim_inode *inode,
793 struct list_head *unhashed_streams,
798 u8 _buf[8192] _aligned_attribute(8);
801 IO_STATUS_BLOCK io_status;
803 const FILE_STREAM_INFORMATION *info;
805 DEBUG("Capturing streams from \"%ls\"", path);
808 bufsize = sizeof(_buf);
810 if (!(vol_flags & FILE_NAMED_STREAMS))
813 /* Get a buffer containing the stream information. */
814 while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(*hFile_p,
818 FileStreamInformation)))
822 case STATUS_BUFFER_OVERFLOW:
828 newbuf = MALLOC(bufsize);
830 newbuf = REALLOC(buf, bufsize);
832 ret = WIMLIB_ERR_NOMEM;
838 case STATUS_NOT_IMPLEMENTED:
839 case STATUS_NOT_SUPPORTED:
840 case STATUS_INVALID_INFO_CLASS:
843 set_errno_from_nt_status(status);
844 ERROR_WITH_ERRNO("\"%ls\": Failed to query "
845 "stream information", path);
846 ret = WIMLIB_ERR_READ;
851 if (io_status.Information == 0) {
852 /* No stream information. */
857 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
858 /* OpenEncryptedFileRaw() seems to fail with
859 * ERROR_SHARING_VIOLATION if there are any handles opened to
861 CloseHandle(*hFile_p);
862 *hFile_p = INVALID_HANDLE_VALUE;
865 /* Parse one or more stream information structures. */
866 info = (const FILE_STREAM_INFORMATION *)buf;
868 WIN32_FIND_STREAM_DATA dat;
870 if (info->StreamNameLength <= sizeof(dat.cStreamName) - 2) {
871 dat.StreamSize = info->StreamSize;
872 memcpy(dat.cStreamName, info->StreamName, info->StreamNameLength);
873 dat.cStreamName[info->StreamNameLength / 2] = L'\0';
875 /* Capture the stream. */
876 ret = win32_capture_stream(path, path_num_chars, inode,
877 unhashed_streams, &dat);
881 if (info->NextEntryOffset == 0) {
882 /* No more stream information. */
885 /* Advance to next stream information. */
886 info = (const FILE_STREAM_INFORMATION *)
887 ((const u8 *)info + info->NextEntryOffset);
893 /* The volume does not support named streams. Only capture the unnamed
895 DEBUG("Only capturing unnamed data stream");
896 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
897 FILE_ATTRIBUTE_REPARSE_POINT))
904 WIN32_FIND_STREAM_DATA dat;
906 wcscpy(dat.cStreamName, L"::$DATA");
907 dat.StreamSize.QuadPart = file_size;
908 ret = win32_capture_stream(path, path_num_chars,
909 inode, unhashed_streams, &dat);
912 /* Free buffer if allocated on heap. */
919 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
921 size_t path_num_chars,
922 struct add_image_params *params,
923 struct win32_capture_state *state,
926 struct wim_dentry *root = NULL;
927 struct wim_inode *inode = NULL;
934 HANDLE hFile = INVALID_HANDLE_VALUE;
938 if (should_exclude_path(path + params->capture_root_nchars,
939 path_num_chars - params->capture_root_nchars,
947 if (path_num_chars >= 4 &&
948 !wmemcmp(path, L"\\\\?\\", 4) &&
949 path_num_chars + 1 - 4 > MAX_PATH &&
950 state->num_long_path_warnings < MAX_CAPTURE_LONG_PATH_WARNINGS)
952 WARNING("Path \"%ls\" exceeds MAX_PATH", path);
953 if (++state->num_long_path_warnings == MAX_CAPTURE_LONG_PATH_WARNINGS)
954 WARNING("Suppressing further warnings about long paths.");
958 desiredAccess = FILE_READ_DATA | FILE_READ_ATTRIBUTES |
959 READ_CONTROL | ACCESS_SYSTEM_SECURITY;
961 hFile = win32_open_existing_file(path, desiredAccess);
962 if (hFile == INVALID_HANDLE_VALUE) {
963 err = GetLastError();
964 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD) {
965 if (desiredAccess & ACCESS_SYSTEM_SECURITY) {
966 desiredAccess &= ~ACCESS_SYSTEM_SECURITY;
969 if (desiredAccess & READ_CONTROL) {
970 desiredAccess &= ~READ_CONTROL;
974 set_errno_from_GetLastError();
975 ERROR_WITH_ERRNO("Failed to open \"%ls\" for reading", path);
976 ret = WIMLIB_ERR_OPEN;
980 BY_HANDLE_FILE_INFORMATION file_info;
981 if (!GetFileInformationByHandle(hFile, &file_info)) {
982 set_errno_from_GetLastError();
983 ERROR_WITH_ERRNO("Failed to get file information for \"%ls\"",
985 ret = WIMLIB_ERR_STAT;
989 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
990 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
991 ret = win32_get_reparse_data(hFile, path, params,
994 /* WIMLIB_ERR_* (inverted) */
997 } else if (ret & RP_FIXED) {
999 } else if (ret == RP_EXCLUDED) {
1007 /* Create a WIM dentry with an associated inode, which may be shared.
1009 * However, we need to explicitly check for directories and files with
1010 * only 1 link and refuse to hard link them. This is because Windows
1011 * has a bug where it can return duplicate File IDs for files and
1012 * directories on the FAT filesystem. */
1013 ret = inode_table_new_dentry(params->inode_table,
1014 path_basename_with_len(path, path_num_chars),
1015 ((u64)file_info.nFileIndexHigh << 32) |
1016 (u64)file_info.nFileIndexLow,
1017 file_info.dwVolumeSerialNumber,
1018 (file_info.nNumberOfLinks <= 1 ||
1019 (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1024 ret = win32_get_short_name(hFile, root);
1028 inode = root->d_inode;
1030 if (inode->i_nlink > 1) {
1031 /* Shared inode; nothing more to do */
1035 inode->i_attributes = file_info.dwFileAttributes;
1036 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1037 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1038 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1039 inode->i_resolved = 1;
1041 params->add_flags &= ~WIMLIB_ADD_FLAG_ROOT;
1043 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1044 && (vol_flags & FILE_PERSISTENT_ACLS))
1046 ret = win32_get_security_descriptor(hFile, path, inode,
1047 params->sd_set, state,
1053 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1054 (u64)file_info.nFileSizeLow;
1057 /* Capture the unnamed data stream (only should be present for regular
1058 * files) and any alternate data streams. */
1059 ret = win32_capture_streams(&hFile,
1063 params->unhashed_streams,
1069 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1070 /* Reparse point: set the reparse data (which we read already)
1072 inode->i_not_rpfixed = not_rpfixed;
1073 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1074 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1075 params->lookup_table);
1076 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1077 /* Directory (not a reparse point) --- recurse to children */
1079 if (hFile == INVALID_HANDLE_VALUE) {
1080 /* Re-open handle that was closed to read raw encrypted
1082 hFile = win32_open_existing_file(path, FILE_READ_DATA);
1083 if (hFile == INVALID_HANDLE_VALUE) {
1084 set_errno_from_GetLastError();
1085 ERROR_WITH_ERRNO("Failed to reopen \"%ls\"",
1087 ret = WIMLIB_ERR_OPEN;
1091 ret = win32_recurse_directory(hFile,
1102 path[path_num_chars] = '\0';
1104 params->progress.scan.cur_path = path;
1106 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1108 do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1110 if (hFile != INVALID_HANDLE_VALUE)
1115 free_dentry_tree(root, params->lookup_table);
1120 win32_do_capture_warnings(const wchar_t *path,
1121 const struct win32_capture_state *state,
1124 if (state->num_get_sacl_priv_notheld == 0 &&
1125 state->num_get_sd_access_denied == 0)
1128 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1129 if (state->num_get_sacl_priv_notheld != 0) {
1130 WARNING("- Could not capture SACL (System Access Control List)\n"
1131 " on %lu files or directories.",
1132 state->num_get_sacl_priv_notheld);
1134 if (state->num_get_sd_access_denied != 0) {
1135 WARNING("- Could not capture security descriptor at all\n"
1136 " on %lu files or directories.",
1137 state->num_get_sd_access_denied);
1139 WARNING("To fully capture all security descriptors, run the program\n"
1140 " with Administrator rights.");
1143 #define WINDOWS_NT_MAX_PATH 32768
1145 /* Win32 version of capturing a directory tree */
1147 win32_build_dentry_tree(struct wim_dentry **root_ret,
1148 const wchar_t *root_disk_path,
1149 struct add_image_params *params)
1154 struct win32_capture_state state;
1158 path_nchars = wcslen(root_disk_path);
1159 if (path_nchars > WINDOWS_NT_MAX_PATH)
1160 return WIMLIB_ERR_INVALID_PARAM;
1162 ret = win32_get_file_and_vol_ids(root_disk_path,
1163 ¶ms->capture_root_ino,
1164 ¶ms->capture_root_dev);
1166 ERROR_WITH_ERRNO("Can't open %ls", root_disk_path);
1170 win32_get_vol_flags(root_disk_path, &vol_flags, NULL);
1172 /* WARNING: There is no check for overflow later when this buffer is
1173 * being used! But it's as long as the maximum path length understood
1174 * by Windows NT (which is NOT the same as MAX_PATH). */
1175 path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1177 return WIMLIB_ERR_NOMEM;
1179 /* Work around defective behavior in Windows where paths longer than 260
1180 * characters are not supported by default; instead they need to be
1181 * turned into absolute paths and prefixed with "\\?\". */
1183 if (wcsncmp(root_disk_path, L"\\\\?\\", 4)) {
1184 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 3,
1187 if (dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 3) {
1188 WARNING("Can't get full path name for \"%ls\"", root_disk_path);
1189 wmemcpy(path, root_disk_path, path_nchars + 1);
1191 wmemcpy(path, L"\\\\?\\", 4);
1192 path_nchars = 4 + dret;
1195 wmemcpy(path, root_disk_path, path_nchars + 1);
1198 /* Strip trailing slashes. If we don't do this, we may create a path
1199 * with multiple consecutive backslashes, which for some reason causes
1200 * Windows to report that the file cannot be found. */
1201 while (path_nchars >= 2 &&
1202 path[path_nchars - 1] == L'\\' &&
1203 path[path_nchars - 2] != L':')
1205 path[--path_nchars] = L'\0';
1208 params->capture_root_nchars = path_nchars;
1210 memset(&state, 0, sizeof(state));
1211 ret = win32_build_dentry_tree_recursive(root_ret, path,
1212 path_nchars, params,
1216 win32_do_capture_warnings(root_disk_path, &state, params->add_flags);
1220 #endif /* __WIN32__ */