2 * win32_capture.c - Windows-specific code for capturing files into a WIM image.
6 * Copyright (C) 2013 Eric Biggers
8 * This file is part of wimlib, a library for working with WIM files.
10 * wimlib is free software; you can redistribute it and/or modify it under the
11 * terms of the GNU General Public License as published by the Free
12 * Software Foundation; either version 3 of the License, or (at your option)
15 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 * A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with wimlib; if not, see http://www.gnu.org/licenses/.
30 #include "wimlib/win32_common.h"
32 #include "wimlib/capture.h"
33 #include "wimlib/endianness.h"
34 #include "wimlib/error.h"
35 #include "wimlib/lookup_table.h"
36 #include "wimlib/paths.h"
37 #include "wimlib/reparse.h"
39 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
40 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
41 struct win32_capture_state {
42 unsigned long num_get_sd_access_denied;
43 unsigned long num_get_sacl_priv_notheld;
47 static const wchar_t *capture_access_denied_msg =
48 L" If you are not running this program as the administrator, you may\n"
49 " need to do so, so that all data and metadata can be backed up.\n"
50 " Otherwise, there may be no way to access the desired data or\n"
51 " metadata without taking ownership of the file or directory.\n"
55 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
57 consume_data_callback_t cb,
66 HANDLE hFile = win32_open_file_data_only(lte->file_on_disk);
67 if (hFile == INVALID_HANDLE_VALUE) {
69 ERROR("Failed to open \"%ls\"", lte->file_on_disk);
71 return WIMLIB_ERR_OPEN;
75 out_buf = alloca(WIM_CHUNK_SIZE);
79 bytes_remaining = size;
80 while (bytes_remaining) {
81 DWORD bytesToRead, bytesRead;
83 bytesToRead = min(WIM_CHUNK_SIZE, bytes_remaining);
84 if (!ReadFile(hFile, out_buf, bytesToRead, &bytesRead, NULL) ||
85 bytesRead != bytesToRead)
88 ERROR("Failed to read data from \"%ls\"", lte->file_on_disk);
90 ret = WIMLIB_ERR_READ;
93 bytes_remaining -= bytesRead;
95 ret = (*cb)(out_buf, bytesRead, ctx_or_buf);
106 struct win32_encrypted_read_ctx {
107 consume_data_callback_t read_prefix_cb;
108 void *read_prefix_ctx_or_buf;
116 win32_encrypted_export_cb(unsigned char *_data, void *_ctx, unsigned long len)
118 const void *data = _data;
119 struct win32_encrypted_read_ctx *ctx = _ctx;
122 DEBUG("len = %lu", len);
123 if (ctx->read_prefix_cb) {
124 /* The length of the buffer passed to the ReadEncryptedFileRaw()
125 * export callback is undocumented, so we assume it may be of
127 size_t bytes_to_buffer = min(ctx->bytes_remaining - ctx->buf_filled,
129 while (bytes_to_buffer) {
130 size_t bytes_to_copy_to_buf =
131 min(bytes_to_buffer, WIM_CHUNK_SIZE - ctx->buf_filled);
133 memcpy(ctx->buf + ctx->buf_filled, data,
134 bytes_to_copy_to_buf);
135 ctx->buf_filled += bytes_to_copy_to_buf;
136 data += bytes_to_copy_to_buf;
137 bytes_to_buffer -= bytes_to_copy_to_buf;
139 if (ctx->buf_filled == WIM_CHUNK_SIZE ||
140 ctx->buf_filled == ctx->bytes_remaining)
142 ret = (*ctx->read_prefix_cb)(ctx->buf,
144 ctx->read_prefix_ctx_or_buf);
146 ctx->wimlib_err_code = ret;
147 /* Shouldn't matter what error code is returned
148 * here, as long as it isn't ERROR_SUCCESS. */
149 return ERROR_READ_FAULT;
151 ctx->bytes_remaining -= ctx->buf_filled;
156 size_t len_to_copy = min(len, ctx->bytes_remaining);
157 memcpy(ctx->read_prefix_ctx_or_buf, data, len_to_copy);
158 ctx->bytes_remaining -= len_to_copy;
159 ctx->read_prefix_ctx_or_buf += len_to_copy;
161 return ERROR_SUCCESS;
165 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
167 consume_data_callback_t cb,
171 struct win32_encrypted_read_ctx export_ctx;
176 DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
177 size, lte->file_on_disk);
179 export_ctx.read_prefix_cb = cb;
180 export_ctx.read_prefix_ctx_or_buf = ctx_or_buf;
181 export_ctx.wimlib_err_code = 0;
183 export_ctx.buf = MALLOC(WIM_CHUNK_SIZE);
185 return WIMLIB_ERR_NOMEM;
187 export_ctx.buf = NULL;
189 export_ctx.buf_filled = 0;
190 export_ctx.bytes_remaining = size;
192 err = OpenEncryptedFileRawW(lte->file_on_disk, 0, &file_ctx);
193 if (err != ERROR_SUCCESS) {
194 ERROR("Failed to open encrypted file \"%ls\" for raw read",
197 ret = WIMLIB_ERR_OPEN;
200 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
201 &export_ctx, file_ctx);
202 if (err != ERROR_SUCCESS) {
203 ERROR("Failed to read encrypted file \"%ls\"",
206 ret = export_ctx.wimlib_err_code;
208 ret = WIMLIB_ERR_READ;
209 } else if (export_ctx.bytes_remaining != 0) {
210 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
211 "encryted file \"%ls\"",
212 size - export_ctx.bytes_remaining, size,
214 ret = WIMLIB_ERR_READ;
218 CloseEncryptedFileRaw(file_ctx);
220 FREE(export_ctx.buf);
226 FILETIME_to_u64(const FILETIME *ft)
228 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
232 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
234 WIN32_FIND_DATAW dat;
238 /* If we can't read the short filename for some reason, we just ignore
239 * the error and assume the file has no short name. I don't think this
240 * should be an issue, since the short names are essentially obsolete
242 hFind = FindFirstFileW(path, &dat);
243 if (hFind != INVALID_HANDLE_VALUE) {
244 if (dat.cAlternateFileName[0] != L'\0') {
245 DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
246 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
248 size_t n = short_name_nbytes + sizeof(wchar_t);
249 dentry->short_name = MALLOC(n);
250 if (dentry->short_name) {
251 memcpy(dentry->short_name, dat.cAlternateFileName, n);
252 dentry->short_name_nbytes = short_name_nbytes;
254 ret = WIMLIB_ERR_NOMEM;
263 win32_get_security_descriptor(struct wim_dentry *dentry,
264 struct wim_sd_set *sd_set,
266 struct win32_capture_state *state,
269 SECURITY_INFORMATION requestedInformation;
275 requestedInformation = DACL_SECURITY_INFORMATION |
276 SACL_SECURITY_INFORMATION |
277 OWNER_SECURITY_INFORMATION |
278 GROUP_SECURITY_INFORMATION;
280 /* Request length of security descriptor */
281 status = GetFileSecurityW(path, requestedInformation,
282 NULL, 0, &lenNeeded);
283 err = GetLastError();
284 if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
285 DWORD len = lenNeeded;
287 if (GetFileSecurityW(path, requestedInformation,
288 (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
290 int security_id = sd_set_add_sd(sd_set, buf, len);
292 return WIMLIB_ERR_NOMEM;
294 dentry->d_inode->i_security_id = security_id;
298 err = GetLastError();
302 if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS)
306 case ERROR_PRIVILEGE_NOT_HELD:
307 if (requestedInformation & SACL_SECURITY_INFORMATION) {
308 n = state->num_get_sacl_priv_notheld++;
309 requestedInformation &= ~SACL_SECURITY_INFORMATION;
310 if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
312 "We don't have enough privileges to read the full security\n"
313 " descriptor of \"%ls\"!\n"
314 " Re-trying with SACL omitted.\n", path);
315 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
317 "Suppressing further privileges not held error messages when reading\n"
318 " security descriptors.");
323 case ERROR_ACCESS_DENIED:
324 n = state->num_get_sd_access_denied++;
325 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
326 WARNING("Failed to read security descriptor of \"%ls\": "
327 "Access denied!\n%ls", path, capture_access_denied_msg);
328 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
329 WARNING("Suppressing further access denied errors messages i"
330 "when reading security descriptors");
335 ERROR("Failed to read security descriptor of \"%ls\"", path);
337 return WIMLIB_ERR_READ;
342 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
344 size_t path_num_chars,
345 struct add_image_params *params,
346 struct win32_capture_state *state,
349 /* Reads the directory entries of directory using a Win32 API and recursively
350 * calls win32_build_dentry_tree() on them. */
352 win32_recurse_directory(struct wim_dentry *root,
354 size_t dir_path_num_chars,
355 struct add_image_params *params,
356 struct win32_capture_state *state,
359 WIN32_FIND_DATAW dat;
364 DEBUG("Recurse to directory \"%ls\"", dir_path);
366 /* Begin reading the directory by calling FindFirstFileW. Unlike UNIX
367 * opendir(), FindFirstFileW has file globbing built into it. But this
368 * isn't what we actually want, so just add a dummy glob to get all
370 dir_path[dir_path_num_chars] = L'/';
371 dir_path[dir_path_num_chars + 1] = L'*';
372 dir_path[dir_path_num_chars + 2] = L'\0';
373 hFind = FindFirstFileW(dir_path, &dat);
374 dir_path[dir_path_num_chars] = L'\0';
376 if (hFind == INVALID_HANDLE_VALUE) {
377 err = GetLastError();
378 if (err == ERROR_FILE_NOT_FOUND) {
381 ERROR("Failed to read directory \"%ls\"", dir_path);
383 return WIMLIB_ERR_READ;
388 /* Skip . and .. entries */
389 if (dat.cFileName[0] == L'.' &&
390 (dat.cFileName[1] == L'\0' ||
391 (dat.cFileName[1] == L'.' &&
392 dat.cFileName[2] == L'\0')))
394 size_t filename_len = wcslen(dat.cFileName);
396 dir_path[dir_path_num_chars] = L'/';
397 wmemcpy(dir_path + dir_path_num_chars + 1,
401 struct wim_dentry *child;
402 size_t path_len = dir_path_num_chars + 1 + filename_len;
403 ret = win32_build_dentry_tree_recursive(&child,
409 dir_path[dir_path_num_chars] = L'\0';
413 dentry_add_child(root, child);
414 } while (FindNextFileW(hFind, &dat));
415 err = GetLastError();
416 if (err != ERROR_NO_MORE_FILES) {
417 ERROR("Failed to read directory \"%ls\"", dir_path);
420 ret = WIMLIB_ERR_READ;
427 /* Reparse point fixup status code */
429 /* Reparse point corresponded to an absolute symbolic link or junction
430 * point that pointed outside the directory tree being captured, and
431 * therefore was excluded. */
434 /* Reparse point was not fixed as it was either a relative symbolic
435 * link, a mount point, or something else we could not understand. */
438 /* Reparse point corresponded to an absolute symbolic link or junction
439 * point that pointed inside the directory tree being captured, where
440 * the target was specified by a "full" \??\ prefixed path, and
441 * therefore was fixed to be relative to the root of the directory tree
443 RP_FIXED_FULLPATH = 0x2,
445 /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
446 * have the \??\ prefix. It may have begun with a drive letter though.
448 RP_FIXED_ABSPATH = 0x4,
450 /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
451 RP_FIXED = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
454 /* Given the "substitute name" target of a Windows reparse point, try doing a
455 * fixup where we change it to be absolute relative to the root of the directory
456 * tree being captured.
458 * Note that this is only executed when WIMLIB_ADD_FLAG_RPFIX has been
461 * @capture_root_ino and @capture_root_dev indicate the inode number and device
462 * of the root of the directory tree being captured. They are meant to identify
463 * this directory (as an alternative to its actual path, which could potentially
464 * be reached via multiple destinations due to other symbolic links). This may
465 * not work properly on FAT, which doesn't seem to supply proper inode numbers
466 * or file IDs. However, FAT doesn't support reparse points so this function
467 * wouldn't even be called anyway.
469 static enum rp_status
470 win32_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
471 u64 capture_root_ino, u64 capture_root_dev,
474 u16 target_nchars = *target_nbytes_p / 2;
475 size_t stripped_chars;
476 wchar_t *orig_target;
479 ret = parse_substitute_name(target, *target_nbytes_p, rptag);
482 stripped_chars = ret;
485 target[target_nchars] = L'\0';
486 orig_target = target;
487 target = capture_fixup_absolute_symlink(target + stripped_chars,
488 capture_root_ino, capture_root_dev);
491 target_nchars = wcslen(target);
492 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
493 *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
494 DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
496 return RP_FIXED_FULLPATH;
498 return RP_FIXED_ABSPATH;
501 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
504 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
505 u64 capture_root_ino, u64 capture_root_dev,
508 struct reparse_data rpdata;
511 enum rp_status rp_status;
513 rpbuflen = *rpbuflen_p;
514 ret = parse_reparse_data(rpbuf, rpbuflen, &rpdata);
518 rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
519 &rpdata.substitute_name_nbytes,
522 le32_to_cpu(*(le32*)rpbuf));
523 if (rp_status & RP_FIXED) {
524 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
525 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
526 wmemcpy(substitute_name_copy, rpdata.substitute_name,
527 rpdata.substitute_name_nbytes / 2);
528 rpdata.substitute_name = substitute_name_copy;
529 rpdata.print_name = substitute_name_copy;
530 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
531 if (rp_status == RP_FIXED_FULLPATH) {
532 /* "full path", meaning \??\ prefixed. We should not
533 * include this prefix in the print name, as it is
534 * apparently meant for the filesystem driver only. */
535 rpdata.print_name += 4;
536 rpdata.print_name_nbytes -= 8;
538 ret = make_reparse_buffer(&rpdata, rpbuf);
544 if (rp_status == RP_EXCLUDED) {
545 size_t print_name_nchars = rpdata.print_name_nbytes / 2;
546 wchar_t print_name0[print_name_nchars + 1];
547 print_name0[print_name_nchars] = L'\0';
548 wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
549 WARNING("Ignoring %ls pointing out of capture directory:\n"
550 " \"%ls\" -> \"%ls\"\n"
551 " (Use --norpfix to capture all symbolic links "
552 "and junction points as-is)",
553 (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK) ?
554 L"absolute symbolic link" : L"junction point",
563 * Loads the reparse point data from a reparse point into memory, optionally
564 * fixing the targets of absolute symbolic links and junction points to be
565 * relative to the root of capture.
567 * @hFile: Open handle to the reparse point.
568 * @path: Path to the reparse point. Used for error messages only.
569 * @params: Additional parameters, including whether to do reparse point fixups
571 * @rpbuf: Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
572 * the reparse point buffer will be loaded.
573 * @rpbuflen_ret: On success, the length of the reparse point buffer in bytes
574 * is written to this location.
577 * On success, returns an `enum rp_status' value that indicates if and/or
578 * how the reparse point fixup was done.
580 * On failure, returns a negative value that is a negated WIMLIB_ERR_*
584 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
585 struct add_image_params *params,
586 u8 *rpbuf, u16 *rpbuflen_ret)
593 DEBUG("Loading reparse data from \"%ls\"", path);
594 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
595 NULL, /* "Not used with this operation; set to NULL" */
596 0, /* "Not used with this operation; set to 0" */
597 rpbuf, /* "A pointer to a buffer that
598 receives the reparse point data */
599 REPARSE_POINT_MAX_SIZE, /* "The size of the output
604 DWORD err = GetLastError();
605 ERROR("Failed to get reparse data of \"%ls\"", path);
607 return -WIMLIB_ERR_READ;
609 if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
610 ERROR("Reparse data on \"%ls\" is invalid", path);
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,
629 *rpbuflen_ret = rpbuflen;
634 win32_tally_encrypted_size_cb(unsigned char *_data, void *_ctx,
638 return ERROR_SUCCESS;
642 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
649 err = OpenEncryptedFileRawW(path, 0, &file_ctx);
650 if (err != ERROR_SUCCESS) {
651 ERROR("Failed to open encrypted file \"%ls\" for raw read", path);
653 return WIMLIB_ERR_OPEN;
655 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
657 if (err != ERROR_SUCCESS) {
658 ERROR("Failed to read raw encrypted data from \"%ls\"", path);
660 ret = WIMLIB_ERR_READ;
664 CloseEncryptedFileRaw(file_ctx);
668 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
669 * stream); calculates its SHA1 message digest and either creates a `struct
670 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
671 * wim_lookup_table_entry' for an identical stream.
673 * @path: Path to the file (UTF-16LE).
675 * @path_num_chars: Number of 2-byte characters in @path.
677 * @inode: WIM inode to save the stream into.
679 * @lookup_table: Stream lookup table for the WIM.
681 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
684 * Returns 0 on success; nonzero on failure.
687 win32_capture_stream(const wchar_t *path,
688 size_t path_num_chars,
689 struct wim_inode *inode,
690 struct wim_lookup_table *lookup_table,
691 WIN32_FIND_STREAM_DATA *dat)
693 struct wim_ads_entry *ads_entry;
694 struct wim_lookup_table_entry *lte;
696 wchar_t *stream_name, *colon;
697 size_t stream_name_nchars;
698 bool is_named_stream;
701 size_t spath_buf_nbytes;
702 const wchar_t *relpath_prefix;
703 const wchar_t *colonchar;
705 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
707 /* The stream name should be returned as :NAME:TYPE */
708 stream_name = dat->cStreamName;
709 if (*stream_name != L':')
710 goto out_invalid_stream_name;
712 colon = wcschr(stream_name, L':');
714 goto out_invalid_stream_name;
716 if (wcscmp(colon + 1, L"$DATA")) {
717 /* Not a DATA stream */
724 stream_name_nchars = colon - stream_name;
725 is_named_stream = (stream_name_nchars != 0);
727 if (is_named_stream) {
728 /* Allocate an ADS entry for the named stream. */
729 ads_entry = inode_add_ads_utf16le(inode, stream_name,
730 stream_name_nchars * sizeof(wchar_t));
732 ret = WIMLIB_ERR_NOMEM;
737 /* If zero length stream, no lookup table entry needed. */
738 if ((u64)dat->StreamSize.QuadPart == 0) {
743 /* Create a UTF-16LE string @spath that gives the filename, then a
744 * colon, then the stream name. Or, if it's an unnamed stream, just the
745 * filename. It is MALLOC()'ed so that it can be saved in the
746 * wim_lookup_table_entry if needed.
748 * As yet another special case, relative paths need to be changed to
749 * begin with an explicit "./" so that, for example, a file t:ads, where
750 * :ads is the part we added, is not interpreted as a file on the t:
752 spath_nchars = path_num_chars;
753 relpath_prefix = L"";
755 if (is_named_stream) {
756 spath_nchars += 1 + stream_name_nchars;
758 if (path_num_chars == 1 &&
763 relpath_prefix = L"./";
767 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
768 spath = MALLOC(spath_buf_nbytes);
770 swprintf(spath, L"%ls%ls%ls%ls",
771 relpath_prefix, path, colonchar, stream_name);
773 /* Make a new wim_lookup_table_entry */
774 lte = new_lookup_table_entry();
776 ret = WIMLIB_ERR_NOMEM;
779 lte->file_on_disk = spath;
781 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
783 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
784 ret = win32_get_encrypted_file_size(path, &encrypted_size);
787 lte->resource_entry.original_size = encrypted_size;
789 lte->resource_location = RESOURCE_WIN32;
790 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
794 if (is_named_stream) {
795 stream_id = ads_entry->stream_id;
796 ads_entry->lte = lte;
801 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
807 out_invalid_stream_name:
808 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
809 ret = WIMLIB_ERR_READ;
813 /* Scans a Win32 file for unnamed and named data streams (not reparse point
816 * @path: Path to the file (UTF-16LE).
818 * @path_num_chars: Number of 2-byte characters in @path.
820 * @inode: WIM inode to save the stream into.
822 * @lookup_table: Stream lookup table for the WIM.
824 * @file_size: Size of unnamed data stream. (Used only if alternate
825 * data streams API appears to be unavailable.)
827 * @vol_flags: Flags that specify features of the volume being
830 * Returns 0 on success; nonzero on failure.
833 win32_capture_streams(const wchar_t *path,
834 size_t path_num_chars,
835 struct wim_inode *inode,
836 struct wim_lookup_table *lookup_table,
840 WIN32_FIND_STREAM_DATA dat;
845 DEBUG("Capturing streams from \"%ls\"", path);
847 if (win32func_FindFirstStreamW == NULL ||
848 !(vol_flags & FILE_NAMED_STREAMS))
851 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
852 if (hFind == INVALID_HANDLE_VALUE) {
853 err = GetLastError();
854 if (err == ERROR_CALL_NOT_IMPLEMENTED)
857 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
858 * points and directories */
859 if ((inode->i_attributes &
860 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
861 && err == ERROR_HANDLE_EOF)
863 DEBUG("ERROR_HANDLE_EOF (ok)");
866 if (err == ERROR_ACCESS_DENIED) {
867 WARNING("Failed to look up data streams "
868 "of \"%ls\": Access denied!\n%ls",
869 path, capture_access_denied_msg);
872 ERROR("Failed to look up data streams "
875 return WIMLIB_ERR_READ;
880 ret = win32_capture_stream(path,
886 } while (win32func_FindNextStreamW(hFind, &dat));
887 err = GetLastError();
888 if (err != ERROR_HANDLE_EOF) {
889 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
891 ret = WIMLIB_ERR_READ;
897 /* FindFirstStreamW() API is not available, or the volume does not
898 * support named streams. Only capture the unnamed data stream. */
899 DEBUG("Only capturing unnamed data stream");
900 if (inode->i_attributes &
901 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
905 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
906 * stream to reduce the code to a call to the
907 * already-implemented win32_capture_stream() */
908 wcscpy(dat.cStreamName, L"::$DATA");
909 dat.StreamSize.QuadPart = file_size;
910 ret = win32_capture_stream(path,
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;
935 if (exclude_path(path, path_num_chars, params->config, true)) {
936 if (params->add_flags & WIMLIB_ADD_FLAG_ROOT) {
937 ERROR("Cannot exclude the root directory from capture");
938 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
941 if ((params->add_flags & WIMLIB_ADD_FLAG_EXCLUDE_VERBOSE)
942 && params->progress_func)
944 union wimlib_progress_info info;
945 info.scan.cur_path = path;
946 info.scan.excluded = true;
947 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
953 if ((params->add_flags & WIMLIB_ADD_FLAG_VERBOSE)
954 && params->progress_func)
956 union wimlib_progress_info info;
957 info.scan.cur_path = path;
958 info.scan.excluded = false;
959 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
962 HANDLE hFile = win32_open_existing_file(path,
963 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
964 if (hFile == INVALID_HANDLE_VALUE) {
965 err = GetLastError();
966 ERROR("Win32 API: Failed to open \"%ls\"", path);
968 ret = WIMLIB_ERR_OPEN;
972 BY_HANDLE_FILE_INFORMATION file_info;
973 if (!GetFileInformationByHandle(hFile, &file_info)) {
974 err = GetLastError();
975 ERROR("Win32 API: Failed to get file information for \"%ls\"",
978 ret = WIMLIB_ERR_STAT;
979 goto out_close_handle;
982 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
983 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
984 ret = win32_get_reparse_data(hFile, path, params,
987 /* WIMLIB_ERR_* (inverted) */
989 goto out_close_handle;
990 } else if (ret & RP_FIXED) {
992 } else if (ret == RP_EXCLUDED) {
994 goto out_close_handle;
1000 /* Create a WIM dentry with an associated inode, which may be shared.
1002 * However, we need to explicitly check for directories and files with
1003 * only 1 link and refuse to hard link them. This is because Windows
1004 * has a bug where it can return duplicate File IDs for files and
1005 * directories on the FAT filesystem. */
1006 ret = inode_table_new_dentry(¶ms->inode_table,
1007 path_basename_with_len(path, path_num_chars),
1008 ((u64)file_info.nFileIndexHigh << 32) |
1009 (u64)file_info.nFileIndexLow,
1010 file_info.dwVolumeSerialNumber,
1011 (file_info.nNumberOfLinks <= 1 ||
1012 (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1015 goto out_close_handle;
1017 ret = win32_get_short_name(root, path);
1019 goto out_close_handle;
1021 inode = root->d_inode;
1023 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1024 goto out_close_handle;
1026 inode->i_attributes = file_info.dwFileAttributes;
1027 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1028 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1029 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1030 inode->i_resolved = 1;
1032 params->add_flags &= ~WIMLIB_ADD_FLAG_ROOT;
1034 if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1035 && (vol_flags & FILE_PERSISTENT_ACLS))
1037 ret = win32_get_security_descriptor(root, ¶ms->sd_set,
1041 goto out_close_handle;
1044 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1045 (u64)file_info.nFileSizeLow;
1049 /* Capture the unnamed data stream (only should be present for regular
1050 * files) and any alternate data streams. */
1051 ret = win32_capture_streams(path,
1054 params->lookup_table,
1060 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1061 /* Reparse point: set the reparse data (which we read already)
1063 inode->i_not_rpfixed = not_rpfixed;
1064 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1065 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1066 params->lookup_table);
1067 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1068 /* Directory (not a reparse point) --- recurse to children */
1069 ret = win32_recurse_directory(root,
1083 free_dentry_tree(root, params->lookup_table);
1088 win32_do_capture_warnings(const struct win32_capture_state *state,
1091 if (state->num_get_sacl_priv_notheld == 0 &&
1092 state->num_get_sd_access_denied == 0)
1096 WARNING("Built dentry tree successfully, but with the following problem(s):");
1097 if (state->num_get_sacl_priv_notheld != 0) {
1098 WARNING("Could not capture SACL (System Access Control List)\n"
1099 " on %lu files or directories.",
1100 state->num_get_sacl_priv_notheld);
1102 if (state->num_get_sd_access_denied != 0) {
1103 WARNING("Could not capture security descriptor at all\n"
1104 " on %lu files or directories.",
1105 state->num_get_sd_access_denied);
1108 "Try running the program as the Administrator to make sure all the\n"
1109 " desired metadata has been captured exactly. However, if you\n"
1110 " do not care about capturing security descriptors correctly, then\n"
1111 " nothing more needs to be done%ls\n",
1112 (add_flags & WIMLIB_ADD_FLAG_NO_ACLS) ? L"." :
1113 L", although you might consider\n"
1114 " using the --no-acls option to explicitly capture no security\n"
1118 /* Win32 version of capturing a directory tree */
1120 win32_build_dentry_tree(struct wim_dentry **root_ret,
1121 const wchar_t *root_disk_path,
1122 struct add_image_params *params)
1127 struct win32_capture_state state;
1130 if (!win32func_FindFirstStreamW) {
1131 WARNING("Running on Windows XP or earlier; "
1132 "alternate data streams will not be captured.");
1135 path_nchars = wcslen(root_disk_path);
1136 if (path_nchars > 32767)
1137 return WIMLIB_ERR_INVALID_PARAM;
1139 if (GetFileAttributesW(root_disk_path) == INVALID_FILE_ATTRIBUTES &&
1140 GetLastError() == ERROR_FILE_NOT_FOUND)
1142 ERROR("Capture directory \"%ls\" does not exist!",
1144 return WIMLIB_ERR_OPENDIR;
1147 ret = win32_get_file_and_vol_ids(root_disk_path,
1148 ¶ms->capture_root_ino,
1149 ¶ms->capture_root_dev);
1153 win32_get_vol_flags(root_disk_path, &vol_flags);
1155 /* There is no check for overflow later when this buffer is being used!
1156 * But the max path length on NTFS is 32767 characters, and paths need
1157 * to be written specially to even go past 260 characters, so we should
1158 * be okay with 32770 characters. */
1159 path = MALLOC(32770 * sizeof(wchar_t));
1161 return WIMLIB_ERR_NOMEM;
1163 wmemcpy(path, root_disk_path, path_nchars + 1);
1165 memset(&state, 0, sizeof(state));
1166 ret = win32_build_dentry_tree_recursive(root_ret, path,
1167 path_nchars, params,
1171 win32_do_capture_warnings(&state, params->add_flags);
1175 #endif /* __WIN32__ */