4 * All the library code specific to native Windows builds is in here.
8 * Copyright (C) 2013 Eric Biggers
10 * This file is part of wimlib, a library for working with WIM files.
12 * wimlib is free software; you can redistribute it and/or modify it under the
13 * terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 3 of the License, or (at your option)
17 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 * A PARTICULAR PURPOSE. See the GNU General Public License for more
22 * You should have received a copy of the GNU General Public License
23 * along with wimlib; if not, see http://www.gnu.org/licenses/.
32 #include <shlwapi.h> /* for PathMatchSpecW() */
33 #include <aclapi.h> /* for SetSecurityInfo() */
34 #ifdef ERROR /* windows.h defines this */
40 #include "lookup_table.h"
42 #include "endianness.h"
43 #include "buffer_io.h"
48 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
49 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
50 #define MAX_CREATE_HARD_LINK_WARNINGS 5
51 struct win32_capture_state {
52 unsigned long num_get_sd_access_denied;
53 unsigned long num_get_sacl_priv_notheld;
56 #define MAX_SET_SD_ACCESS_DENIED_WARNINGS 1
57 #define MAX_SET_SACL_PRIV_NOTHELD_WARNINGS 1
59 #ifdef ENABLE_ERROR_MESSAGES
61 win32_error(u32 err_code)
65 nchars = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
66 FORMAT_MESSAGE_ALLOCATE_BUFFER,
68 (wchar_t*)&buffer, 0, NULL);
70 ERROR("Error printing error message! "
71 "Computer will self-destruct in 3 seconds.");
73 ERROR("Win32 error: %ls", buffer);
77 #else /* ENABLE_ERROR_MESSAGES */
78 # define win32_error(err_code)
79 #endif /* !ENABLE_ERROR_MESSAGES */
81 /* Pointers to functions that are not available on all targetted versions of
82 * Windows (XP and later). NOTE: The WINAPI annotations seem to be important; I
83 * assume it specifies a certain calling convention. */
86 static HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
87 STREAM_INFO_LEVELS InfoLevel,
88 LPVOID lpFindStreamData,
89 DWORD dwFlags) = NULL;
92 static BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
93 LPVOID lpFindStreamData) = NULL;
95 static HMODULE hKernel32 = NULL;
97 /* Try to dynamically load some functions */
103 if (hKernel32 == NULL) {
104 DEBUG("Loading Kernel32.dll");
105 hKernel32 = LoadLibraryW(L"Kernel32.dll");
106 if (hKernel32 == NULL) {
107 err = GetLastError();
108 WARNING("Can't load Kernel32.dll");
114 DEBUG("Looking for FindFirstStreamW");
115 win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32, "FindFirstStreamW");
116 if (!win32func_FindFirstStreamW) {
117 WARNING("Could not find function FindFirstStreamW() in Kernel32.dll!");
118 WARNING("Capturing alternate data streams will not be supported.");
122 DEBUG("Looking for FindNextStreamW");
123 win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32, "FindNextStreamW");
124 if (!win32func_FindNextStreamW) {
125 WARNING("Could not find function FindNextStreamW() in Kernel32.dll!");
126 WARNING("Capturing alternate data streams will not be supported.");
127 win32func_FindFirstStreamW = NULL;
132 win32_global_cleanup()
134 if (hKernel32 != NULL) {
135 DEBUG("Closing Kernel32.dll");
136 FreeLibrary(hKernel32);
141 static const wchar_t *capture_access_denied_msg =
142 L" If you are not running this program as the administrator, you may\n"
143 " need to do so, so that all data and metadata can be backed up.\n"
144 " Otherwise, there may be no way to access the desired data or\n"
145 " metadata without taking ownership of the file or directory.\n"
148 static const wchar_t *apply_access_denied_msg =
149 L"If you are not running this program as the administrator, you may\n"
150 " need to do so, so that all data and metadata can be extracted\n"
151 " exactly as the origignal copy. However, if you do not care that\n"
152 " the security descriptors are extracted correctly, you could run\n"
153 " `wimlib-imagex apply' with the --no-acls flag instead.\n"
157 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
159 return CreateFileW(path,
162 NULL, /* lpSecurityAttributes */
164 FILE_FLAG_BACKUP_SEMANTICS |
165 FILE_FLAG_OPEN_REPARSE_POINT,
166 NULL /* hTemplateFile */);
170 win32_open_file_data_only(const wchar_t *path)
172 return win32_open_existing_file(path, FILE_READ_DATA);
176 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
178 consume_data_callback_t cb,
187 HANDLE hFile = win32_open_file_data_only(lte->file_on_disk);
188 if (hFile == INVALID_HANDLE_VALUE) {
189 err = GetLastError();
190 ERROR("Failed to open \"%ls\"", lte->file_on_disk);
192 return WIMLIB_ERR_OPEN;
196 out_buf = alloca(WIM_CHUNK_SIZE);
198 out_buf = ctx_or_buf;
200 bytes_remaining = size;
201 while (bytes_remaining) {
202 DWORD bytesToRead, bytesRead;
204 bytesToRead = min(WIM_CHUNK_SIZE, bytes_remaining);
205 if (!ReadFile(hFile, out_buf, bytesToRead, &bytesRead, NULL) ||
206 bytesRead != bytesToRead)
208 err = GetLastError();
209 ERROR("Failed to read data from \"%ls\"", lte->file_on_disk);
211 ret = WIMLIB_ERR_READ;
214 bytes_remaining -= bytesRead;
216 ret = (*cb)(out_buf, bytesRead, ctx_or_buf);
220 out_buf += bytesRead;
227 struct win32_encrypted_read_ctx {
228 consume_data_callback_t read_prefix_cb;
229 void *read_prefix_ctx_or_buf;
237 win32_encrypted_export_cb(unsigned char *_data, void *_ctx, unsigned long len)
239 const void *data = _data;
240 struct win32_encrypted_read_ctx *ctx = _ctx;
243 DEBUG("len = %lu", len);
244 if (ctx->read_prefix_cb) {
245 /* The length of the buffer passed to the ReadEncryptedFileRaw()
246 * export callback is undocumented, so we assume it may be of
248 size_t bytes_to_buffer = min(ctx->bytes_remaining - ctx->buf_filled,
250 while (bytes_to_buffer) {
251 size_t bytes_to_copy_to_buf =
252 min(bytes_to_buffer, WIM_CHUNK_SIZE - ctx->buf_filled);
254 memcpy(ctx->buf + ctx->buf_filled, data,
255 bytes_to_copy_to_buf);
256 ctx->buf_filled += bytes_to_copy_to_buf;
257 data += bytes_to_copy_to_buf;
258 bytes_to_buffer -= bytes_to_copy_to_buf;
260 if (ctx->buf_filled == WIM_CHUNK_SIZE ||
261 ctx->buf_filled == ctx->bytes_remaining)
263 ret = (*ctx->read_prefix_cb)(ctx->buf,
265 ctx->read_prefix_ctx_or_buf);
267 ctx->wimlib_err_code = ret;
268 /* Shouldn't matter what error code is returned
269 * here, as long as it isn't ERROR_SUCCESS. */
270 return ERROR_READ_FAULT;
272 ctx->bytes_remaining -= ctx->buf_filled;
277 size_t len_to_copy = min(len, ctx->bytes_remaining);
278 memcpy(ctx->read_prefix_ctx_or_buf, data, len_to_copy);
279 ctx->bytes_remaining -= len_to_copy;
280 ctx->read_prefix_ctx_or_buf += len_to_copy;
282 return ERROR_SUCCESS;
286 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
288 consume_data_callback_t cb,
292 struct win32_encrypted_read_ctx export_ctx;
297 DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
298 size, lte->file_on_disk);
300 export_ctx.read_prefix_cb = cb;
301 export_ctx.read_prefix_ctx_or_buf = ctx_or_buf;
302 export_ctx.wimlib_err_code = 0;
304 export_ctx.buf = MALLOC(WIM_CHUNK_SIZE);
306 return WIMLIB_ERR_NOMEM;
308 export_ctx.buf = NULL;
310 export_ctx.buf_filled = 0;
311 export_ctx.bytes_remaining = size;
313 err = OpenEncryptedFileRawW(lte->file_on_disk, 0, &file_ctx);
314 if (err != ERROR_SUCCESS) {
315 ERROR("Failed to open encrypted file \"%ls\" for raw read",
318 ret = WIMLIB_ERR_OPEN;
321 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
322 &export_ctx, file_ctx);
323 if (err != ERROR_SUCCESS) {
324 ERROR("Failed to read encrypted file \"%ls\"",
327 ret = export_ctx.wimlib_err_code;
329 ret = WIMLIB_ERR_READ;
330 } else if (export_ctx.bytes_remaining != 0) {
331 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
332 "encryted file \"%ls\"",
333 size - export_ctx.bytes_remaining, size,
335 ret = WIMLIB_ERR_READ;
339 CloseEncryptedFileRaw(file_ctx);
341 FREE(export_ctx.buf);
345 /* Given a path, which may not yet exist, get a set of flags that describe the
346 * features of the volume the path is on. */
348 win32_get_vol_flags(const wchar_t *path, unsigned *vol_flags_ret)
354 if (path[0] != L'\0' && path[0] != L'\\' &&
355 path[0] != L'/' && path[1] == L':')
357 /* Path starts with a drive letter; use it. */
358 volume = alloca(4 * sizeof(wchar_t));
364 /* Path does not start with a drive letter; use the volume of
365 * the current working directory. */
368 bret = GetVolumeInformationW(volume, /* lpRootPathName */
369 NULL, /* lpVolumeNameBuffer */
370 0, /* nVolumeNameSize */
371 NULL, /* lpVolumeSerialNumber */
372 NULL, /* lpMaximumComponentLength */
373 &vol_flags, /* lpFileSystemFlags */
374 NULL, /* lpFileSystemNameBuffer */
375 0); /* nFileSystemNameSize */
377 DWORD err = GetLastError();
378 WARNING("Failed to get volume information for path \"%ls\"", path);
380 vol_flags = 0xffffffff;
383 DEBUG("using vol_flags = %x", vol_flags);
384 *vol_flags_ret = vol_flags;
390 FILETIME_to_u64(const FILETIME *ft)
392 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
396 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
398 WIN32_FIND_DATAW dat;
402 /* If we can't read the short filename for some reason, we just ignore
403 * the error and assume the file has no short name. I don't think this
404 * should be an issue, since the short names are essentially obsolete
406 hFind = FindFirstFileW(path, &dat);
407 if (hFind != INVALID_HANDLE_VALUE) {
408 if (dat.cAlternateFileName[0] != L'\0') {
409 DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
410 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
412 size_t n = short_name_nbytes + sizeof(wchar_t);
413 dentry->short_name = MALLOC(n);
414 if (dentry->short_name) {
415 memcpy(dentry->short_name, dat.cAlternateFileName, n);
416 dentry->short_name_nbytes = short_name_nbytes;
418 ret = WIMLIB_ERR_NOMEM;
427 win32_get_security_descriptor(struct wim_dentry *dentry,
428 struct sd_set *sd_set,
430 struct win32_capture_state *state,
433 SECURITY_INFORMATION requestedInformation;
439 requestedInformation = DACL_SECURITY_INFORMATION |
440 SACL_SECURITY_INFORMATION |
441 OWNER_SECURITY_INFORMATION |
442 GROUP_SECURITY_INFORMATION;
444 /* Request length of security descriptor */
445 status = GetFileSecurityW(path, requestedInformation,
446 NULL, 0, &lenNeeded);
447 err = GetLastError();
448 if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
449 DWORD len = lenNeeded;
451 if (GetFileSecurityW(path, requestedInformation,
452 (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
454 int security_id = sd_set_add_sd(sd_set, buf, len);
456 return WIMLIB_ERR_NOMEM;
458 dentry->d_inode->i_security_id = security_id;
462 err = GetLastError();
466 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS)
470 case ERROR_PRIVILEGE_NOT_HELD:
471 if (requestedInformation & SACL_SECURITY_INFORMATION) {
472 n = state->num_get_sacl_priv_notheld++;
473 requestedInformation &= ~SACL_SECURITY_INFORMATION;
474 if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
476 "We don't have enough privileges to read the full security\n"
477 " descriptor of \"%ls\"!\n"
478 " Re-trying with SACL omitted.\n", path);
479 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
481 "Suppressing further privileges not held error messages when reading\n"
482 " security descriptors.");
487 case ERROR_ACCESS_DENIED:
488 n = state->num_get_sd_access_denied++;
489 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
490 WARNING("Failed to read security descriptor of \"%ls\": "
491 "Access denied!\n%ls", path, capture_access_denied_msg);
492 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
493 WARNING("Suppressing further access denied errors messages i"
494 "when reading security descriptors");
499 ERROR("Failed to read security descriptor of \"%ls\"", path);
501 return WIMLIB_ERR_READ;
506 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
508 size_t path_num_chars,
509 struct add_image_params *params,
510 struct win32_capture_state *state,
513 /* Reads the directory entries of directory using a Win32 API and recursively
514 * calls win32_build_dentry_tree() on them. */
516 win32_recurse_directory(struct wim_dentry *root,
518 size_t dir_path_num_chars,
519 struct add_image_params *params,
520 struct win32_capture_state *state,
523 WIN32_FIND_DATAW dat;
528 DEBUG("Recurse to directory \"%ls\"", dir_path);
530 /* Begin reading the directory by calling FindFirstFileW. Unlike UNIX
531 * opendir(), FindFirstFileW has file globbing built into it. But this
532 * isn't what we actually want, so just add a dummy glob to get all
534 dir_path[dir_path_num_chars] = L'/';
535 dir_path[dir_path_num_chars + 1] = L'*';
536 dir_path[dir_path_num_chars + 2] = L'\0';
537 hFind = FindFirstFileW(dir_path, &dat);
538 dir_path[dir_path_num_chars] = L'\0';
540 if (hFind == INVALID_HANDLE_VALUE) {
541 err = GetLastError();
542 if (err == ERROR_FILE_NOT_FOUND) {
545 ERROR("Failed to read directory \"%ls\"", dir_path);
547 return WIMLIB_ERR_READ;
552 /* Skip . and .. entries */
553 if (dat.cFileName[0] == L'.' &&
554 (dat.cFileName[1] == L'\0' ||
555 (dat.cFileName[1] == L'.' &&
556 dat.cFileName[2] == L'\0')))
558 size_t filename_len = wcslen(dat.cFileName);
560 dir_path[dir_path_num_chars] = L'/';
561 wmemcpy(dir_path + dir_path_num_chars + 1,
565 struct wim_dentry *child;
566 size_t path_len = dir_path_num_chars + 1 + filename_len;
567 ret = win32_build_dentry_tree_recursive(&child,
573 dir_path[dir_path_num_chars] = L'\0';
577 dentry_add_child(root, child);
578 } while (FindNextFileW(hFind, &dat));
579 err = GetLastError();
580 if (err != ERROR_NO_MORE_FILES) {
581 ERROR("Failed to read directory \"%ls\"", dir_path);
584 ret = WIMLIB_ERR_READ;
592 win32_get_file_and_vol_ids(const wchar_t *path, u64 *ino_ret, u64 *dev_ret)
596 BY_HANDLE_FILE_INFORMATION file_info;
599 hFile = win32_open_existing_file(path, FILE_READ_ATTRIBUTES);
600 if (hFile == INVALID_HANDLE_VALUE) {
601 err = GetLastError();
602 if (err != ERROR_FILE_NOT_FOUND) {
603 WARNING("Failed to open \"%ls\" to get file "
604 "and volume IDs", path);
607 return WIMLIB_ERR_OPEN;
610 if (!GetFileInformationByHandle(hFile, &file_info)) {
611 err = GetLastError();
612 ERROR("Failed to get file information for \"%ls\"", path);
614 ret = WIMLIB_ERR_STAT;
616 *ino_ret = ((u64)file_info.nFileIndexHigh << 32) |
617 (u64)file_info.nFileIndexLow;
618 *dev_ret = file_info.dwVolumeSerialNumber;
625 /* Reparse point fixup status code */
627 /* Reparse point corresponded to an absolute symbolic link or junction
628 * point that pointed outside the directory tree being captured, and
629 * therefore was excluded. */
632 /* Reparse point was not fixed as it was either a relative symbolic
633 * link, a mount point, or something else we could not understand. */
636 /* Reparse point corresponded to an absolute symbolic link or junction
637 * point that pointed inside the directory tree being captured, where
638 * the target was specified by a "full" \??\ prefixed path, and
639 * therefore was fixed to be relative to the root of the directory tree
641 RP_FIXED_FULLPATH = 0x2,
643 /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
644 * have the \??\ prefix. It may have begun with a drive letter though.
646 RP_FIXED_ABSPATH = 0x4,
648 /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
649 RP_FIXED = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
652 /* Given the "substitute name" target of a Windows reparse point, try doing a
653 * fixup where we change it to be absolute relative to the root of the directory
654 * tree being captured.
656 * Note that this is only executed when WIMLIB_ADD_IMAGE_FLAG_RPFIX has been
659 * @capture_root_ino and @capture_root_dev indicate the inode number and device
660 * of the root of the directory tree being captured. They are meant to identify
661 * this directory (as an alternative to its actual path, which could potentially
662 * be reached via multiple destinations due to other symbolic links). This may
663 * not work properly on FAT, which doesn't seem to supply proper inode numbers
664 * or file IDs. However, FAT doesn't support reparse points so this function
665 * wouldn't even be called anyway.
667 static enum rp_status
668 win32_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
669 u64 capture_root_ino, u64 capture_root_dev,
672 u16 target_nchars = *target_nbytes_p / 2;
673 size_t stripped_chars;
674 wchar_t *orig_target;
677 ret = parse_substitute_name(target, *target_nbytes_p, rptag);
680 stripped_chars = ret;
683 target[target_nchars] = L'\0';
684 orig_target = target;
685 target = capture_fixup_absolute_symlink(target + stripped_chars,
686 capture_root_ino, capture_root_dev);
689 target_nchars = wcslen(target);
690 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
691 *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
692 DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
694 return RP_FIXED_FULLPATH;
696 return RP_FIXED_ABSPATH;
699 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
702 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
703 u64 capture_root_ino, u64 capture_root_dev,
706 struct reparse_data rpdata;
709 enum rp_status rp_status;
711 rpbuflen = *rpbuflen_p;
712 ret = parse_reparse_data(rpbuf, rpbuflen, &rpdata);
716 rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
717 &rpdata.substitute_name_nbytes,
720 le32_to_cpu(*(u32*)rpbuf));
721 if (rp_status & RP_FIXED) {
722 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
723 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
724 wmemcpy(substitute_name_copy, rpdata.substitute_name,
725 rpdata.substitute_name_nbytes / 2);
726 rpdata.substitute_name = substitute_name_copy;
727 rpdata.print_name = substitute_name_copy;
728 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
729 if (rp_status == RP_FIXED_FULLPATH) {
730 /* "full path", meaning \??\ prefixed. We should not
731 * include this prefix in the print name, as it is
732 * apparently meant for the filesystem driver only. */
733 rpdata.print_name += 4;
734 rpdata.print_name_nbytes -= 8;
736 ret = make_reparse_buffer(&rpdata, rpbuf);
742 if (rp_status == RP_EXCLUDED) {
743 size_t print_name_nchars = rpdata.print_name_nbytes / 2;
744 wchar_t print_name0[print_name_nchars + 1];
745 print_name0[print_name_nchars] = L'\0';
746 wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
747 WARNING("Ignoring %ls pointing out of capture directory:\n"
748 " \"%ls\" -> \"%ls\"\n"
749 " (Use --norpfix to capture all symbolic links "
750 "and junction points as-is)",
751 (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK) ?
752 L"absolute symbolic link" : L"junction point",
761 * Loads the reparse point data from a reparse point into memory, optionally
762 * fixing the targets of absolute symbolic links and junction points to be
763 * relative to the root of capture.
765 * @hFile: Open handle to the reparse point.
766 * @path: Path to the reparse point. Used for error messages only.
767 * @params: Additional parameters, including whether to do reparse point fixups
769 * @rpbuf: Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
770 * the reparse point buffer will be loaded.
771 * @rpbuflen_ret: On success, the length of the reparse point buffer in bytes
772 * is written to this location.
775 * On success, returns an `enum rp_status' value that indicates if and/or
776 * how the reparse point fixup was done.
778 * On failure, returns a negative value that is a negated WIMLIB_ERR_*
782 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
783 struct add_image_params *params,
784 u8 *rpbuf, u16 *rpbuflen_ret)
791 DEBUG("Loading reparse data from \"%ls\"", path);
792 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
793 NULL, /* "Not used with this operation; set to NULL" */
794 0, /* "Not used with this operation; set to 0" */
795 rpbuf, /* "A pointer to a buffer that
796 receives the reparse point data */
797 REPARSE_POINT_MAX_SIZE, /* "The size of the output
802 DWORD err = GetLastError();
803 ERROR("Failed to get reparse data of \"%ls\"", path);
805 return -WIMLIB_ERR_READ;
807 if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
808 ERROR("Reparse data on \"%ls\" is invalid", path);
809 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
812 rpbuflen = bytesReturned;
813 reparse_tag = le32_to_cpu(*(u32*)rpbuf);
814 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX &&
815 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
816 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
818 /* Try doing reparse point fixup */
819 ret = win32_capture_try_rpfix(rpbuf,
821 params->capture_root_ino,
822 params->capture_root_dev,
827 *rpbuflen_ret = rpbuflen;
832 win32_tally_encrypted_size_cb(unsigned char *_data, void *_ctx,
836 return ERROR_SUCCESS;
840 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
847 err = OpenEncryptedFileRawW(path, 0, &file_ctx);
848 if (err != ERROR_SUCCESS) {
849 ERROR("Failed to open encrypted file \"%ls\" for raw read", path);
851 return WIMLIB_ERR_OPEN;
853 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
855 if (err != ERROR_SUCCESS) {
856 ERROR("Failed to read raw encrypted data from \"%ls\"", path);
858 ret = WIMLIB_ERR_READ;
862 CloseEncryptedFileRaw(file_ctx);
866 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
867 * stream); calculates its SHA1 message digest and either creates a `struct
868 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
869 * wim_lookup_table_entry' for an identical stream.
871 * @path: Path to the file (UTF-16LE).
873 * @path_num_chars: Number of 2-byte characters in @path.
875 * @inode: WIM inode to save the stream into.
877 * @lookup_table: Stream lookup table for the WIM.
879 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
882 * Returns 0 on success; nonzero on failure.
885 win32_capture_stream(const wchar_t *path,
886 size_t path_num_chars,
887 struct wim_inode *inode,
888 struct wim_lookup_table *lookup_table,
889 WIN32_FIND_STREAM_DATA *dat)
891 struct wim_ads_entry *ads_entry;
892 struct wim_lookup_table_entry *lte;
894 wchar_t *stream_name, *colon;
895 size_t stream_name_nchars;
896 bool is_named_stream;
899 size_t spath_buf_nbytes;
900 const wchar_t *relpath_prefix;
901 const wchar_t *colonchar;
903 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
905 /* The stream name should be returned as :NAME:TYPE */
906 stream_name = dat->cStreamName;
907 if (*stream_name != L':')
908 goto out_invalid_stream_name;
910 colon = wcschr(stream_name, L':');
912 goto out_invalid_stream_name;
914 if (wcscmp(colon + 1, L"$DATA")) {
915 /* Not a DATA stream */
922 stream_name_nchars = colon - stream_name;
923 is_named_stream = (stream_name_nchars != 0);
925 if (is_named_stream) {
926 /* Allocate an ADS entry for the named stream. */
927 ads_entry = inode_add_ads_utf16le(inode, stream_name,
928 stream_name_nchars * sizeof(wchar_t));
930 ret = WIMLIB_ERR_NOMEM;
935 /* If zero length stream, no lookup table entry needed. */
936 if ((u64)dat->StreamSize.QuadPart == 0) {
941 /* Create a UTF-16LE string @spath that gives the filename, then a
942 * colon, then the stream name. Or, if it's an unnamed stream, just the
943 * filename. It is MALLOC()'ed so that it can be saved in the
944 * wim_lookup_table_entry if needed.
946 * As yet another special case, relative paths need to be changed to
947 * begin with an explicit "./" so that, for example, a file t:ads, where
948 * :ads is the part we added, is not interpreted as a file on the t:
950 spath_nchars = path_num_chars;
951 relpath_prefix = L"";
953 if (is_named_stream) {
954 spath_nchars += 1 + stream_name_nchars;
956 if (path_num_chars == 1 &&
961 relpath_prefix = L"./";
965 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
966 spath = MALLOC(spath_buf_nbytes);
968 swprintf(spath, L"%ls%ls%ls%ls",
969 relpath_prefix, path, colonchar, stream_name);
971 /* Make a new wim_lookup_table_entry */
972 lte = new_lookup_table_entry();
974 ret = WIMLIB_ERR_NOMEM;
977 lte->file_on_disk = spath;
979 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
981 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
982 ret = win32_get_encrypted_file_size(path, &encrypted_size);
985 lte->resource_entry.original_size = encrypted_size;
987 lte->resource_location = RESOURCE_WIN32;
988 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
992 if (is_named_stream) {
993 stream_id = ads_entry->stream_id;
994 ads_entry->lte = lte;
999 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
1005 out_invalid_stream_name:
1006 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
1007 ret = WIMLIB_ERR_READ;
1011 /* Scans a Win32 file for unnamed and named data streams (not reparse point
1014 * @path: Path to the file (UTF-16LE).
1016 * @path_num_chars: Number of 2-byte characters in @path.
1018 * @inode: WIM inode to save the stream into.
1020 * @lookup_table: Stream lookup table for the WIM.
1022 * @file_size: Size of unnamed data stream. (Used only if alternate
1023 * data streams API appears to be unavailable.)
1025 * @vol_flags: Flags that specify features of the volume being
1028 * Returns 0 on success; nonzero on failure.
1031 win32_capture_streams(const wchar_t *path,
1032 size_t path_num_chars,
1033 struct wim_inode *inode,
1034 struct wim_lookup_table *lookup_table,
1038 WIN32_FIND_STREAM_DATA dat;
1043 DEBUG("Capturing streams from \"%ls\"", path);
1045 if (win32func_FindFirstStreamW == NULL ||
1046 !(vol_flags & FILE_NAMED_STREAMS))
1049 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1050 if (hFind == INVALID_HANDLE_VALUE) {
1051 err = GetLastError();
1052 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1055 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1056 * points and directories */
1057 if ((inode->i_attributes &
1058 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1059 && err == ERROR_HANDLE_EOF)
1061 DEBUG("ERROR_HANDLE_EOF (ok)");
1064 if (err == ERROR_ACCESS_DENIED) {
1065 WARNING("Failed to look up data streams "
1066 "of \"%ls\": Access denied!\n%ls",
1067 path, capture_access_denied_msg);
1070 ERROR("Failed to look up data streams "
1071 "of \"%ls\"", path);
1073 return WIMLIB_ERR_READ;
1078 ret = win32_capture_stream(path,
1080 inode, lookup_table,
1083 goto out_find_close;
1084 } while (win32func_FindNextStreamW(hFind, &dat));
1085 err = GetLastError();
1086 if (err != ERROR_HANDLE_EOF) {
1087 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
1089 ret = WIMLIB_ERR_READ;
1095 /* FindFirstStreamW() API is not available, or the volume does not
1096 * support named streams. Only capture the unnamed data stream. */
1097 DEBUG("Only capturing unnamed data stream");
1098 if (inode->i_attributes &
1099 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1103 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
1104 * stream to reduce the code to a call to the
1105 * already-implemented win32_capture_stream() */
1106 wcscpy(dat.cStreamName, L"::$DATA");
1107 dat.StreamSize.QuadPart = file_size;
1108 ret = win32_capture_stream(path,
1110 inode, lookup_table,
1117 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1119 size_t path_num_chars,
1120 struct add_image_params *params,
1121 struct win32_capture_state *state,
1124 struct wim_dentry *root = NULL;
1125 struct wim_inode *inode;
1133 if (exclude_path(path, path_num_chars, params->config, true)) {
1134 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
1135 ERROR("Cannot exclude the root directory from capture");
1136 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1139 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
1140 && params->progress_func)
1142 union wimlib_progress_info info;
1143 info.scan.cur_path = path;
1144 info.scan.excluded = true;
1145 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1151 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
1152 && params->progress_func)
1154 union wimlib_progress_info info;
1155 info.scan.cur_path = path;
1156 info.scan.excluded = false;
1157 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1160 HANDLE hFile = win32_open_existing_file(path,
1161 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1162 if (hFile == INVALID_HANDLE_VALUE) {
1163 err = GetLastError();
1164 ERROR("Win32 API: Failed to open \"%ls\"", path);
1166 ret = WIMLIB_ERR_OPEN;
1170 BY_HANDLE_FILE_INFORMATION file_info;
1171 if (!GetFileInformationByHandle(hFile, &file_info)) {
1172 err = GetLastError();
1173 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1176 ret = WIMLIB_ERR_STAT;
1177 goto out_close_handle;
1180 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1181 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1182 ret = win32_get_reparse_data(hFile, path, params,
1185 /* WIMLIB_ERR_* (inverted) */
1187 goto out_close_handle;
1188 } else if (ret & RP_FIXED) {
1190 } else if (ret == RP_EXCLUDED) {
1192 goto out_close_handle;
1198 /* Create a WIM dentry with an associated inode, which may be shared.
1200 * However, we need to explicitly check for directories and files with
1201 * only 1 link and refuse to hard link them. This is because Windows
1202 * has a bug where it can return duplicate File IDs for files and
1203 * directories on the FAT filesystem. */
1204 ret = inode_table_new_dentry(params->inode_table,
1205 path_basename_with_len(path, path_num_chars),
1206 ((u64)file_info.nFileIndexHigh << 32) |
1207 (u64)file_info.nFileIndexLow,
1208 file_info.dwVolumeSerialNumber,
1209 (file_info.nNumberOfLinks <= 1 ||
1210 (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1213 goto out_close_handle;
1215 ret = win32_get_short_name(root, path);
1217 goto out_close_handle;
1219 inode = root->d_inode;
1221 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1222 goto out_close_handle;
1224 inode->i_attributes = file_info.dwFileAttributes;
1225 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1226 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1227 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1228 inode->i_resolved = 1;
1230 params->add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
1232 if (!(params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)
1233 && (vol_flags & FILE_PERSISTENT_ACLS))
1235 ret = win32_get_security_descriptor(root, params->sd_set,
1237 params->add_image_flags);
1239 goto out_close_handle;
1242 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1243 (u64)file_info.nFileSizeLow;
1247 /* Capture the unnamed data stream (only should be present for regular
1248 * files) and any alternate data streams. */
1249 ret = win32_capture_streams(path,
1252 params->lookup_table,
1258 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1259 /* Reparse point: set the reparse data (which we read already)
1261 inode->i_not_rpfixed = not_rpfixed;
1262 inode->i_reparse_tag = le32_to_cpu(*(u32*)rpbuf);
1263 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1264 params->lookup_table);
1265 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1266 /* Directory (not a reparse point) --- recurse to children */
1267 ret = win32_recurse_directory(root,
1281 free_dentry_tree(root, params->lookup_table);
1286 win32_do_capture_warnings(const struct win32_capture_state *state,
1287 int add_image_flags)
1289 if (state->num_get_sacl_priv_notheld == 0 &&
1290 state->num_get_sd_access_denied == 0)
1294 WARNING("Built dentry tree successfully, but with the following problem(s):");
1295 if (state->num_get_sacl_priv_notheld != 0) {
1296 WARNING("Could not capture SACL (System Access Control List)\n"
1297 " on %lu files or directories.",
1298 state->num_get_sacl_priv_notheld);
1300 if (state->num_get_sd_access_denied != 0) {
1301 WARNING("Could not capture security descriptor at all\n"
1302 " on %lu files or directories.",
1303 state->num_get_sd_access_denied);
1306 "Try running the program as the Administrator to make sure all the\n"
1307 " desired metadata has been captured exactly. However, if you\n"
1308 " do not care about capturing security descriptors correctly, then\n"
1309 " nothing more needs to be done%ls\n",
1310 (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
1311 L", although you might consider\n"
1312 " passing the --no-acls flag to `wimlib-imagex capture' or\n"
1313 " `wimlib-imagex append' to explicitly capture no security\n"
1317 /* Win32 version of capturing a directory tree */
1319 win32_build_dentry_tree(struct wim_dentry **root_ret,
1320 const wchar_t *root_disk_path,
1321 struct add_image_params *params)
1326 struct win32_capture_state state;
1330 path_nchars = wcslen(root_disk_path);
1331 if (path_nchars > 32767)
1332 return WIMLIB_ERR_INVALID_PARAM;
1334 if (GetFileAttributesW(root_disk_path) == INVALID_FILE_ATTRIBUTES &&
1335 GetLastError() == ERROR_FILE_NOT_FOUND)
1337 ERROR("Capture directory \"%ls\" does not exist!",
1339 return WIMLIB_ERR_OPENDIR;
1342 ret = win32_get_file_and_vol_ids(root_disk_path,
1343 ¶ms->capture_root_ino,
1344 ¶ms->capture_root_dev);
1348 win32_get_vol_flags(root_disk_path, &vol_flags);
1350 /* There is no check for overflow later when this buffer is being used!
1351 * But the max path length on NTFS is 32767 characters, and paths need
1352 * to be written specially to even go past 260 characters, so we should
1353 * be okay with 32770 characters. */
1354 path = MALLOC(32770 * sizeof(wchar_t));
1356 return WIMLIB_ERR_NOMEM;
1358 wmemcpy(path, root_disk_path, path_nchars + 1);
1360 memset(&state, 0, sizeof(state));
1361 ret = win32_build_dentry_tree_recursive(root_ret, path,
1362 path_nchars, params,
1366 win32_do_capture_warnings(&state, params->add_image_flags);
1371 win32_extract_try_rpfix(u8 *rpbuf,
1372 const wchar_t *extract_root_realpath,
1373 unsigned extract_root_realpath_nchars)
1375 struct reparse_data rpdata;
1377 size_t target_nchars;
1378 size_t stripped_nchars;
1379 wchar_t *stripped_target;
1380 wchar_t stripped_target_nchars;
1383 utf16lechar *new_target;
1384 utf16lechar *new_print_name;
1385 size_t new_target_nchars;
1386 size_t new_print_name_nchars;
1389 ret = parse_reparse_data(rpbuf, 8 + le16_to_cpu(*(u16*)(rpbuf + 4)),
1394 if (extract_root_realpath[0] == L'\0' ||
1395 extract_root_realpath[1] != L':' ||
1396 extract_root_realpath[2] != L'\\')
1398 ERROR("Can't understand full path format \"%ls\". "
1399 "Try turning reparse point fixups off...",
1400 extract_root_realpath);
1401 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1404 ret = parse_substitute_name(rpdata.substitute_name,
1405 rpdata.substitute_name_nbytes,
1409 stripped_nchars = ret;
1410 target = rpdata.substitute_name;
1411 target_nchars = rpdata.substitute_name_nbytes / sizeof(utf16lechar);
1412 stripped_target = target + 6;
1413 stripped_target_nchars = target_nchars - stripped_nchars;
1415 new_target = alloca((6 + extract_root_realpath_nchars +
1416 stripped_target_nchars) * sizeof(utf16lechar));
1419 if (stripped_nchars == 6) {
1420 /* Include \??\ prefix if it was present before */
1421 wmemcpy(p, L"\\??\\", 4);
1425 /* Print name excludes the \??\ if present. */
1427 if (stripped_nchars != 0) {
1428 /* Get drive letter from real path to extract root, if a drive
1429 * letter was present before. */
1430 *p++ = extract_root_realpath[0];
1431 *p++ = extract_root_realpath[1];
1433 /* Copy the rest of the extract root */
1434 wmemcpy(p, extract_root_realpath + 2, extract_root_realpath_nchars - 2);
1435 p += extract_root_realpath_nchars - 2;
1437 /* Append the stripped target */
1438 wmemcpy(p, stripped_target, stripped_target_nchars);
1439 p += stripped_target_nchars;
1440 new_target_nchars = p - new_target;
1441 new_print_name_nchars = p - new_print_name;
1443 if (new_target_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE ||
1444 new_print_name_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE)
1446 ERROR("Path names too long to do reparse point fixup!");
1447 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1449 rpdata.substitute_name = new_target;
1450 rpdata.substitute_name_nbytes = new_target_nchars * sizeof(utf16lechar);
1451 rpdata.print_name = new_print_name;
1452 rpdata.print_name_nbytes = new_print_name_nchars * sizeof(utf16lechar);
1453 return make_reparse_buffer(&rpdata, rpbuf);
1456 /* Wrapper around the FSCTL_SET_REPARSE_POINT ioctl to set the reparse data on
1457 * an extracted reparse point. */
1459 win32_set_reparse_data(HANDLE h,
1460 const struct wim_inode *inode,
1461 const struct wim_lookup_table_entry *lte,
1462 const wchar_t *path,
1463 const struct apply_args *args)
1466 u8 rpbuf[REPARSE_POINT_MAX_SIZE];
1467 DWORD bytesReturned;
1469 DEBUG("Setting reparse data on \"%ls\"", path);
1471 ret = wim_inode_get_reparse_data(inode, rpbuf);
1475 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX &&
1476 (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1477 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT) &&
1478 !inode->i_not_rpfixed)
1480 ret = win32_extract_try_rpfix(rpbuf,
1481 args->target_realpath,
1482 args->target_realpath_len);
1484 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1487 /* Set the reparse data on the open file using the
1488 * FSCTL_SET_REPARSE_POINT ioctl.
1490 * There are contradictions in Microsoft's documentation for this:
1492 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1493 * lpOverlapped is ignored."
1495 * --- So setting lpOverlapped to NULL is okay since it's ignored.
1497 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1498 * operation returns no output data and lpOutBuffer is NULL,
1499 * DeviceIoControl makes use of lpBytesReturned. After such an
1500 * operation, the value of lpBytesReturned is meaningless."
1502 * --- So lpOverlapped not really ignored, as it affects another
1503 * parameter. This is the actual behavior: lpBytesReturned must be
1504 * specified, even though lpBytesReturned is documented as:
1506 * "Not used with this operation; set to NULL."
1508 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, rpbuf,
1509 8 + le16_to_cpu(*(u16*)(rpbuf + 4)),
1511 &bytesReturned /* lpBytesReturned */,
1512 NULL /* lpOverlapped */))
1514 DWORD err = GetLastError();
1515 ERROR("Failed to set reparse data on \"%ls\"", path);
1517 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1518 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1519 else if (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1520 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT)
1521 return WIMLIB_ERR_LINK;
1523 return WIMLIB_ERR_WRITE;
1528 /* Wrapper around the FSCTL_SET_COMPRESSION ioctl to change the
1529 * FILE_ATTRIBUTE_COMPRESSED flag of a file or directory. */
1531 win32_set_compression_state(HANDLE hFile, USHORT format, const wchar_t *path)
1533 DWORD bytesReturned;
1534 if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1535 &format, sizeof(USHORT),
1537 &bytesReturned, NULL))
1539 /* Could be a warning only, but we only call this if the volume
1540 * supports compression. So I'm calling this an error. */
1541 DWORD err = GetLastError();
1542 ERROR("Failed to set compression flag on \"%ls\"", path);
1544 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1545 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1547 return WIMLIB_ERR_WRITE;
1552 /* Wrapper around FSCTL_SET_SPARSE ioctl to set a file as sparse. */
1554 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1556 DWORD bytesReturned;
1557 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1560 &bytesReturned, NULL))
1562 /* Could be a warning only, but we only call this if the volume
1563 * supports sparse files. So I'm calling this an error. */
1564 DWORD err = GetLastError();
1565 WARNING("Failed to set sparse flag on \"%ls\"", path);
1567 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1568 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1570 return WIMLIB_ERR_WRITE;
1576 * Sets the security descriptor on an extracted file.
1579 win32_set_security_data(const struct wim_inode *inode,
1581 const wchar_t *path,
1582 struct apply_args *args)
1584 PSECURITY_DESCRIPTOR descriptor;
1587 const struct wim_security_data *sd;
1589 SECURITY_INFORMATION securityInformation = 0;
1596 BOOL owner_defaulted;
1597 BOOL group_defaulted;
1599 BOOL dacl_defaulted;
1601 BOOL sacl_defaulted;
1603 sd = wim_const_security_data(args->w);
1604 descriptor = sd->descriptors[inode->i_security_id];
1606 GetSecurityDescriptorOwner(descriptor, &owner, &owner_defaulted);
1608 securityInformation |= OWNER_SECURITY_INFORMATION;
1610 GetSecurityDescriptorGroup(descriptor, &group, &group_defaulted);
1612 securityInformation |= GROUP_SECURITY_INFORMATION;
1614 GetSecurityDescriptorDacl(descriptor, &dacl_present,
1615 &dacl, &dacl_defaulted);
1617 securityInformation |= DACL_SECURITY_INFORMATION;
1619 GetSecurityDescriptorSacl(descriptor, &sacl_present,
1620 &sacl, &sacl_defaulted);
1622 securityInformation |= SACL_SECURITY_INFORMATION;
1625 if (securityInformation == 0)
1627 if (SetSecurityInfo(hFile, SE_FILE_OBJECT,
1628 securityInformation, owner, group, dacl, sacl))
1630 err = GetLastError();
1631 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1634 case ERROR_PRIVILEGE_NOT_HELD:
1635 if (securityInformation & SACL_SECURITY_INFORMATION) {
1636 n = args->num_set_sacl_priv_notheld++;
1637 securityInformation &= ~SACL_SECURITY_INFORMATION;
1639 if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1641 "We don't have enough privileges to set the full security\n"
1642 " descriptor on \"%ls\"!\n", path);
1643 if (args->num_set_sd_access_denied +
1644 args->num_set_sacl_priv_notheld == 1)
1646 WARNING("%ls", apply_access_denied_msg);
1648 WARNING("Re-trying with SACL omitted.\n", path);
1649 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1651 "Suppressing further 'privileges not held' error messages when setting\n"
1652 " security descriptors.");
1657 case ERROR_INVALID_OWNER:
1658 case ERROR_ACCESS_DENIED:
1659 n = args->num_set_sd_access_denied++;
1660 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1661 WARNING("Failed to set security descriptor on \"%ls\": "
1662 "Access denied!\n", path);
1663 if (args->num_set_sd_access_denied +
1664 args->num_set_sacl_priv_notheld == 1)
1666 WARNING("%ls", apply_access_denied_msg);
1668 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1670 "Suppressing further access denied error messages when setting\n"
1671 " security descriptors");
1676 ERROR("Failed to set security descriptor on \"%ls\"", path);
1678 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1679 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1681 return WIMLIB_ERR_WRITE;
1687 win32_extract_chunk(const void *buf, size_t len, void *arg)
1689 HANDLE hStream = arg;
1691 DWORD nbytes_written;
1692 wimlib_assert(len <= 0xffffffff);
1694 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1695 nbytes_written != len)
1697 DWORD err = GetLastError();
1698 ERROR("WriteFile(): write error");
1700 return WIMLIB_ERR_WRITE;
1706 do_win32_extract_stream(HANDLE hStream, const struct wim_lookup_table_entry *lte)
1708 return extract_wim_resource(lte, wim_resource_size(lte),
1709 win32_extract_chunk, hStream);
1712 struct win32_encrypted_extract_ctx {
1713 const struct wim_lookup_table_entry *lte;
1718 win32_encrypted_import_cb(unsigned char *data, void *_ctx,
1719 unsigned long *len_p)
1721 struct win32_encrypted_extract_ctx *ctx = _ctx;
1722 unsigned long len = *len_p;
1723 const struct wim_lookup_table_entry *lte = ctx->lte;
1725 len = min(len, wim_resource_size(lte) - ctx->offset);
1727 if (read_partial_wim_resource_into_buf(lte, len, ctx->offset, data, false))
1728 return ERROR_READ_FAULT;
1732 return ERROR_SUCCESS;
1735 /* Create an encrypted file and extract the raw encrypted data to it.
1737 * @path: Path to encrypted file to create.
1738 * @lte: WIM lookup_table entry for the raw encrypted data.
1740 * This is separate from do_win32_extract_stream() because the WIM is supposed
1741 * to contain the *raw* encrypted data, which needs to be extracted ("imported")
1742 * using the special APIs OpenEncryptedFileRawW(), WriteEncryptedFileRaw(), and
1743 * CloseEncryptedFileRaw().
1745 * Returns 0 on success; nonzero on failure.
1748 do_win32_extract_encrypted_stream(const wchar_t *path,
1749 const struct wim_lookup_table_entry *lte)
1754 DEBUG("Opening file \"%ls\" to extract raw encrypted data", path);
1756 ret = OpenEncryptedFileRawW(path, CREATE_FOR_IMPORT, &file_ctx);
1758 ERROR("Failed to open \"%ls\" to write raw encrypted data", path);
1760 return WIMLIB_ERR_OPEN;
1764 struct win32_encrypted_extract_ctx ctx;
1768 ret = WriteEncryptedFileRaw(win32_encrypted_import_cb, &ctx, file_ctx);
1769 if (ret == ERROR_SUCCESS) {
1772 ret = WIMLIB_ERR_WRITE;
1773 ERROR("Failed to extract encrypted file \"%ls\"", path);
1776 CloseEncryptedFileRaw(file_ctx);
1781 path_is_root_of_drive(const wchar_t *path)
1786 if (*path != L'/' && *path != L'\\') {
1787 if (*(path + 1) == L':')
1792 while (*path == L'/' || *path == L'\\')
1794 return (*path == L'\0');
1798 win32_mask_attributes(DWORD i_attributes)
1800 return i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1801 FILE_ATTRIBUTE_COMPRESSED |
1802 FILE_ATTRIBUTE_REPARSE_POINT |
1803 FILE_ATTRIBUTE_DIRECTORY |
1804 FILE_ATTRIBUTE_ENCRYPTED |
1805 FILE_FLAG_DELETE_ON_CLOSE |
1806 FILE_FLAG_NO_BUFFERING |
1807 FILE_FLAG_OPEN_NO_RECALL |
1808 FILE_FLAG_OVERLAPPED |
1809 FILE_FLAG_RANDOM_ACCESS |
1810 /*FILE_FLAG_SESSION_AWARE |*/
1811 FILE_FLAG_SEQUENTIAL_SCAN |
1812 FILE_FLAG_WRITE_THROUGH);
1816 win32_get_create_flags_and_attributes(DWORD i_attributes)
1819 * Some attributes cannot be set by passing them to CreateFile(). In
1822 * FILE_ATTRIBUTE_DIRECTORY:
1823 * CreateDirectory() must be called instead of CreateFile().
1825 * FILE_ATTRIBUTE_SPARSE_FILE:
1827 * See: win32_set_sparse().
1829 * FILE_ATTRIBUTE_COMPRESSED:
1830 * Not clear from the documentation, but apparently this needs an
1832 * See: win32_set_compressed().
1834 * FILE_ATTRIBUTE_REPARSE_POINT:
1835 * Needs an ioctl, with the reparse data specified.
1836 * See: win32_set_reparse_data().
1838 * In addition, clear any file flags in the attributes that we don't
1839 * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1840 * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1842 return win32_mask_attributes(i_attributes) |
1843 FILE_FLAG_OPEN_REPARSE_POINT |
1844 FILE_FLAG_BACKUP_SEMANTICS;
1847 /* Set compression and/or sparse attributes on a stream, if supported by the
1850 win32_set_special_stream_attributes(HANDLE hFile, const struct wim_inode *inode,
1851 struct wim_lookup_table_entry *unnamed_stream_lte,
1852 const wchar_t *path, unsigned vol_flags)
1856 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1857 if (vol_flags & FILE_FILE_COMPRESSION) {
1858 ret = win32_set_compression_state(hFile,
1859 COMPRESSION_FORMAT_DEFAULT,
1864 DEBUG("Cannot set compression attribute on \"%ls\": "
1865 "volume does not support transparent compression",
1870 if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1871 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1872 DEBUG("Setting sparse flag on \"%ls\"", path);
1873 ret = win32_set_sparse(hFile, path);
1877 DEBUG("Cannot set sparse attribute on \"%ls\": "
1878 "volume does not support sparse files",
1885 /* Pre-create directories; extract encrypted streams */
1887 win32_begin_extract_unnamed_stream(const struct wim_inode *inode,
1888 const struct wim_lookup_table_entry *lte,
1889 const wchar_t *path,
1890 DWORD *creationDisposition_ret,
1891 unsigned int vol_flags)
1896 /* Directories must be created with CreateDirectoryW(). Then the call
1897 * to CreateFileW() will merely open the directory that was already
1898 * created rather than creating a new file. */
1899 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY &&
1900 !path_is_root_of_drive(path)) {
1901 if (!CreateDirectoryW(path, NULL)) {
1902 err = GetLastError();
1903 if (err != ERROR_ALREADY_EXISTS) {
1904 ERROR("Failed to create directory \"%ls\"",
1907 return WIMLIB_ERR_MKDIR;
1910 DEBUG("Created directory \"%ls\"", path);
1911 *creationDisposition_ret = OPEN_EXISTING;
1913 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED &&
1914 vol_flags & FILE_SUPPORTS_ENCRYPTION)
1916 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1917 unsigned remaining_sharing_violations = 100;
1918 while (!EncryptFile(path)) {
1919 if (remaining_sharing_violations &&
1920 err == ERROR_SHARING_VIOLATION)
1922 WARNING("Couldn't encrypt directory \"%ls\" "
1923 "due to sharing violation; re-trying "
1924 "after 100 ms", path);
1926 remaining_sharing_violations--;
1928 err = GetLastError();
1929 ERROR("Failed to encrypt directory \"%ls\"",
1932 return WIMLIB_ERR_WRITE;
1936 ret = do_win32_extract_encrypted_stream(path, lte);
1939 DEBUG("Extracted encrypted file \"%ls\"", path);
1941 *creationDisposition_ret = OPEN_EXISTING;
1944 /* Set file attributes if we created the file. Otherwise, we haven't
1945 * created the file set and we will set the attributes in the call to
1948 * The FAT filesystem does not let you change the attributes of the root
1949 * directory, so treat that as a special case and do not set attributes.
1951 if (*creationDisposition_ret == OPEN_EXISTING &&
1952 !path_is_root_of_drive(path))
1954 if (!SetFileAttributesW(path,
1955 win32_mask_attributes(inode->i_attributes)))
1957 err = GetLastError();
1958 ERROR("Failed to set attributes on \"%ls\"", path);
1960 return WIMLIB_ERR_WRITE;
1966 /* Set security descriptor and extract stream data or reparse data (skip the
1967 * unnamed data stream of encrypted files, which was already extracted). */
1969 win32_finish_extract_stream(HANDLE h, const struct wim_dentry *dentry,
1970 const struct wim_lookup_table_entry *lte,
1971 const wchar_t *stream_path,
1972 const wchar_t *stream_name_utf16,
1973 struct apply_args *args)
1976 const struct wim_inode *inode = dentry->d_inode;
1977 const wchar_t *short_name;
1978 if (stream_name_utf16 == NULL) {
1979 /* Unnamed stream. */
1981 /* Set security descriptor, unless the extract_flags indicate
1982 * not to or the volume does not supported it. Note that this
1983 * is only done when the unnamed stream is being extracted, as
1984 * security descriptors are per-file and not per-stream. */
1985 if (inode->i_security_id >= 0 &&
1986 !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
1987 && (args->vol_flags & FILE_PERSISTENT_ACLS))
1989 ret = win32_set_security_data(inode, h, stream_path, args);
1994 /* Handle reparse points. The data for them needs to be set
1995 * using a special ioctl. Note that the reparse point may have
1996 * been created using CreateFileW() in the case of
1997 * non-directories or CreateDirectoryW() in the case of
1998 * directories; but the ioctl works either way. Also, it is
1999 * only this step that actually sets the
2000 * FILE_ATTRIBUTE_REPARSE_POINT, as it is not valid to set it
2001 * using SetFileAttributesW() or CreateFileW().
2003 * If the volume does not support reparse points we simply
2004 * ignore the reparse data. (N.B. the code currently doesn't
2005 * actually reach this case because reparse points are skipped
2006 * entirely on such volumes.) */
2007 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2008 if (args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
2009 ret = win32_set_reparse_data(h, inode,
2015 DEBUG("Cannot set reparse data on \"%ls\": volume "
2016 "does not support reparse points", stream_path);
2018 } else if (lte != NULL &&
2019 !(args->vol_flags & FILE_SUPPORTS_ENCRYPTION &&
2020 inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2022 /* Extract the data of the unnamed stream, unless the
2023 * lookup table entry is NULL (indicating an empty
2024 * stream for which no data needs to be extracted), or
2025 * the stream is encrypted and therefore was already
2026 * extracted as a special case. */
2027 ret = do_win32_extract_stream(h, lte);
2032 if (dentry_has_short_name(dentry))
2033 short_name = dentry->short_name;
2036 /* Set short name */
2037 if (!SetFileShortNameW(h, short_name)) {
2039 DWORD err = GetLastError();
2040 ERROR("Could not set short name on \"%ls\"", stream_path);
2045 /* Extract the data for a named data stream. */
2047 DEBUG("Extracting named data stream \"%ls\" (len = %"PRIu64")",
2048 stream_path, wim_resource_size(lte));
2049 ret = do_win32_extract_stream(h, lte);
2056 win32_decrypt_file(HANDLE open_handle, const wchar_t *path)
2059 /* We cannot call DecryptFileW() while there is an open handle to the
2060 * file. So close it first. */
2061 if (!CloseHandle(open_handle)) {
2062 err = GetLastError();
2063 ERROR("Failed to close handle for \"%ls\"", path);
2065 return WIMLIB_ERR_WRITE;
2067 if (!DecryptFileW(path, 0 /* reserved parameter; set to 0 */)) {
2068 err = GetLastError();
2069 ERROR("Failed to decrypt file \"%ls\"", path);
2071 return WIMLIB_ERR_WRITE;
2077 * Create and extract a stream to a file, or create a directory, using the
2080 * This handles reparse points, directories, alternate data streams, encrypted
2081 * files, compressed files, etc.
2083 * @dentry: WIM dentry for the file or directory being extracted.
2085 * @path: Path to extract the file to.
2087 * @stream_name_utf16:
2088 * Name of the stream, or NULL if the stream is unnamed. This will
2089 * be called with a NULL stream_name_utf16 before any non-NULL
2090 * stream_name_utf16's.
2092 * @lte: WIM lookup table entry for the stream. May be NULL to indicate
2093 * a stream of length 0.
2095 * @args: Additional apply context, including flags indicating supported
2098 * Returns 0 on success; nonzero on failure.
2101 win32_extract_stream(const struct wim_dentry *dentry,
2102 const wchar_t *path,
2103 const wchar_t *stream_name_utf16,
2104 struct wim_lookup_table_entry *lte,
2105 struct apply_args *args)
2107 wchar_t *stream_path;
2111 DWORD creationDisposition = CREATE_ALWAYS;
2112 DWORD requestedAccess;
2113 BY_HANDLE_FILE_INFORMATION file_info;
2114 unsigned remaining_sharing_violations = 1000;
2115 const struct wim_inode *inode = dentry->d_inode;
2117 if (stream_name_utf16) {
2118 /* Named stream. Create a buffer that contains the UTF-16LE
2119 * string [./]path:stream_name_utf16. This is needed to
2120 * create and open the stream using CreateFileW(). I'm not
2121 * aware of any other APIs to do this. Note: the '$DATA' suffix
2122 * seems to be unneeded. Additional note: a "./" prefix needs
2123 * to be added when the path is not absolute to avoid ambiguity
2124 * with drive letters. */
2125 size_t stream_path_nchars;
2127 size_t stream_name_nchars;
2128 const wchar_t *prefix;
2130 path_nchars = wcslen(path);
2131 stream_name_nchars = wcslen(stream_name_utf16);
2132 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
2133 if (path[0] != cpu_to_le16(L'\0') &&
2134 path[0] != cpu_to_le16(L'/') &&
2135 path[0] != cpu_to_le16(L'\\') &&
2136 path[1] != cpu_to_le16(L':'))
2139 stream_path_nchars += 2;
2143 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
2144 swprintf(stream_path, L"%ls%ls:%ls",
2145 prefix, path, stream_name_utf16);
2147 /* Unnamed stream; its path is just the path to the file itself.
2149 stream_path = (wchar_t*)path;
2151 ret = win32_begin_extract_unnamed_stream(inode, lte, path,
2152 &creationDisposition,
2158 DEBUG("Opening \"%ls\"", stream_path);
2159 /* DELETE access is needed for SetFileShortNameW(), for some reason. */
2160 requestedAccess = GENERIC_READ | GENERIC_WRITE | DELETE |
2161 ACCESS_SYSTEM_SECURITY;
2163 /* Open the stream to be extracted. Depending on what we have set
2164 * creationDisposition to, we may be creating this for the first time,
2165 * or we may be opening on existing stream we already created using
2166 * CreateDirectoryW() or OpenEncryptedFileRawW(). */
2167 h = CreateFileW(stream_path,
2171 creationDisposition,
2172 win32_get_create_flags_and_attributes(inode->i_attributes),
2174 if (h == INVALID_HANDLE_VALUE) {
2175 err = GetLastError();
2176 if (err == ERROR_ACCESS_DENIED &&
2177 path_is_root_of_drive(stream_path))
2182 if ((err == ERROR_PRIVILEGE_NOT_HELD ||
2183 err == ERROR_ACCESS_DENIED) &&
2184 (requestedAccess & ACCESS_SYSTEM_SECURITY))
2186 /* Try opening the file again without privilege to
2188 requestedAccess &= ~ACCESS_SYSTEM_SECURITY;
2189 goto try_open_again;
2191 if (err == ERROR_SHARING_VIOLATION) {
2192 if (remaining_sharing_violations) {
2193 --remaining_sharing_violations;
2194 /* This can happen when restoring encrypted directories
2195 * for some reason. Probably a bug in EncryptFile(). */
2196 WARNING("Couldn't open \"%ls\" due to sharing violation; "
2197 "re-trying after 100ms", stream_path);
2199 goto try_open_again;
2201 ERROR("Too many sharing violations; giving up...");
2204 if (creationDisposition == OPEN_EXISTING)
2205 ERROR("Failed to open \"%ls\"", stream_path);
2207 ERROR("Failed to create \"%ls\"", stream_path);
2210 ret = WIMLIB_ERR_OPEN;
2214 /* Check the attributes of the file we just opened, and remove
2215 * encryption or compression if either was set by default but is not
2216 * supposed to be set based on the WIM inode attributes. */
2217 if (!GetFileInformationByHandle(h, &file_info)) {
2218 err = GetLastError();
2219 ERROR("Failed to get attributes of \"%ls\"", stream_path);
2221 ret = WIMLIB_ERR_STAT;
2222 goto fail_close_handle;
2225 /* Remove encryption? */
2226 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED &&
2227 !(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2229 /* File defaulted to encrypted due to being in an encrypted
2230 * directory, but is not actually supposed to be encrypted.
2232 * This is a workaround, because I'm not aware of any way to
2233 * directly (e.g. with CreateFileW()) create an unencrypted file
2234 * in a directory with FILE_ATTRIBUTE_ENCRYPTED set. */
2235 ret = win32_decrypt_file(h, stream_path);
2237 goto fail; /* win32_decrypt_file() closed the handle. */
2238 creationDisposition = OPEN_EXISTING;
2239 goto try_open_again;
2242 /* Remove compression? */
2243 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED &&
2244 !(inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED))
2246 /* Similar to the encrypted case, above, if the file defaulted
2247 * to compressed due to being in an compressed directory, but is
2248 * not actually supposed to be compressed, explicitly set the
2249 * compression format to COMPRESSION_FORMAT_NONE. */
2250 ret = win32_set_compression_state(h, COMPRESSION_FORMAT_NONE,
2253 goto fail_close_handle;
2256 /* Set compression and/or sparse attributes if needed */
2257 ret = win32_set_special_stream_attributes(h, inode, lte, path,
2261 goto fail_close_handle;
2263 /* At this point we have at least created the needed stream with the
2264 * appropriate attributes. We have yet to set the appropriate security
2265 * descriptor and actually extract the stream data (other than for
2266 * extracted files, which were already extracted).
2267 * win32_finish_extract_stream() handles these additional steps. */
2268 ret = win32_finish_extract_stream(h, dentry, lte, stream_path,
2269 stream_name_utf16, args);
2271 goto fail_close_handle;
2273 /* Done extracting the stream. Close the handle and return. */
2274 DEBUG("Closing \"%ls\"", stream_path);
2275 if (!CloseHandle(h)) {
2276 err = GetLastError();
2277 ERROR("Failed to close \"%ls\"", stream_path);
2279 ret = WIMLIB_ERR_WRITE;
2287 ERROR("Error extracting \"%ls\"", stream_path);
2293 * Creates a file, directory, or reparse point and extracts all streams to it
2294 * (unnamed data stream and/or reparse point stream, plus any alternate data
2295 * streams). Handles sparse, compressed, and/or encrypted files.
2297 * @dentry: WIM dentry for this file or directory.
2298 * @path: UTF-16LE external path to extract the inode to.
2299 * @args: Additional extraction context.
2301 * Returns 0 on success; nonzero on failure.
2304 win32_extract_streams(const struct wim_dentry *dentry,
2305 const wchar_t *path, struct apply_args *args)
2307 struct wim_lookup_table_entry *unnamed_lte;
2309 const struct wim_inode *inode = dentry->d_inode;
2311 /* First extract the unnamed stream. */
2313 unnamed_lte = inode_unnamed_lte_resolved(inode);
2314 ret = win32_extract_stream(dentry, path, NULL, unnamed_lte, args);
2318 /* Extract any named streams, if supported by the volume. */
2320 if (!(args->vol_flags & FILE_NAMED_STREAMS))
2322 for (u16 i = 0; i < inode->i_num_ads; i++) {
2323 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
2325 /* Skip the unnamed stream if it's in the ADS entries (we
2326 * already extracted it...) */
2327 if (ads_entry->stream_name_nbytes == 0)
2330 /* Skip special UNIX data entries (see documentation for
2331 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
2332 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
2333 && !memcmp(ads_entry->stream_name,
2334 WIMLIB_UNIX_DATA_TAG_UTF16LE,
2335 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
2338 /* Extract the named stream */
2339 ret = win32_extract_stream(dentry,
2341 ads_entry->stream_name,
2351 /* If not done already, load the supported feature flags for the volume onto
2352 * which the image is being extracted, and warn the user about any missing
2353 * features that could be important. */
2355 win32_check_vol_flags(const wchar_t *output_path, struct apply_args *args)
2357 if (args->have_vol_flags)
2360 win32_get_vol_flags(output_path, &args->vol_flags);
2361 args->have_vol_flags = true;
2362 /* Warn the user about data that may not be extracted. */
2363 if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
2364 WARNING("Volume does not support sparse files!\n"
2365 " Sparse files will be extracted as non-sparse.");
2366 if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2367 WARNING("Volume does not support reparse points!\n"
2368 " Reparse point data will not be extracted.");
2369 if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
2370 WARNING("Volume does not support named data streams!\n"
2371 " Named data streams will not be extracted.");
2373 if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
2374 WARNING("Volume does not support encryption!\n"
2375 " Encrypted files will be extracted as raw data.");
2377 if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
2378 WARNING("Volume does not support transparent compression!\n"
2379 " Compressed files will be extracted as non-compressed.");
2381 if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
2382 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
2383 ERROR("Strict ACLs requested, but the volume does not "
2385 return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
2387 WARNING("Volume does not support persistent ACLS!\n"
2388 " File permissions will not be extracted.");
2395 * Try extracting a hard link.
2397 * @output_path: Path to link to be extracted.
2399 * @inode: WIM inode that the link is to; inode->i_extracted_file
2400 * the path to a name of the file that has already been
2401 * extracted (we use this to create the hard link).
2403 * @args: Additional apply context, used here to keep track of
2404 * the number of times creating a hard link failed due to
2405 * ERROR_INVALID_FUNCTION. This error should indicate that hard
2406 * links are not supported by the volume, and we would like to
2407 * warn the user a few times, but not too many times.
2409 * Returns 0 if the hard link was successfully extracted. Returns
2410 * WIMLIB_ERR_LINK (> 0) if an error occurred, other than hard links possibly
2411 * being unsupported by the volume. Returns a negative value if creating the
2412 * hard link failed due to ERROR_INVALID_FUNCTION.
2415 win32_try_hard_link(const wchar_t *output_path, const struct wim_inode *inode,
2416 struct apply_args *args)
2420 /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
2421 * but it's only available on Windows 7 and later. So no use
2422 * even checking it, really. Instead, CreateHardLinkW() will
2423 * apparently return ERROR_INVALID_FUNCTION if the volume does
2424 * not support hard links. */
2425 DEBUG("Creating hard link \"%ls => %ls\"",
2426 output_path, inode->i_extracted_file);
2427 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
2430 err = GetLastError();
2431 if (err != ERROR_INVALID_FUNCTION) {
2432 ERROR("Can't create hard link \"%ls => %ls\"",
2433 output_path, inode->i_extracted_file);
2435 return WIMLIB_ERR_LINK;
2437 args->num_hard_links_failed++;
2438 if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
2439 WARNING("Can't create hard link \"%ls => %ls\":\n"
2440 " Volume does not support hard links!\n"
2441 " Falling back to extracting a copy of the file.",
2442 output_path, inode->i_extracted_file);
2443 } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
2444 WARNING("Suppressing further hard linking warnings...");
2450 /* Extract a file, directory, reparse point, or hard link to an
2451 * already-extracted file using the Win32 API */
2453 win32_do_apply_dentry(const wchar_t *output_path,
2454 size_t output_path_num_chars,
2455 struct wim_dentry *dentry,
2456 struct apply_args *args)
2459 struct wim_inode *inode = dentry->d_inode;
2461 ret = win32_check_vol_flags(output_path, args);
2464 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
2465 /* Linked file, with another name already extracted. Create a
2467 ret = win32_try_hard_link(output_path, inode, args);
2470 /* Negative return value from win32_try_hard_link() indicates
2471 * that hard links are probably not supported by the volume.
2472 * Fall back to extracting a copy of the file. */
2475 /* If this is a reparse point and the volume does not support reparse
2476 * points, just skip it completely. */
2477 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2478 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2480 WARNING("Skipping extraction of reparse point \"%ls\":\n"
2481 " Not supported by destination filesystem",
2484 /* Create the file, directory, or reparse point, and extract the
2486 ret = win32_extract_streams(dentry, output_path, args);
2490 if (inode->i_extracted_file == NULL) {
2491 const struct wim_lookup_table_entry *lte;
2493 /* Tally bytes extracted, including all alternate data streams,
2494 * unless we extracted a hard link (or, at least extracted a
2495 * name that was supposed to be a hard link) */
2496 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
2497 lte = inode_stream_lte_resolved(inode, i);
2499 args->progress.extract.completed_bytes +=
2500 wim_resource_size(lte);
2502 if (inode->i_nlink > 1) {
2503 /* Save extracted path for a later call to
2504 * CreateHardLinkW() if this inode has multiple links.
2506 inode->i_extracted_file = WSTRDUP(output_path);
2507 if (!inode->i_extracted_file)
2508 return WIMLIB_ERR_NOMEM;
2514 /* Set timestamps on an extracted file using the Win32 API */
2516 win32_do_apply_dentry_timestamps(const wchar_t *path,
2517 size_t path_num_chars,
2518 const struct wim_dentry *dentry,
2519 const struct apply_args *args)
2523 const struct wim_inode *inode = dentry->d_inode;
2525 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2526 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2528 /* Skip reparse points not extracted */
2532 /* Windows doesn't let you change the timestamps of the root directory
2533 * (at least on FAT, which is dumb but expected since FAT doesn't store
2534 * any metadata about the root directory...) */
2535 if (path_is_root_of_drive(path))
2538 DEBUG("Opening \"%ls\" to set timestamps", path);
2539 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
2540 if (h == INVALID_HANDLE_VALUE) {
2541 err = GetLastError();
2545 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
2546 .dwHighDateTime = inode->i_creation_time >> 32};
2547 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
2548 .dwHighDateTime = inode->i_last_access_time >> 32};
2549 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
2550 .dwHighDateTime = inode->i_last_write_time >> 32};
2552 DEBUG("Calling SetFileTime() on \"%ls\"", path);
2553 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
2554 err = GetLastError();
2558 DEBUG("Closing \"%ls\"", path);
2559 if (!CloseHandle(h)) {
2560 err = GetLastError();
2565 /* Only warn if setting timestamps failed; still return 0. */
2566 WARNING("Can't set timestamps on \"%ls\"", path);
2572 /* Replacement for POSIX fsync() */
2579 h = (HANDLE)_get_osfhandle(fd);
2580 if (h == INVALID_HANDLE_VALUE) {
2581 err = GetLastError();
2582 ERROR("Could not get Windows handle for file descriptor");
2587 if (!FlushFileBuffers(h)) {
2588 err = GetLastError();
2589 ERROR("Could not flush file buffers to disk");
2597 /* Use the Win32 API to get the number of processors */
2599 win32_get_number_of_processors()
2601 SYSTEM_INFO sysinfo;
2602 GetSystemInfo(&sysinfo);
2603 return sysinfo.dwNumberOfProcessors;
2606 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
2607 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
2608 * really does the right thing under all circumstances. */
2610 realpath(const wchar_t *path, wchar_t *resolved_path)
2613 wimlib_assert(resolved_path == NULL);
2616 ret = GetFullPathNameW(path, 0, NULL, NULL);
2618 err = GetLastError();
2622 resolved_path = TMALLOC(ret);
2625 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2627 err = GetLastError();
2628 free(resolved_path);
2629 resolved_path = NULL;
2637 return resolved_path;
2640 /* rename() on Windows fails if the destination file exists. And we need to
2641 * make it work on wide characters. Fix it. */
2643 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2645 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2648 /* As usual, the possible error values are not documented */
2649 DWORD err = GetLastError();
2650 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2658 /* Replacement for POSIX fnmatch() (partial functionality only) */
2660 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2662 if (PathMatchSpecW(string, pattern))
2668 /* truncate() replacement */
2670 win32_truncate_replacement(const wchar_t *path, off_t size)
2672 DWORD err = NO_ERROR;
2673 LARGE_INTEGER liOffset;
2675 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2676 if (h == INVALID_HANDLE_VALUE)
2679 liOffset.QuadPart = size;
2680 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2681 goto fail_close_handle;
2683 if (!SetEndOfFile(h))
2684 goto fail_close_handle;
2689 err = GetLastError();
2692 if (err == NO_ERROR)
2693 err = GetLastError();
2694 ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2701 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2702 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2703 * linked in by Visual Studio...?). */
2705 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2707 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2709 pthread_mutex_lock(&strerror_lock);
2710 mbstowcs(buf, strerror(errnum), buflen);
2711 buf[buflen - 1] = '\0';
2712 pthread_mutex_unlock(&strerror_lock);
2716 #endif /* __WIN32__ */