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"
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 winnt_openat(HANDLE cur_dir, const wchar_t *path, size_t path_nchars,
51 ACCESS_MASK perms, HANDLE *h_ret)
54 OBJECT_ATTRIBUTES attr;
58 name.Length = path_nchars * sizeof(wchar_t);
59 name.MaximumLength = name.Length + sizeof(wchar_t);
60 name.Buffer = (wchar_t *)path;
62 attr.Length = sizeof(attr);
63 attr.RootDirectory = cur_dir;
64 attr.ObjectName = &name;
66 attr.SecurityDescriptor = NULL;
67 attr.SecurityQualityOfService = NULL;
70 status = (*func_NtOpenFile)(h_ret, perms, &attr, &iosb,
74 FILE_OPEN_REPARSE_POINT |
75 FILE_OPEN_FOR_BACKUP_INTENT |
76 FILE_SYNCHRONOUS_IO_NONALERT);
77 if (!NT_SUCCESS(status)) {
78 if (status == STATUS_ACCESS_DENIED ||
79 status == STATUS_PRIVILEGE_NOT_HELD) {
80 if (perms & ACCESS_SYSTEM_SECURITY) {
81 perms &= ~ACCESS_SYSTEM_SECURITY;
84 if (perms & READ_CONTROL) {
85 perms &= ~READ_CONTROL;
94 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
96 consume_data_callback_t cb,
106 path = lte->file_on_disk;
107 status = winnt_openat(NULL, path, wcslen(path),
108 FILE_READ_DATA | SYNCHRONIZE, &h);
109 if (!NT_SUCCESS(status)) {
110 set_errno_from_nt_status(status);
111 ERROR_WITH_ERRNO("\"%ls\": Can't open for reading", path);
112 return WIMLIB_ERR_OPEN;
116 bytes_remaining = size;
117 while (bytes_remaining) {
118 IO_STATUS_BLOCK iosb;
121 count = min(sizeof(buf), bytes_remaining);
123 status = (*func_NtReadFile)(h, NULL, NULL, NULL,
124 &iosb, buf, count, NULL, NULL);
125 if (!NT_SUCCESS(status) || iosb.Information != count) {
126 set_errno_from_nt_status(status);
127 ERROR_WITH_ERRNO("\"%ls\": Error reading data", path);
128 ret = WIMLIB_ERR_READ;
132 bytes_remaining -= count;
133 ret = (*cb)(buf, count, cb_ctx);
141 struct win32_encrypted_read_ctx {
142 consume_data_callback_t read_prefix_cb;
143 void *read_prefix_ctx;
149 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
151 struct win32_encrypted_read_ctx *ctx = _ctx;
153 size_t bytes_to_consume = min(len, ctx->bytes_remaining);
155 if (bytes_to_consume == 0)
156 return ERROR_SUCCESS;
158 ret = (*ctx->read_prefix_cb)(data, bytes_to_consume, ctx->read_prefix_ctx);
160 ctx->wimlib_err_code = ret;
161 /* Shouldn't matter what error code is returned here, as long as
162 * it isn't ERROR_SUCCESS. */
163 return ERROR_READ_FAULT;
165 ctx->bytes_remaining -= bytes_to_consume;
166 return ERROR_SUCCESS;
170 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
172 consume_data_callback_t cb,
175 struct win32_encrypted_read_ctx export_ctx;
180 DEBUG("Reading %"PRIu64" bytes from encrypted file \"%ls\"",
181 size, lte->file_on_disk);
183 export_ctx.read_prefix_cb = cb;
184 export_ctx.read_prefix_ctx = cb_ctx;
185 export_ctx.wimlib_err_code = 0;
186 export_ctx.bytes_remaining = size;
188 err = OpenEncryptedFileRaw(lte->file_on_disk, 0, &file_ctx);
189 if (err != ERROR_SUCCESS) {
190 set_errno_from_win32_error(err);
191 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
192 "for raw read", lte->file_on_disk);
193 return WIMLIB_ERR_OPEN;
195 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
196 &export_ctx, file_ctx);
197 if (err != ERROR_SUCCESS) {
198 set_errno_from_win32_error(err);
199 ERROR_WITH_ERRNO("Failed to read encrypted file \"%ls\"",
201 ret = export_ctx.wimlib_err_code;
203 ret = WIMLIB_ERR_READ;
204 } else if (export_ctx.bytes_remaining != 0) {
205 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
206 "encryted file \"%ls\"",
207 size - export_ctx.bytes_remaining, size,
209 ret = WIMLIB_ERR_READ;
213 CloseEncryptedFileRaw(file_ctx);
217 /* Load the short name of a file into a WIM dentry.
219 * If we can't read the short filename for some reason, we just ignore the error
220 * and assume the file has no short name. This shouldn't be an issue, since the
221 * short names are essentially obsolete anyway.
224 win32_get_short_name(HANDLE hFile, struct wim_dentry *dentry)
227 /* It's not any harder to just make the NtQueryInformationFile() system
228 * call ourselves, and it saves a dumb call to FindFirstFile() which of
229 * course has to create its own handle. */
231 IO_STATUS_BLOCK io_status;
232 u8 buf[128] _aligned_attribute(8);
233 const FILE_NAME_INFORMATION *info;
235 status = (*func_NtQueryInformationFile)(hFile, &io_status, buf, sizeof(buf),
236 FileAlternateNameInformation);
237 info = (const FILE_NAME_INFORMATION*)buf;
238 if (NT_SUCCESS(status) && info->FileNameLength != 0) {
239 dentry->short_name = utf16le_dupz(info->FileName,
240 info->FileNameLength);
241 if (!dentry->short_name)
242 return WIMLIB_ERR_NOMEM;
243 dentry->short_name_nbytes = info->FileNameLength;
249 win32_get_security_descriptor(HANDLE h,
250 struct wim_inode *inode,
251 struct wim_sd_set *sd_set,
252 struct win32_capture_state *state,
255 SECURITY_INFORMATION requestedInformation;
263 requestedInformation = DACL_SECURITY_INFORMATION |
264 SACL_SECURITY_INFORMATION |
265 OWNER_SECURITY_INFORMATION |
266 GROUP_SECURITY_INFORMATION;
268 bufsize = sizeof(_buf);
271 * We need the file's security descriptor in SECURITY_DESCRIPTOR_RELATIVE
272 * format, and we currently have a handle opened with as many relevant
273 * permissions as possible. At this point, on Windows there are a number of
274 * options for reading a file's security descriptor:
276 * GetFileSecurity(): This takes in a path and returns the
277 * SECURITY_DESCRIPTOR_RELATIVE. Problem: this uses an internal handle, not
278 * ours, and the handle created internally doesn't specify
279 * FILE_FLAG_BACKUP_SEMANTICS. Therefore there can be access denied errors on
280 * some files and directories, even when running as the Administrator.
282 * GetSecurityInfo(): This takes in a handle and returns the security
283 * descriptor split into a bunch of different parts. This should work, but it's
284 * dumb because we have to put the security descriptor back together again.
286 * BackupRead(): This can read the security descriptor, but this is a
287 * difficult-to-use API, probably only works as the Administrator, and the
288 * format of the returned data is not well documented.
290 * NtQuerySecurityObject(): This is exactly what we need, as it takes in a
291 * handle and returns the security descriptor in SECURITY_DESCRIPTOR_RELATIVE
292 * format. Only problem is that it's a ntdll function and therefore not
293 * officially part of the Win32 API. Oh well.
295 while (!(NT_SUCCESS(status = (*func_NtQuerySecurityObject)(h,
296 requestedInformation,
297 (PSECURITY_DESCRIPTOR)buf,
302 case STATUS_BUFFER_TOO_SMALL:
303 wimlib_assert(buf == _buf);
304 buf = MALLOC(lenNeeded);
306 return WIMLIB_ERR_NOMEM;
309 case STATUS_PRIVILEGE_NOT_HELD:
310 case STATUS_ACCESS_DENIED:
311 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
313 set_errno_from_nt_status(status);
314 ret = WIMLIB_ERR_READ;
317 if (requestedInformation & SACL_SECURITY_INFORMATION) {
318 state->num_get_sacl_priv_notheld++;
319 requestedInformation &= ~SACL_SECURITY_INFORMATION;
322 state->num_get_sd_access_denied++;
328 inode->i_security_id = sd_set_add_sd(sd_set, buf, lenNeeded);
329 if (inode->i_security_id < 0)
330 ret = WIMLIB_ERR_NOMEM;
340 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
343 size_t full_path_nchars,
344 const wchar_t *filename,
345 size_t filename_nchars,
346 struct add_image_params *params,
347 struct win32_capture_state *state,
350 /* Reads the directory entries of directory and recursively calls
351 * win32_build_dentry_tree() on them. */
353 win32_recurse_directory(HANDLE h,
355 size_t full_path_nchars,
356 struct wim_dentry *root,
357 struct add_image_params *params,
358 struct win32_capture_state *state,
363 /* Using NtQueryDirectoryFile() we can re-use the same open handle,
364 * which we opened with FILE_FLAG_BACKUP_SEMANTICS. */
367 IO_STATUS_BLOCK io_status;
368 const size_t bufsize = 8192;
371 buf = MALLOC(bufsize);
373 return WIMLIB_ERR_NOMEM;
375 while (NT_SUCCESS(status = (*func_NtQueryDirectoryFile)(h, NULL, NULL, NULL,
376 &io_status, buf, bufsize,
377 FileNamesInformation,
378 FALSE, NULL, FALSE)))
380 const FILE_NAMES_INFORMATION *info = buf;
382 if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
383 !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
384 info->FileName[1] == L'.'))
387 struct wim_dentry *child;
389 p = full_path + full_path_nchars;
391 p = wmempcpy(p, info->FileName,
392 info->FileNameLength / 2);
395 ret = win32_build_dentry_tree_recursive(
400 full_path + full_path_nchars + 1,
401 info->FileNameLength / 2,
406 full_path[full_path_nchars] = L'\0';
411 dentry_add_child(root, child);
413 if (info->NextEntryOffset == 0)
415 info = (const FILE_NAMES_INFORMATION *)
416 ((const u8 *)info + info->NextEntryOffset);
420 if (status != STATUS_NO_MORE_FILES) {
421 set_errno_from_nt_status(status);
422 ERROR_WITH_ERRNO("\"%ls\": Can't read directory", full_path);
423 ret = WIMLIB_ERR_READ;
430 /* Reparse point fixup status code */
432 /* Reparse point corresponded to an absolute symbolic link or junction
433 * point that pointed outside the directory tree being captured, and
434 * therefore was excluded. */
437 /* Reparse point was not fixed as it was either a relative symbolic
438 * link, a mount point, or something else we could not understand. */
441 /* Reparse point corresponded to an absolute symbolic link or junction
442 * point that pointed inside the directory tree being captured, where
443 * the target was specified by a "full" \??\ prefixed path, and
444 * therefore was fixed to be relative to the root of the directory tree
446 RP_FIXED_FULLPATH = 0x2,
448 /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
449 * have the \??\ prefix. It may have begun with a drive letter though.
451 RP_FIXED_ABSPATH = 0x4,
453 /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
454 RP_FIXED = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
457 /* Given the "substitute name" target of a Windows reparse point, try doing a
458 * fixup where we change it to be absolute relative to the root of the directory
459 * tree being captured.
461 * Note that this is only executed when WIMLIB_ADD_FLAG_RPFIX has been
464 * @capture_root_ino and @capture_root_dev indicate the inode number and device
465 * of the root of the directory tree being captured. They are meant to identify
466 * this directory (as an alternative to its actual path, which could potentially
467 * be reached via multiple destinations due to other symbolic links). This may
468 * not work properly on FAT, which doesn't seem to supply proper inode numbers
469 * or file IDs. However, FAT doesn't support reparse points so this function
470 * wouldn't even be called anyway.
472 static enum rp_status
473 win32_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
474 u64 capture_root_ino, u64 capture_root_dev,
477 u16 target_nchars = *target_nbytes_p / 2;
478 size_t stripped_chars;
479 wchar_t *orig_target;
482 ret = parse_substitute_name(target, *target_nbytes_p, rptag);
485 stripped_chars = ret;
488 target[target_nchars] = L'\0';
489 orig_target = target;
490 target = capture_fixup_absolute_symlink(target + stripped_chars,
491 capture_root_ino, capture_root_dev);
494 target_nchars = wcslen(target);
495 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
496 *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
497 DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
499 return RP_FIXED_FULLPATH;
501 return RP_FIXED_ABSPATH;
504 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
507 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
508 u64 capture_root_ino, u64 capture_root_dev,
509 const wchar_t *path, struct add_image_params *params)
511 struct reparse_data rpdata;
513 enum rp_status rp_status;
515 ret = parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata);
519 rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
520 &rpdata.substitute_name_nbytes,
523 le32_to_cpu(*(le32*)rpbuf));
524 if (rp_status & RP_FIXED) {
525 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
526 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
527 wmemcpy(substitute_name_copy, rpdata.substitute_name,
528 rpdata.substitute_name_nbytes / 2);
529 rpdata.substitute_name = substitute_name_copy;
530 rpdata.print_name = substitute_name_copy;
531 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
532 if (rp_status == RP_FIXED_FULLPATH) {
533 /* "full path", meaning \??\ prefixed. We should not
534 * include this prefix in the print name, as it is
535 * apparently meant for the filesystem driver only. */
536 rpdata.print_name += 4;
537 rpdata.print_name_nbytes -= 8;
539 ret = make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
545 if (rp_status == RP_EXCLUDED) {
546 /* Ignoring absolute symbolic link or junction point
547 * that points out of the tree to be captured. */
548 size_t print_name_nchars = rpdata.print_name_nbytes / 2;
549 wchar_t print_name0[print_name_nchars + 1];
550 print_name0[print_name_nchars] = L'\0';
551 wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
553 params->progress.scan.cur_path = path;
554 params->progress.scan.symlink_target = print_name0;
555 do_capture_progress(params,
556 WIMLIB_SCAN_DENTRY_EXCLUDED_SYMLINK,
565 * Loads the reparse point data from a reparse point into memory, optionally
566 * fixing the targets of absolute symbolic links and junction points to be
567 * relative to the root of capture.
569 * @h: Open handle to the reparse point.
570 * @path: Path to the reparse point file.
571 * @params: Additional parameters, including whether to do reparse point fixups
573 * @rpbuf: Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
574 * the reparse point buffer will be loaded.
575 * @rpbuflen_ret: On success, the length of the reparse point buffer in bytes
576 * is written to this location.
579 * On success, returns an `enum rp_status' value that indicates if and/or
580 * how the reparse point fixup was done.
582 * On failure, returns a negative value that is a negated WIMLIB_ERR_*
586 win32_get_reparse_data(HANDLE h, const wchar_t *path,
587 struct add_image_params *params,
588 u8 *rpbuf, u16 *rpbuflen_ret)
595 if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
596 NULL, /* "Not used with this operation; set to NULL" */
597 0, /* "Not used with this operation; set to 0" */
598 rpbuf, /* "A pointer to a buffer that
599 receives the reparse point data */
600 REPARSE_POINT_MAX_SIZE, /* "The size of the output
605 set_errno_from_GetLastError();
606 return -WIMLIB_ERR_READ;
609 if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
611 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
614 rpbuflen = bytesReturned;
615 reparse_tag = le32_to_cpu(*(le32*)rpbuf);
616 if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
617 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
618 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
620 /* Try doing reparse point fixup */
621 ret = win32_capture_try_rpfix(rpbuf,
623 params->capture_root_ino,
624 params->capture_root_dev,
630 *rpbuflen_ret = rpbuflen;
635 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
638 *(u64*)_size_ret += len;
639 return ERROR_SUCCESS;
643 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
649 err = OpenEncryptedFileRaw(path, 0, &file_ctx);
650 if (err != ERROR_SUCCESS) {
651 set_errno_from_win32_error(err);
652 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
653 "for raw read", path);
654 return WIMLIB_ERR_OPEN;
657 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
659 if (err != ERROR_SUCCESS) {
660 set_errno_from_win32_error(err);
661 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
663 ret = WIMLIB_ERR_READ;
667 CloseEncryptedFileRaw(file_ctx);
672 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
673 const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
675 const wchar_t *sep, *type, *end;
677 /* The stream name should be returned as :NAME:TYPE */
678 if (raw_stream_name_nchars < 1)
680 if (raw_stream_name[0] != L':')
684 raw_stream_name_nchars--;
686 end = raw_stream_name + raw_stream_name_nchars;
688 sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
696 if (wmemcmp(type, L"$DATA", 5))
699 *stream_name_ret = raw_stream_name;
700 *stream_name_nchars_ret = sep - raw_stream_name;
705 build_stream_path(const wchar_t *path, size_t path_nchars,
706 const wchar_t *stream_name, size_t stream_name_nchars)
708 size_t stream_path_nchars;
709 wchar_t *stream_path;
712 stream_path_nchars = path_nchars;
713 if (stream_name_nchars)
714 stream_path_nchars += 1 + stream_name_nchars;
716 stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
718 p = wmempcpy(stream_path, path, path_nchars);
719 if (stream_name_nchars) {
721 p = wmempcpy(p, stream_name, stream_name_nchars);
729 win32_capture_stream(const wchar_t *path, size_t path_nchars,
730 const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
732 struct wim_inode *inode,
733 struct list_head *unhashed_streams)
735 const wchar_t *stream_name;
736 size_t stream_name_nchars;
737 struct wim_ads_entry *ads_entry;
738 wchar_t *stream_path;
739 struct wim_lookup_table_entry *lte;
742 /* Given the raw stream name (which is something like
743 * L":streamname:$DATA", extract just the stream name part. */
744 if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
745 &stream_name, &stream_name_nchars))
748 /* If this is a named stream, allocate an ADS entry. */
749 if (stream_name_nchars) {
750 ads_entry = inode_add_ads_utf16le(inode, stream_name,
751 stream_name_nchars * sizeof(wchar_t));
753 return WIMLIB_ERR_NOMEM;
758 /* If the stream is empty, no lookup table entry is needed. */
759 if (stream_size == 0)
762 /* Build the path to the stream. For unnamed streams, this is simply
763 * the path to the file. For named streams, this is the path to the
764 * file, followed by a colon, followed by the stream name. */
765 stream_path = build_stream_path(path, path_nchars,
766 stream_name, stream_name_nchars);
768 return WIMLIB_ERR_NOMEM;
770 /* Set up the lookup table entry for the stream. */
771 lte = new_lookup_table_entry();
774 return WIMLIB_ERR_NOMEM;
776 lte->file_on_disk = stream_path;
777 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
778 lte->size = stream_size;
779 if ((inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) && !ads_entry) {
780 /* Special case for encrypted file. */
782 /* OpenEncryptedFileRaw() expects Win32 name, not NT name. */
783 lte->file_on_disk[1] = L'\\';
784 wimlib_assert(!wmemcmp(lte->file_on_disk, L"\\\\?\\", 4));
789 ret = win32_get_encrypted_file_size(lte->file_on_disk,
792 free_lookup_table_entry(lte);
795 lte->size = encrypted_size;
796 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
800 stream_id = ads_entry->stream_id;
801 ads_entry->lte = lte;
806 add_unhashed_stream(lte, inode, stream_id, unhashed_streams);
810 /* Load information about the streams of an open file into a WIM inode.
812 * We use the NtQueryInformationFile() system call instead of FindFirstStream()
813 * and FindNextStream(). This is done for two reasons:
815 * - FindFirstStream() opens its own handle to the file or directory and
816 * apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
817 * causing access denied errors on certain files (even when running as the
819 * - FindFirstStream() and FindNextStream() is only available on Windows Vista
820 * and later, whereas the stream support in NtQueryInformationFile() was
821 * already present in Windows XP.
824 win32_capture_streams(HANDLE *hFile_p,
827 struct wim_inode *inode,
828 struct list_head *unhashed_streams,
833 u8 _buf[1024] _aligned_attribute(8);
836 IO_STATUS_BLOCK io_status;
838 const FILE_STREAM_INFORMATION *info;
840 DEBUG("Capturing streams from \"%ls\"", path);
843 bufsize = sizeof(_buf);
845 if (!(vol_flags & FILE_NAMED_STREAMS))
848 /* Get a buffer containing the stream information. */
849 while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(*hFile_p,
853 FileStreamInformation)))
857 case STATUS_BUFFER_OVERFLOW:
863 newbuf = MALLOC(bufsize);
865 newbuf = REALLOC(buf, bufsize);
867 ret = WIMLIB_ERR_NOMEM;
873 case STATUS_NOT_IMPLEMENTED:
874 case STATUS_NOT_SUPPORTED:
875 case STATUS_INVALID_INFO_CLASS:
878 set_errno_from_nt_status(status);
879 ERROR_WITH_ERRNO("\"%ls\": Failed to query "
880 "stream information", path);
881 ret = WIMLIB_ERR_READ;
886 if (io_status.Information == 0) {
887 /* No stream information. */
892 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
893 /* OpenEncryptedFileRaw() seems to fail with
894 * ERROR_SHARING_VIOLATION if there are any handles opened to
896 (*func_NtClose)(*hFile_p);
897 *hFile_p = INVALID_HANDLE_VALUE;
900 /* Parse one or more stream information structures. */
901 info = (const FILE_STREAM_INFORMATION *)buf;
903 /* Capture the stream. */
904 ret = win32_capture_stream(path, path_nchars,
906 info->StreamNameLength / 2,
907 info->StreamSize.QuadPart,
908 inode, unhashed_streams);
912 if (info->NextEntryOffset == 0) {
913 /* No more stream information. */
916 /* Advance to next stream information. */
917 info = (const FILE_STREAM_INFORMATION *)
918 ((const u8 *)info + info->NextEntryOffset);
924 /* The volume does not support named streams. Only capture the unnamed
926 DEBUG("Only capturing unnamed data stream");
927 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
928 FILE_ATTRIBUTE_REPARSE_POINT))
934 ret = win32_capture_stream(path, path_nchars,
935 L"::$DATA", 7, file_size,
936 inode, unhashed_streams);
938 /* Free buffer if allocated on heap. */
945 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
948 size_t full_path_nchars,
949 const wchar_t *filename,
950 size_t filename_nchars,
951 struct add_image_params *params,
952 struct win32_capture_state *state,
955 struct wim_dentry *root = NULL;
956 struct wim_inode *inode = NULL;
957 HANDLE h = INVALID_HANDLE_VALUE;
960 FILE_ALL_INFORMATION file_info;
965 if (should_exclude_path(full_path + params->capture_root_nchars,
966 full_path_nchars - params->capture_root_nchars,
973 status = winnt_openat(cur_dir,
974 (cur_dir ? filename : full_path),
975 (cur_dir ? filename_nchars : full_path_nchars),
977 FILE_READ_ATTRIBUTES |
979 ACCESS_SYSTEM_SECURITY |
982 if (!NT_SUCCESS(status)) {
983 set_errno_from_nt_status(status);
984 ERROR_WITH_ERRNO("\"%ls\": Can't open file", full_path);
985 ret = WIMLIB_ERR_OPEN;
990 IO_STATUS_BLOCK iosb;
992 status = (*func_NtQueryInformationFile)(h, &iosb,
993 &file_info, sizeof(file_info),
995 if (!NT_SUCCESS(status) && status != STATUS_BUFFER_OVERFLOW) {
996 set_errno_from_GetLastError();
997 ERROR_WITH_ERRNO("\"%ls\": Can't get file information", full_path);
998 ret = WIMLIB_ERR_STAT;
1004 /* Root directory; get volume information. */
1005 FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1006 FILE_FS_VOLUME_INFORMATION vol_info;
1007 IO_STATUS_BLOCK iosb;
1009 /* Get volume flags */
1010 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1011 &attr_info, sizeof(attr_info),
1012 FileFsAttributeInformation);
1013 if ((NT_SUCCESS(status) || (status == STATUS_BUFFER_OVERFLOW)) &&
1014 iosb.Information >= offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1015 FileSystemAttributes) +
1016 sizeof(attr_info.FileSystemAttributes))
1018 vol_flags = attr_info.FileSystemAttributes;
1020 set_errno_from_nt_status(status);
1021 WARNING_WITH_ERRNO("\"%ls\": Can't get volume attributes",
1026 /* Set inode number of root directory */
1027 params->capture_root_ino = file_info.InternalInformation.IndexNumber.QuadPart;
1030 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1031 &vol_info, sizeof(vol_info),
1032 FileFsVolumeInformation);
1033 if ((NT_SUCCESS(status) || (status == STATUS_BUFFER_OVERFLOW)) &&
1034 iosb.Information >= offsetof(FILE_FS_VOLUME_INFORMATION,
1035 VolumeSerialNumber) +
1036 sizeof(vol_info.VolumeSerialNumber))
1038 params->capture_root_dev = vol_info.VolumeSerialNumber;
1040 set_errno_from_nt_status(status);
1041 WARNING_WITH_ERRNO("\"%ls\": Can't get volume ID",
1043 params->capture_root_dev = 0;
1047 if (file_info.BasicInformation.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1048 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1049 ret = win32_get_reparse_data(h, full_path,
1050 params, rpbuf, &rpbuflen);
1052 /* WIMLIB_ERR_* (inverted) */
1054 ERROR_WITH_ERRNO("\"%ls\": Can't get reparse data",
1057 } else if (ret & RP_FIXED) {
1059 } else if (ret == RP_EXCLUDED) {
1067 /* Create a WIM dentry with an associated inode, which may be shared.
1069 * However, we need to explicitly check for directories and files with
1070 * only 1 link and refuse to hard link them. This is because Windows
1071 * has a bug where it can return duplicate File IDs for files and
1072 * directories on the FAT filesystem. */
1073 ret = inode_table_new_dentry(params->inode_table,
1075 file_info.InternalInformation.IndexNumber.QuadPart,
1076 0, /* We don't follow mount points, so we
1077 currently don't need to get the
1078 volume ID / device number. */
1079 (file_info.StandardInformation.NumberOfLinks <= 1 ||
1080 (file_info.BasicInformation.FileAttributes &
1081 FILE_ATTRIBUTE_DIRECTORY)),
1086 ret = win32_get_short_name(h, root);
1088 ERROR_WITH_ERRNO("\"%ls\": Can't get short name", full_path);
1092 inode = root->d_inode;
1094 if (inode->i_nlink > 1) {
1095 /* Shared inode; nothing more to do */
1100 inode->i_attributes = file_info.BasicInformation.FileAttributes;
1101 inode->i_creation_time = file_info.BasicInformation.CreationTime.QuadPart;
1102 inode->i_last_write_time = file_info.BasicInformation.LastWriteTime.QuadPart;
1103 inode->i_last_access_time = file_info.BasicInformation.LastAccessTime.QuadPart;
1104 inode->i_resolved = 1;
1106 params->add_flags &= ~WIMLIB_ADD_FLAG_ROOT;
1108 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1109 && (vol_flags & FILE_PERSISTENT_ACLS))
1111 ret = win32_get_security_descriptor(h, inode,
1112 params->sd_set, state,
1115 ERROR_WITH_ERRNO("\"%ls\": Can't "
1116 "read security descriptor", full_path);
1121 /* Capture the unnamed data stream (only should be present for regular
1122 * files) and any alternate data streams. */
1123 ret = win32_capture_streams(&h,
1127 params->unhashed_streams,
1128 file_info.StandardInformation.EndOfFile.QuadPart,
1133 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1134 /* Reparse point: set the reparse data (which we read already)
1136 inode->i_not_rpfixed = not_rpfixed;
1137 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1138 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1139 params->lookup_table);
1140 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1141 /* Directory (not a reparse point) --- recurse to children */
1143 if (h == INVALID_HANDLE_VALUE) {
1144 /* Re-open handle that was closed to read raw encrypted
1146 status = winnt_openat(cur_dir,
1148 filename : full_path),
1150 filename_nchars : full_path_nchars),
1151 FILE_LIST_DIRECTORY | SYNCHRONIZE,
1153 if (!NT_SUCCESS(status)) {
1154 set_errno_from_nt_status(status);
1155 ERROR_WITH_ERRNO("\"%ls\": Can't open file",
1157 ret = WIMLIB_ERR_OPEN;
1161 ret = win32_recurse_directory(h,
1173 params->progress.scan.cur_path = full_path;
1175 do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1177 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1179 if (h != INVALID_HANDLE_VALUE)
1184 free_dentry_tree(root, params->lookup_table);
1189 win32_do_capture_warnings(const wchar_t *path,
1190 const struct win32_capture_state *state,
1193 if (state->num_get_sacl_priv_notheld == 0 &&
1194 state->num_get_sd_access_denied == 0)
1197 WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1198 if (state->num_get_sacl_priv_notheld != 0) {
1199 WARNING("- Could not capture SACL (System Access Control List)\n"
1200 " on %lu files or directories.",
1201 state->num_get_sacl_priv_notheld);
1203 if (state->num_get_sd_access_denied != 0) {
1204 WARNING("- Could not capture security descriptor at all\n"
1205 " on %lu files or directories.",
1206 state->num_get_sd_access_denied);
1208 WARNING("To fully capture all security descriptors, run the program\n"
1209 " with Administrator rights.");
1212 #define WINDOWS_NT_MAX_PATH 32768
1214 /* Win32 version of capturing a directory tree */
1216 win32_build_dentry_tree(struct wim_dentry **root_ret,
1217 const wchar_t *root_disk_path,
1218 struct add_image_params *params)
1224 struct win32_capture_state state;
1226 /* WARNING: There is no check for overflow later when this buffer is
1227 * being used! But it's as long as the maximum path length understood
1228 * by Windows NT (which is NOT the same as MAX_PATH). */
1229 path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1231 return WIMLIB_ERR_NOMEM;
1233 /* Translate into full path. */
1234 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 3,
1237 if (dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 3) {
1238 ERROR("Can't get full path name for \"%ls\"", root_disk_path);
1239 return WIMLIB_ERR_UNSUPPORTED;
1242 /* Add \??\ prefix to form the NT namespace path. */
1243 wmemcpy(path, L"\\??\\", 4);
1244 path_nchars = dret + 4;
1246 /* Strip trailing slashes. If we don't do this, we may create a path
1247 * with multiple consecutive backslashes, which for some reason causes
1248 * Windows to report that the file cannot be found. */
1249 while (path_nchars >= 2 &&
1250 path[path_nchars - 1] == L'\\' &&
1251 path[path_nchars - 2] != L':')
1253 path[--path_nchars] = L'\0';
1256 params->capture_root_nchars = path_nchars;
1258 memset(&state, 0, sizeof(state));
1259 ret = win32_build_dentry_tree_recursive(root_ret, NULL,
1260 path, path_nchars, L"", 0,
1264 win32_do_capture_warnings(root_disk_path, &state, params->add_flags);
1268 #endif /* __WIN32__ */