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)
705 struct reparse_data rpdata;
708 enum rp_status rp_status;
710 rpbuflen = *rpbuflen_p;
711 ret = parse_reparse_data(rpbuf, rpbuflen, &rpdata);
715 rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
716 &rpdata.substitute_name_nbytes,
719 le32_to_cpu(*(u32*)rpbuf));
720 if (rp_status & RP_FIXED) {
721 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
722 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
723 wmemcpy(substitute_name_copy, rpdata.substitute_name,
724 rpdata.substitute_name_nbytes / 2);
725 rpdata.substitute_name = substitute_name_copy;
726 rpdata.print_name = substitute_name_copy;
727 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
728 if (rp_status == RP_FIXED_FULLPATH) {
729 /* "full path", meaning \??\ prefixed. We should not
730 * include this prefix in the print name, as it is
731 * apparently meant for the filesystem driver only. */
732 rpdata.print_name += 4;
733 rpdata.print_name_nbytes -= 8;
735 ret = make_reparse_buffer(&rpdata, rpbuf);
747 * Loads the reparse point data from a reparse point into memory, optionally
748 * fixing the targets of absolute symbolic links and junction points to be
749 * relative to the root of capture.
751 * @hFile: Open handle to the reparse point.
752 * @path: Path to the reparse point. Used for error messages only.
753 * @params: Additional parameters, including whether to do reparse point fixups
755 * @rpbuf: Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
756 * the reparse point buffer will be loaded.
757 * @rpbuflen_ret: On success, the length of the reparse point buffer in bytes
758 * is written to this location.
761 * On success, returns an `enum rp_status' value that indicates if and/or
762 * how the reparse point fixup was done.
764 * On failure, returns a negative value that is a negated WIMLIB_ERR_*
768 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
769 struct add_image_params *params,
770 u8 *rpbuf, u16 *rpbuflen_ret)
777 DEBUG("Loading reparse data from \"%ls\"", path);
778 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
779 NULL, /* "Not used with this operation; set to NULL" */
780 0, /* "Not used with this operation; set to 0" */
781 rpbuf, /* "A pointer to a buffer that
782 receives the reparse point data */
783 REPARSE_POINT_MAX_SIZE, /* "The size of the output
788 DWORD err = GetLastError();
789 ERROR("Failed to get reparse data of \"%ls\"", path);
791 return -WIMLIB_ERR_READ;
793 if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
794 ERROR("Reparse data on \"%ls\" is invalid", path);
795 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
798 rpbuflen = bytesReturned;
799 reparse_tag = le32_to_cpu(*(u32*)rpbuf);
800 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX &&
801 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
802 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
804 /* Try doing reparse point fixup */
805 ret = win32_capture_try_rpfix(rpbuf,
807 params->capture_root_ino,
808 params->capture_root_dev);
812 *rpbuflen_ret = rpbuflen;
817 win32_tally_encrypted_size_cb(unsigned char *_data, void *_ctx,
821 return ERROR_SUCCESS;
825 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
832 err = OpenEncryptedFileRawW(path, 0, &file_ctx);
833 if (err != ERROR_SUCCESS) {
834 ERROR("Failed to open encrypted file \"%ls\" for raw read", path);
836 return WIMLIB_ERR_OPEN;
838 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
840 if (err != ERROR_SUCCESS) {
841 ERROR("Failed to read raw encrypted data from \"%ls\"", path);
843 ret = WIMLIB_ERR_READ;
847 CloseEncryptedFileRaw(file_ctx);
851 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
852 * stream); calculates its SHA1 message digest and either creates a `struct
853 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
854 * wim_lookup_table_entry' for an identical stream.
856 * @path: Path to the file (UTF-16LE).
858 * @path_num_chars: Number of 2-byte characters in @path.
860 * @inode: WIM inode to save the stream into.
862 * @lookup_table: Stream lookup table for the WIM.
864 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
867 * Returns 0 on success; nonzero on failure.
870 win32_capture_stream(const wchar_t *path,
871 size_t path_num_chars,
872 struct wim_inode *inode,
873 struct wim_lookup_table *lookup_table,
874 WIN32_FIND_STREAM_DATA *dat)
876 struct wim_ads_entry *ads_entry;
877 struct wim_lookup_table_entry *lte;
879 wchar_t *stream_name, *colon;
880 size_t stream_name_nchars;
881 bool is_named_stream;
884 size_t spath_buf_nbytes;
885 const wchar_t *relpath_prefix;
886 const wchar_t *colonchar;
888 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
890 /* The stream name should be returned as :NAME:TYPE */
891 stream_name = dat->cStreamName;
892 if (*stream_name != L':')
893 goto out_invalid_stream_name;
895 colon = wcschr(stream_name, L':');
897 goto out_invalid_stream_name;
899 if (wcscmp(colon + 1, L"$DATA")) {
900 /* Not a DATA stream */
907 stream_name_nchars = colon - stream_name;
908 is_named_stream = (stream_name_nchars != 0);
910 if (is_named_stream) {
911 /* Allocate an ADS entry for the named stream. */
912 ads_entry = inode_add_ads_utf16le(inode, stream_name,
913 stream_name_nchars * sizeof(wchar_t));
915 ret = WIMLIB_ERR_NOMEM;
920 /* If zero length stream, no lookup table entry needed. */
921 if ((u64)dat->StreamSize.QuadPart == 0) {
926 /* Create a UTF-16LE string @spath that gives the filename, then a
927 * colon, then the stream name. Or, if it's an unnamed stream, just the
928 * filename. It is MALLOC()'ed so that it can be saved in the
929 * wim_lookup_table_entry if needed.
931 * As yet another special case, relative paths need to be changed to
932 * begin with an explicit "./" so that, for example, a file t:ads, where
933 * :ads is the part we added, is not interpreted as a file on the t:
935 spath_nchars = path_num_chars;
936 relpath_prefix = L"";
938 if (is_named_stream) {
939 spath_nchars += 1 + stream_name_nchars;
941 if (path_num_chars == 1 &&
946 relpath_prefix = L"./";
950 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
951 spath = MALLOC(spath_buf_nbytes);
953 swprintf(spath, L"%ls%ls%ls%ls",
954 relpath_prefix, path, colonchar, stream_name);
956 /* Make a new wim_lookup_table_entry */
957 lte = new_lookup_table_entry();
959 ret = WIMLIB_ERR_NOMEM;
962 lte->file_on_disk = spath;
964 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
966 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
967 ret = win32_get_encrypted_file_size(path, &encrypted_size);
970 lte->resource_entry.original_size = encrypted_size;
972 lte->resource_location = RESOURCE_WIN32;
973 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
977 if (is_named_stream) {
978 stream_id = ads_entry->stream_id;
979 ads_entry->lte = lte;
984 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
990 out_invalid_stream_name:
991 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
992 ret = WIMLIB_ERR_READ;
996 /* Scans a Win32 file for unnamed and named data streams (not reparse point
999 * @path: Path to the file (UTF-16LE).
1001 * @path_num_chars: Number of 2-byte characters in @path.
1003 * @inode: WIM inode to save the stream into.
1005 * @lookup_table: Stream lookup table for the WIM.
1007 * @file_size: Size of unnamed data stream. (Used only if alternate
1008 * data streams API appears to be unavailable.)
1010 * @vol_flags: Flags that specify features of the volume being
1013 * Returns 0 on success; nonzero on failure.
1016 win32_capture_streams(const wchar_t *path,
1017 size_t path_num_chars,
1018 struct wim_inode *inode,
1019 struct wim_lookup_table *lookup_table,
1023 WIN32_FIND_STREAM_DATA dat;
1028 DEBUG("Capturing streams from \"%ls\"", path);
1030 if (win32func_FindFirstStreamW == NULL ||
1031 !(vol_flags & FILE_NAMED_STREAMS))
1034 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1035 if (hFind == INVALID_HANDLE_VALUE) {
1036 err = GetLastError();
1037 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1040 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1041 * points and directories */
1042 if ((inode->i_attributes &
1043 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1044 && err == ERROR_HANDLE_EOF)
1046 DEBUG("ERROR_HANDLE_EOF (ok)");
1049 if (err == ERROR_ACCESS_DENIED) {
1050 WARNING("Failed to look up data streams "
1051 "of \"%ls\": Access denied!\n%ls",
1052 path, capture_access_denied_msg);
1055 ERROR("Failed to look up data streams "
1056 "of \"%ls\"", path);
1058 return WIMLIB_ERR_READ;
1063 ret = win32_capture_stream(path,
1065 inode, lookup_table,
1068 goto out_find_close;
1069 } while (win32func_FindNextStreamW(hFind, &dat));
1070 err = GetLastError();
1071 if (err != ERROR_HANDLE_EOF) {
1072 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
1074 ret = WIMLIB_ERR_READ;
1080 /* FindFirstStreamW() API is not available, or the volume does not
1081 * support named streams. Only capture the unnamed data stream. */
1082 DEBUG("Only capturing unnamed data stream");
1083 if (inode->i_attributes &
1084 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1088 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
1089 * stream to reduce the code to a call to the
1090 * already-implemented win32_capture_stream() */
1091 wcscpy(dat.cStreamName, L"::$DATA");
1092 dat.StreamSize.QuadPart = file_size;
1093 ret = win32_capture_stream(path,
1095 inode, lookup_table,
1102 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1104 size_t path_num_chars,
1105 struct add_image_params *params,
1106 struct win32_capture_state *state,
1109 struct wim_dentry *root = NULL;
1110 struct wim_inode *inode;
1118 if (exclude_path(path, path_num_chars, params->config, true)) {
1119 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
1120 ERROR("Cannot exclude the root directory from capture");
1121 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1124 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
1125 && params->progress_func)
1127 union wimlib_progress_info info;
1128 info.scan.cur_path = path;
1129 info.scan.excluded = true;
1130 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1136 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
1137 && params->progress_func)
1139 union wimlib_progress_info info;
1140 info.scan.cur_path = path;
1141 info.scan.excluded = false;
1142 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1145 HANDLE hFile = win32_open_existing_file(path,
1146 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1147 if (hFile == INVALID_HANDLE_VALUE) {
1148 err = GetLastError();
1149 ERROR("Win32 API: Failed to open \"%ls\"", path);
1151 ret = WIMLIB_ERR_OPEN;
1155 BY_HANDLE_FILE_INFORMATION file_info;
1156 if (!GetFileInformationByHandle(hFile, &file_info)) {
1157 err = GetLastError();
1158 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1161 ret = WIMLIB_ERR_STAT;
1162 goto out_close_handle;
1165 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1166 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1167 ret = win32_get_reparse_data(hFile, path, params,
1170 /* WIMLIB_ERR_* (inverted) */
1172 goto out_close_handle;
1173 } else if (ret & RP_FIXED) {
1175 } else if (ret == RP_EXCLUDED) {
1177 goto out_close_handle;
1183 /* Create a WIM dentry with an associated inode, which may be shared.
1185 * However, we need to explicitly check for directories and files with
1186 * only 1 link and refuse to hard link them. This is because Windows
1187 * has a bug where it can return duplicate File IDs for files and
1188 * directories on the FAT filesystem. */
1189 ret = inode_table_new_dentry(params->inode_table,
1190 path_basename_with_len(path, path_num_chars),
1191 ((u64)file_info.nFileIndexHigh << 32) |
1192 (u64)file_info.nFileIndexLow,
1193 file_info.dwVolumeSerialNumber,
1194 (file_info.nNumberOfLinks <= 1 ||
1195 (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1198 goto out_close_handle;
1200 ret = win32_get_short_name(root, path);
1202 goto out_close_handle;
1204 inode = root->d_inode;
1206 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1207 goto out_close_handle;
1209 inode->i_attributes = file_info.dwFileAttributes;
1210 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1211 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1212 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1213 inode->i_resolved = 1;
1215 params->add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
1217 if (!(params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)
1218 && (vol_flags & FILE_PERSISTENT_ACLS))
1220 ret = win32_get_security_descriptor(root, params->sd_set,
1222 params->add_image_flags);
1224 goto out_close_handle;
1227 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1228 (u64)file_info.nFileSizeLow;
1232 /* Capture the unnamed data stream (only should be present for regular
1233 * files) and any alternate data streams. */
1234 ret = win32_capture_streams(path,
1237 params->lookup_table,
1243 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1244 /* Reparse point: set the reparse data (which we read already)
1246 inode->i_not_rpfixed = not_rpfixed;
1247 inode->i_reparse_tag = le32_to_cpu(*(u32*)rpbuf);
1248 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1249 params->lookup_table);
1250 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1251 /* Directory (not a reparse point) --- recurse to children */
1252 ret = win32_recurse_directory(root,
1266 free_dentry_tree(root, params->lookup_table);
1271 win32_do_capture_warnings(const struct win32_capture_state *state,
1272 int add_image_flags)
1274 if (state->num_get_sacl_priv_notheld == 0 &&
1275 state->num_get_sd_access_denied == 0)
1279 WARNING("Built dentry tree successfully, but with the following problem(s):");
1280 if (state->num_get_sacl_priv_notheld != 0) {
1281 WARNING("Could not capture SACL (System Access Control List)\n"
1282 " on %lu files or directories.",
1283 state->num_get_sacl_priv_notheld);
1285 if (state->num_get_sd_access_denied != 0) {
1286 WARNING("Could not capture security descriptor at all\n"
1287 " on %lu files or directories.",
1288 state->num_get_sd_access_denied);
1291 "Try running the program as the Administrator to make sure all the\n"
1292 " desired metadata has been captured exactly. However, if you\n"
1293 " do not care about capturing security descriptors correctly, then\n"
1294 " nothing more needs to be done%ls\n",
1295 (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
1296 L", although you might consider\n"
1297 " passing the --no-acls flag to `wimlib-imagex capture' or\n"
1298 " `wimlib-imagex append' to explicitly capture no security\n"
1302 /* Win32 version of capturing a directory tree */
1304 win32_build_dentry_tree(struct wim_dentry **root_ret,
1305 const wchar_t *root_disk_path,
1306 struct add_image_params *params)
1311 struct win32_capture_state state;
1315 path_nchars = wcslen(root_disk_path);
1316 if (path_nchars > 32767)
1317 return WIMLIB_ERR_INVALID_PARAM;
1319 if (GetFileAttributesW(root_disk_path) == INVALID_FILE_ATTRIBUTES &&
1320 GetLastError() == ERROR_FILE_NOT_FOUND)
1322 ERROR("Capture directory \"%ls\" does not exist!",
1324 return WIMLIB_ERR_OPENDIR;
1327 ret = win32_get_file_and_vol_ids(root_disk_path,
1328 ¶ms->capture_root_ino,
1329 ¶ms->capture_root_dev);
1333 win32_get_vol_flags(root_disk_path, &vol_flags);
1335 /* There is no check for overflow later when this buffer is being used!
1336 * But the max path length on NTFS is 32767 characters, and paths need
1337 * to be written specially to even go past 260 characters, so we should
1338 * be okay with 32770 characters. */
1339 path = MALLOC(32770 * sizeof(wchar_t));
1341 return WIMLIB_ERR_NOMEM;
1343 wmemcpy(path, root_disk_path, path_nchars + 1);
1345 memset(&state, 0, sizeof(state));
1346 ret = win32_build_dentry_tree_recursive(root_ret, path,
1347 path_nchars, params,
1351 win32_do_capture_warnings(&state, params->add_image_flags);
1356 win32_extract_try_rpfix(u8 *rpbuf,
1357 const wchar_t *extract_root_realpath,
1358 unsigned extract_root_realpath_nchars)
1360 struct reparse_data rpdata;
1362 size_t target_nchars;
1363 size_t stripped_nchars;
1364 wchar_t *stripped_target;
1365 wchar_t stripped_target_nchars;
1368 utf16lechar *new_target;
1369 utf16lechar *new_print_name;
1370 size_t new_target_nchars;
1371 size_t new_print_name_nchars;
1374 ret = parse_reparse_data(rpbuf, 8 + le16_to_cpu(*(u16*)(rpbuf + 4)),
1379 if (extract_root_realpath[0] == L'\0' ||
1380 extract_root_realpath[1] != L':' ||
1381 extract_root_realpath[2] != L'\\')
1383 ERROR("Can't understand full path format \"%ls\". "
1384 "Try turning reparse point fixups off...",
1385 extract_root_realpath);
1386 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1389 ret = parse_substitute_name(rpdata.substitute_name,
1390 rpdata.substitute_name_nbytes,
1394 stripped_nchars = ret;
1395 target = rpdata.substitute_name;
1396 target_nchars = rpdata.substitute_name_nbytes / sizeof(utf16lechar);
1397 stripped_target = target + 6;
1398 stripped_target_nchars = target_nchars - stripped_nchars;
1400 new_target = alloca((6 + extract_root_realpath_nchars +
1401 stripped_target_nchars) * sizeof(utf16lechar));
1404 if (stripped_nchars == 6) {
1405 /* Include \??\ prefix if it was present before */
1406 wmemcpy(p, L"\\??\\", 4);
1410 /* Print name excludes the \??\ if present. */
1412 if (stripped_nchars != 0) {
1413 /* Get drive letter from real path to extract root, if a drive
1414 * letter was present before. */
1415 *p++ = extract_root_realpath[0];
1416 *p++ = extract_root_realpath[1];
1418 /* Copy the rest of the extract root */
1419 wmemcpy(p, extract_root_realpath + 2, extract_root_realpath_nchars - 2);
1420 p += extract_root_realpath_nchars - 2;
1422 /* Append the stripped target */
1423 wmemcpy(p, stripped_target, stripped_target_nchars);
1424 p += stripped_target_nchars;
1425 new_target_nchars = p - new_target;
1426 new_print_name_nchars = p - new_print_name;
1428 if (new_target_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE ||
1429 new_print_name_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE)
1431 ERROR("Path names too long to do reparse point fixup!");
1432 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1434 rpdata.substitute_name = new_target;
1435 rpdata.substitute_name_nbytes = new_target_nchars * sizeof(utf16lechar);
1436 rpdata.print_name = new_print_name;
1437 rpdata.print_name_nbytes = new_print_name_nchars * sizeof(utf16lechar);
1438 return make_reparse_buffer(&rpdata, rpbuf);
1441 /* Wrapper around the FSCTL_SET_REPARSE_POINT ioctl to set the reparse data on
1442 * an extracted reparse point. */
1444 win32_set_reparse_data(HANDLE h,
1445 const struct wim_inode *inode,
1446 const struct wim_lookup_table_entry *lte,
1447 const wchar_t *path,
1448 const struct apply_args *args)
1451 u8 rpbuf[REPARSE_POINT_MAX_SIZE];
1452 DWORD bytesReturned;
1454 DEBUG("Setting reparse data on \"%ls\"", path);
1456 ret = wim_inode_get_reparse_data(inode, rpbuf);
1460 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX &&
1461 (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1462 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT) &&
1463 !inode->i_not_rpfixed)
1465 ret = win32_extract_try_rpfix(rpbuf,
1466 args->target_realpath,
1467 args->target_realpath_len);
1469 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1472 /* Set the reparse data on the open file using the
1473 * FSCTL_SET_REPARSE_POINT ioctl.
1475 * There are contradictions in Microsoft's documentation for this:
1477 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1478 * lpOverlapped is ignored."
1480 * --- So setting lpOverlapped to NULL is okay since it's ignored.
1482 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1483 * operation returns no output data and lpOutBuffer is NULL,
1484 * DeviceIoControl makes use of lpBytesReturned. After such an
1485 * operation, the value of lpBytesReturned is meaningless."
1487 * --- So lpOverlapped not really ignored, as it affects another
1488 * parameter. This is the actual behavior: lpBytesReturned must be
1489 * specified, even though lpBytesReturned is documented as:
1491 * "Not used with this operation; set to NULL."
1493 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, rpbuf,
1494 8 + le16_to_cpu(*(u16*)(rpbuf + 4)),
1496 &bytesReturned /* lpBytesReturned */,
1497 NULL /* lpOverlapped */))
1499 DWORD err = GetLastError();
1500 ERROR("Failed to set reparse data on \"%ls\"", path);
1502 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1503 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1504 else if (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1505 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT)
1506 return WIMLIB_ERR_LINK;
1508 return WIMLIB_ERR_WRITE;
1513 /* Wrapper around the FSCTL_SET_COMPRESSION ioctl to change the
1514 * FILE_ATTRIBUTE_COMPRESSED flag of a file or directory. */
1516 win32_set_compression_state(HANDLE hFile, USHORT format, const wchar_t *path)
1518 DWORD bytesReturned;
1519 if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1520 &format, sizeof(USHORT),
1522 &bytesReturned, NULL))
1524 /* Could be a warning only, but we only call this if the volume
1525 * supports compression. So I'm calling this an error. */
1526 DWORD err = GetLastError();
1527 ERROR("Failed to set compression flag on \"%ls\"", path);
1529 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1530 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1532 return WIMLIB_ERR_WRITE;
1537 /* Wrapper around FSCTL_SET_SPARSE ioctl to set a file as sparse. */
1539 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1541 DWORD bytesReturned;
1542 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1545 &bytesReturned, NULL))
1547 /* Could be a warning only, but we only call this if the volume
1548 * supports sparse files. So I'm calling this an error. */
1549 DWORD err = GetLastError();
1550 WARNING("Failed to set sparse flag on \"%ls\"", path);
1552 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1553 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1555 return WIMLIB_ERR_WRITE;
1561 * Sets the security descriptor on an extracted file.
1564 win32_set_security_data(const struct wim_inode *inode,
1566 const wchar_t *path,
1567 struct apply_args *args)
1569 PSECURITY_DESCRIPTOR descriptor;
1572 const struct wim_security_data *sd;
1574 SECURITY_INFORMATION securityInformation = 0;
1581 BOOL owner_defaulted;
1582 BOOL group_defaulted;
1584 BOOL dacl_defaulted;
1586 BOOL sacl_defaulted;
1588 sd = wim_const_security_data(args->w);
1589 descriptor = sd->descriptors[inode->i_security_id];
1591 GetSecurityDescriptorOwner(descriptor, &owner, &owner_defaulted);
1593 securityInformation |= OWNER_SECURITY_INFORMATION;
1595 GetSecurityDescriptorGroup(descriptor, &group, &group_defaulted);
1597 securityInformation |= GROUP_SECURITY_INFORMATION;
1599 GetSecurityDescriptorDacl(descriptor, &dacl_present,
1600 &dacl, &dacl_defaulted);
1602 securityInformation |= DACL_SECURITY_INFORMATION;
1604 GetSecurityDescriptorSacl(descriptor, &sacl_present,
1605 &sacl, &sacl_defaulted);
1607 securityInformation |= SACL_SECURITY_INFORMATION;
1610 if (securityInformation == 0)
1612 if (SetSecurityInfo(hFile, SE_FILE_OBJECT,
1613 securityInformation, owner, group, dacl, sacl))
1615 err = GetLastError();
1616 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1619 case ERROR_PRIVILEGE_NOT_HELD:
1620 if (securityInformation & SACL_SECURITY_INFORMATION) {
1621 n = args->num_set_sacl_priv_notheld++;
1622 securityInformation &= ~SACL_SECURITY_INFORMATION;
1624 if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1626 "We don't have enough privileges to set the full security\n"
1627 " descriptor on \"%ls\"!\n", path);
1628 if (args->num_set_sd_access_denied +
1629 args->num_set_sacl_priv_notheld == 1)
1631 WARNING("%ls", apply_access_denied_msg);
1633 WARNING("Re-trying with SACL omitted.\n", path);
1634 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1636 "Suppressing further 'privileges not held' error messages when setting\n"
1637 " security descriptors.");
1642 case ERROR_INVALID_OWNER:
1643 case ERROR_ACCESS_DENIED:
1644 n = args->num_set_sd_access_denied++;
1645 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1646 WARNING("Failed to set security descriptor on \"%ls\": "
1647 "Access denied!\n", path);
1648 if (args->num_set_sd_access_denied +
1649 args->num_set_sacl_priv_notheld == 1)
1651 WARNING("%ls", apply_access_denied_msg);
1653 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1655 "Suppressing further access denied error messages when setting\n"
1656 " security descriptors");
1661 ERROR("Failed to set security descriptor on \"%ls\"", path);
1663 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1664 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1666 return WIMLIB_ERR_WRITE;
1672 win32_extract_chunk(const void *buf, size_t len, void *arg)
1674 HANDLE hStream = arg;
1676 DWORD nbytes_written;
1677 wimlib_assert(len <= 0xffffffff);
1679 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1680 nbytes_written != len)
1682 DWORD err = GetLastError();
1683 ERROR("WriteFile(): write error");
1685 return WIMLIB_ERR_WRITE;
1691 do_win32_extract_stream(HANDLE hStream, const struct wim_lookup_table_entry *lte)
1693 return extract_wim_resource(lte, wim_resource_size(lte),
1694 win32_extract_chunk, hStream);
1697 struct win32_encrypted_extract_ctx {
1698 const struct wim_lookup_table_entry *lte;
1703 win32_encrypted_import_cb(unsigned char *data, void *_ctx,
1704 unsigned long *len_p)
1706 struct win32_encrypted_extract_ctx *ctx = _ctx;
1707 unsigned long len = *len_p;
1708 const struct wim_lookup_table_entry *lte = ctx->lte;
1710 len = min(len, wim_resource_size(lte) - ctx->offset);
1712 if (read_partial_wim_resource_into_buf(lte, len, ctx->offset, data, false))
1713 return ERROR_READ_FAULT;
1717 return ERROR_SUCCESS;
1720 /* Create an encrypted file and extract the raw encrypted data to it.
1722 * @path: Path to encrypted file to create.
1723 * @lte: WIM lookup_table entry for the raw encrypted data.
1725 * This is separate from do_win32_extract_stream() because the WIM is supposed
1726 * to contain the *raw* encrypted data, which needs to be extracted ("imported")
1727 * using the special APIs OpenEncryptedFileRawW(), WriteEncryptedFileRaw(), and
1728 * CloseEncryptedFileRaw().
1730 * Returns 0 on success; nonzero on failure.
1733 do_win32_extract_encrypted_stream(const wchar_t *path,
1734 const struct wim_lookup_table_entry *lte)
1739 DEBUG("Opening file \"%ls\" to extract raw encrypted data", path);
1741 ret = OpenEncryptedFileRawW(path, CREATE_FOR_IMPORT, &file_ctx);
1743 ERROR("Failed to open \"%ls\" to write raw encrypted data", path);
1745 return WIMLIB_ERR_OPEN;
1749 struct win32_encrypted_extract_ctx ctx;
1753 ret = WriteEncryptedFileRaw(win32_encrypted_import_cb, &ctx, file_ctx);
1754 if (ret == ERROR_SUCCESS) {
1757 ret = WIMLIB_ERR_WRITE;
1758 ERROR("Failed to extract encrypted file \"%ls\"", path);
1761 CloseEncryptedFileRaw(file_ctx);
1766 path_is_root_of_drive(const wchar_t *path)
1771 if (*path != L'/' && *path != L'\\') {
1772 if (*(path + 1) == L':')
1777 while (*path == L'/' || *path == L'\\')
1779 return (*path == L'\0');
1783 win32_mask_attributes(DWORD i_attributes)
1785 return i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1786 FILE_ATTRIBUTE_COMPRESSED |
1787 FILE_ATTRIBUTE_REPARSE_POINT |
1788 FILE_ATTRIBUTE_DIRECTORY |
1789 FILE_ATTRIBUTE_ENCRYPTED |
1790 FILE_FLAG_DELETE_ON_CLOSE |
1791 FILE_FLAG_NO_BUFFERING |
1792 FILE_FLAG_OPEN_NO_RECALL |
1793 FILE_FLAG_OVERLAPPED |
1794 FILE_FLAG_RANDOM_ACCESS |
1795 /*FILE_FLAG_SESSION_AWARE |*/
1796 FILE_FLAG_SEQUENTIAL_SCAN |
1797 FILE_FLAG_WRITE_THROUGH);
1801 win32_get_create_flags_and_attributes(DWORD i_attributes)
1804 * Some attributes cannot be set by passing them to CreateFile(). In
1807 * FILE_ATTRIBUTE_DIRECTORY:
1808 * CreateDirectory() must be called instead of CreateFile().
1810 * FILE_ATTRIBUTE_SPARSE_FILE:
1812 * See: win32_set_sparse().
1814 * FILE_ATTRIBUTE_COMPRESSED:
1815 * Not clear from the documentation, but apparently this needs an
1817 * See: win32_set_compressed().
1819 * FILE_ATTRIBUTE_REPARSE_POINT:
1820 * Needs an ioctl, with the reparse data specified.
1821 * See: win32_set_reparse_data().
1823 * In addition, clear any file flags in the attributes that we don't
1824 * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1825 * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1827 return win32_mask_attributes(i_attributes) |
1828 FILE_FLAG_OPEN_REPARSE_POINT |
1829 FILE_FLAG_BACKUP_SEMANTICS;
1832 /* Set compression and/or sparse attributes on a stream, if supported by the
1835 win32_set_special_stream_attributes(HANDLE hFile, const struct wim_inode *inode,
1836 struct wim_lookup_table_entry *unnamed_stream_lte,
1837 const wchar_t *path, unsigned vol_flags)
1841 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1842 if (vol_flags & FILE_FILE_COMPRESSION) {
1843 ret = win32_set_compression_state(hFile,
1844 COMPRESSION_FORMAT_DEFAULT,
1849 DEBUG("Cannot set compression attribute on \"%ls\": "
1850 "volume does not support transparent compression",
1855 if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1856 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1857 DEBUG("Setting sparse flag on \"%ls\"", path);
1858 ret = win32_set_sparse(hFile, path);
1862 DEBUG("Cannot set sparse attribute on \"%ls\": "
1863 "volume does not support sparse files",
1870 /* Pre-create directories; extract encrypted streams */
1872 win32_begin_extract_unnamed_stream(const struct wim_inode *inode,
1873 const struct wim_lookup_table_entry *lte,
1874 const wchar_t *path,
1875 DWORD *creationDisposition_ret,
1876 unsigned int vol_flags)
1881 /* Directories must be created with CreateDirectoryW(). Then the call
1882 * to CreateFileW() will merely open the directory that was already
1883 * created rather than creating a new file. */
1884 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY &&
1885 !path_is_root_of_drive(path)) {
1886 if (!CreateDirectoryW(path, NULL)) {
1887 err = GetLastError();
1888 if (err != ERROR_ALREADY_EXISTS) {
1889 ERROR("Failed to create directory \"%ls\"",
1892 return WIMLIB_ERR_MKDIR;
1895 DEBUG("Created directory \"%ls\"", path);
1896 *creationDisposition_ret = OPEN_EXISTING;
1898 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED &&
1899 vol_flags & FILE_SUPPORTS_ENCRYPTION)
1901 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1902 unsigned remaining_sharing_violations = 100;
1903 while (!EncryptFile(path)) {
1904 if (remaining_sharing_violations &&
1905 err == ERROR_SHARING_VIOLATION)
1907 WARNING("Couldn't encrypt directory \"%ls\" "
1908 "due to sharing violation; re-trying "
1909 "after 100 ms", path);
1911 remaining_sharing_violations--;
1913 err = GetLastError();
1914 ERROR("Failed to encrypt directory \"%ls\"",
1917 return WIMLIB_ERR_WRITE;
1921 ret = do_win32_extract_encrypted_stream(path, lte);
1924 DEBUG("Extracted encrypted file \"%ls\"", path);
1926 *creationDisposition_ret = OPEN_EXISTING;
1929 /* Set file attributes if we created the file. Otherwise, we haven't
1930 * created the file set and we will set the attributes in the call to
1933 * The FAT filesystem does not let you change the attributes of the root
1934 * directory, so treat that as a special case and do not set attributes.
1936 if (*creationDisposition_ret == OPEN_EXISTING &&
1937 !path_is_root_of_drive(path))
1939 if (!SetFileAttributesW(path,
1940 win32_mask_attributes(inode->i_attributes)))
1942 err = GetLastError();
1943 ERROR("Failed to set attributes on \"%ls\"", path);
1945 return WIMLIB_ERR_WRITE;
1951 /* Set security descriptor and extract stream data or reparse data (skip the
1952 * unnamed data stream of encrypted files, which was already extracted). */
1954 win32_finish_extract_stream(HANDLE h, const struct wim_dentry *dentry,
1955 const struct wim_lookup_table_entry *lte,
1956 const wchar_t *stream_path,
1957 const wchar_t *stream_name_utf16,
1958 struct apply_args *args)
1961 const struct wim_inode *inode = dentry->d_inode;
1962 const wchar_t *short_name;
1963 if (stream_name_utf16 == NULL) {
1964 /* Unnamed stream. */
1966 /* Set security descriptor, unless the extract_flags indicate
1967 * not to or the volume does not supported it. Note that this
1968 * is only done when the unnamed stream is being extracted, as
1969 * security descriptors are per-file and not per-stream. */
1970 if (inode->i_security_id >= 0 &&
1971 !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
1972 && (args->vol_flags & FILE_PERSISTENT_ACLS))
1974 ret = win32_set_security_data(inode, h, stream_path, args);
1979 /* Handle reparse points. The data for them needs to be set
1980 * using a special ioctl. Note that the reparse point may have
1981 * been created using CreateFileW() in the case of
1982 * non-directories or CreateDirectoryW() in the case of
1983 * directories; but the ioctl works either way. Also, it is
1984 * only this step that actually sets the
1985 * FILE_ATTRIBUTE_REPARSE_POINT, as it is not valid to set it
1986 * using SetFileAttributesW() or CreateFileW().
1988 * If the volume does not support reparse points we simply
1989 * ignore the reparse data. (N.B. the code currently doesn't
1990 * actually reach this case because reparse points are skipped
1991 * entirely on such volumes.) */
1992 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1993 if (args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
1994 ret = win32_set_reparse_data(h, inode,
2000 DEBUG("Cannot set reparse data on \"%ls\": volume "
2001 "does not support reparse points", stream_path);
2003 } else if (lte != NULL &&
2004 !(args->vol_flags & FILE_SUPPORTS_ENCRYPTION &&
2005 inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2007 /* Extract the data of the unnamed stream, unless the
2008 * lookup table entry is NULL (indicating an empty
2009 * stream for which no data needs to be extracted), or
2010 * the stream is encrypted and therefore was already
2011 * extracted as a special case. */
2012 ret = do_win32_extract_stream(h, lte);
2017 if (dentry_has_short_name(dentry))
2018 short_name = dentry->short_name;
2021 /* Set short name */
2022 if (!SetFileShortNameW(h, short_name)) {
2024 DWORD err = GetLastError();
2025 ERROR("Could not set short name on \"%ls\"", stream_path);
2030 /* Extract the data for a named data stream. */
2032 DEBUG("Extracting named data stream \"%ls\" (len = %"PRIu64")",
2033 stream_path, wim_resource_size(lte));
2034 ret = do_win32_extract_stream(h, lte);
2041 win32_decrypt_file(HANDLE open_handle, const wchar_t *path)
2044 /* We cannot call DecryptFileW() while there is an open handle to the
2045 * file. So close it first. */
2046 if (!CloseHandle(open_handle)) {
2047 err = GetLastError();
2048 ERROR("Failed to close handle for \"%ls\"", path);
2050 return WIMLIB_ERR_WRITE;
2052 if (!DecryptFileW(path, 0 /* reserved parameter; set to 0 */)) {
2053 err = GetLastError();
2054 ERROR("Failed to decrypt file \"%ls\"", path);
2056 return WIMLIB_ERR_WRITE;
2062 * Create and extract a stream to a file, or create a directory, using the
2065 * This handles reparse points, directories, alternate data streams, encrypted
2066 * files, compressed files, etc.
2068 * @dentry: WIM dentry for the file or directory being extracted.
2070 * @path: Path to extract the file to.
2072 * @stream_name_utf16:
2073 * Name of the stream, or NULL if the stream is unnamed. This will
2074 * be called with a NULL stream_name_utf16 before any non-NULL
2075 * stream_name_utf16's.
2077 * @lte: WIM lookup table entry for the stream. May be NULL to indicate
2078 * a stream of length 0.
2080 * @args: Additional apply context, including flags indicating supported
2083 * Returns 0 on success; nonzero on failure.
2086 win32_extract_stream(const struct wim_dentry *dentry,
2087 const wchar_t *path,
2088 const wchar_t *stream_name_utf16,
2089 struct wim_lookup_table_entry *lte,
2090 struct apply_args *args)
2092 wchar_t *stream_path;
2096 DWORD creationDisposition = CREATE_ALWAYS;
2097 DWORD requestedAccess;
2098 BY_HANDLE_FILE_INFORMATION file_info;
2099 unsigned remaining_sharing_violations = 1000;
2100 const struct wim_inode *inode = dentry->d_inode;
2102 if (stream_name_utf16) {
2103 /* Named stream. Create a buffer that contains the UTF-16LE
2104 * string [./]path:stream_name_utf16. This is needed to
2105 * create and open the stream using CreateFileW(). I'm not
2106 * aware of any other APIs to do this. Note: the '$DATA' suffix
2107 * seems to be unneeded. Additional note: a "./" prefix needs
2108 * to be added when the path is not absolute to avoid ambiguity
2109 * with drive letters. */
2110 size_t stream_path_nchars;
2112 size_t stream_name_nchars;
2113 const wchar_t *prefix;
2115 path_nchars = wcslen(path);
2116 stream_name_nchars = wcslen(stream_name_utf16);
2117 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
2118 if (path[0] != cpu_to_le16(L'\0') &&
2119 path[0] != cpu_to_le16(L'/') &&
2120 path[0] != cpu_to_le16(L'\\') &&
2121 path[1] != cpu_to_le16(L':'))
2124 stream_path_nchars += 2;
2128 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
2129 swprintf(stream_path, L"%ls%ls:%ls",
2130 prefix, path, stream_name_utf16);
2132 /* Unnamed stream; its path is just the path to the file itself.
2134 stream_path = (wchar_t*)path;
2136 ret = win32_begin_extract_unnamed_stream(inode, lte, path,
2137 &creationDisposition,
2143 DEBUG("Opening \"%ls\"", stream_path);
2144 /* DELETE access is needed for SetFileShortNameW(), for some reason. */
2145 requestedAccess = GENERIC_READ | GENERIC_WRITE | DELETE |
2146 ACCESS_SYSTEM_SECURITY;
2148 /* Open the stream to be extracted. Depending on what we have set
2149 * creationDisposition to, we may be creating this for the first time,
2150 * or we may be opening on existing stream we already created using
2151 * CreateDirectoryW() or OpenEncryptedFileRawW(). */
2152 h = CreateFileW(stream_path,
2156 creationDisposition,
2157 win32_get_create_flags_and_attributes(inode->i_attributes),
2159 if (h == INVALID_HANDLE_VALUE) {
2160 err = GetLastError();
2161 if (err == ERROR_ACCESS_DENIED &&
2162 path_is_root_of_drive(stream_path))
2167 if ((err == ERROR_PRIVILEGE_NOT_HELD ||
2168 err == ERROR_ACCESS_DENIED) &&
2169 (requestedAccess & ACCESS_SYSTEM_SECURITY))
2171 /* Try opening the file again without privilege to
2173 requestedAccess &= ~ACCESS_SYSTEM_SECURITY;
2174 goto try_open_again;
2176 if (err == ERROR_SHARING_VIOLATION) {
2177 if (remaining_sharing_violations) {
2178 --remaining_sharing_violations;
2179 /* This can happen when restoring encrypted directories
2180 * for some reason. Probably a bug in EncryptFile(). */
2181 WARNING("Couldn't open \"%ls\" due to sharing violation; "
2182 "re-trying after 100ms", stream_path);
2184 goto try_open_again;
2186 ERROR("Too many sharing violations; giving up...");
2189 if (creationDisposition == OPEN_EXISTING)
2190 ERROR("Failed to open \"%ls\"", stream_path);
2192 ERROR("Failed to create \"%ls\"", stream_path);
2195 ret = WIMLIB_ERR_OPEN;
2199 /* Check the attributes of the file we just opened, and remove
2200 * encryption or compression if either was set by default but is not
2201 * supposed to be set based on the WIM inode attributes. */
2202 if (!GetFileInformationByHandle(h, &file_info)) {
2203 err = GetLastError();
2204 ERROR("Failed to get attributes of \"%ls\"", stream_path);
2206 ret = WIMLIB_ERR_STAT;
2207 goto fail_close_handle;
2210 /* Remove encryption? */
2211 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED &&
2212 !(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2214 /* File defaulted to encrypted due to being in an encrypted
2215 * directory, but is not actually supposed to be encrypted.
2217 * This is a workaround, because I'm not aware of any way to
2218 * directly (e.g. with CreateFileW()) create an unencrypted file
2219 * in a directory with FILE_ATTRIBUTE_ENCRYPTED set. */
2220 ret = win32_decrypt_file(h, stream_path);
2222 goto fail; /* win32_decrypt_file() closed the handle. */
2223 creationDisposition = OPEN_EXISTING;
2224 goto try_open_again;
2227 /* Remove compression? */
2228 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED &&
2229 !(inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED))
2231 /* Similar to the encrypted case, above, if the file defaulted
2232 * to compressed due to being in an compressed directory, but is
2233 * not actually supposed to be compressed, explicitly set the
2234 * compression format to COMPRESSION_FORMAT_NONE. */
2235 ret = win32_set_compression_state(h, COMPRESSION_FORMAT_NONE,
2238 goto fail_close_handle;
2241 /* Set compression and/or sparse attributes if needed */
2242 ret = win32_set_special_stream_attributes(h, inode, lte, path,
2246 goto fail_close_handle;
2248 /* At this point we have at least created the needed stream with the
2249 * appropriate attributes. We have yet to set the appropriate security
2250 * descriptor and actually extract the stream data (other than for
2251 * extracted files, which were already extracted).
2252 * win32_finish_extract_stream() handles these additional steps. */
2253 ret = win32_finish_extract_stream(h, dentry, lte, stream_path,
2254 stream_name_utf16, args);
2256 goto fail_close_handle;
2258 /* Done extracting the stream. Close the handle and return. */
2259 DEBUG("Closing \"%ls\"", stream_path);
2260 if (!CloseHandle(h)) {
2261 err = GetLastError();
2262 ERROR("Failed to close \"%ls\"", stream_path);
2264 ret = WIMLIB_ERR_WRITE;
2272 ERROR("Error extracting \"%ls\"", stream_path);
2278 * Creates a file, directory, or reparse point and extracts all streams to it
2279 * (unnamed data stream and/or reparse point stream, plus any alternate data
2280 * streams). Handles sparse, compressed, and/or encrypted files.
2282 * @dentry: WIM dentry for this file or directory.
2283 * @path: UTF-16LE external path to extract the inode to.
2284 * @args: Additional extraction context.
2286 * Returns 0 on success; nonzero on failure.
2289 win32_extract_streams(const struct wim_dentry *dentry,
2290 const wchar_t *path, struct apply_args *args)
2292 struct wim_lookup_table_entry *unnamed_lte;
2294 const struct wim_inode *inode = dentry->d_inode;
2296 /* First extract the unnamed stream. */
2298 unnamed_lte = inode_unnamed_lte_resolved(inode);
2299 ret = win32_extract_stream(dentry, path, NULL, unnamed_lte, args);
2303 /* Extract any named streams, if supported by the volume. */
2305 if (!(args->vol_flags & FILE_NAMED_STREAMS))
2307 for (u16 i = 0; i < inode->i_num_ads; i++) {
2308 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
2310 /* Skip the unnamed stream if it's in the ADS entries (we
2311 * already extracted it...) */
2312 if (ads_entry->stream_name_nbytes == 0)
2315 /* Skip special UNIX data entries (see documentation for
2316 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
2317 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
2318 && !memcmp(ads_entry->stream_name,
2319 WIMLIB_UNIX_DATA_TAG_UTF16LE,
2320 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
2323 /* Extract the named stream */
2324 ret = win32_extract_stream(dentry,
2326 ads_entry->stream_name,
2336 /* If not done already, load the supported feature flags for the volume onto
2337 * which the image is being extracted, and warn the user about any missing
2338 * features that could be important. */
2340 win32_check_vol_flags(const wchar_t *output_path, struct apply_args *args)
2342 if (args->have_vol_flags)
2345 win32_get_vol_flags(output_path, &args->vol_flags);
2346 args->have_vol_flags = true;
2347 /* Warn the user about data that may not be extracted. */
2348 if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
2349 WARNING("Volume does not support sparse files!\n"
2350 " Sparse files will be extracted as non-sparse.");
2351 if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2352 WARNING("Volume does not support reparse points!\n"
2353 " Reparse point data will not be extracted.");
2354 if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
2355 WARNING("Volume does not support named data streams!\n"
2356 " Named data streams will not be extracted.");
2358 if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
2359 WARNING("Volume does not support encryption!\n"
2360 " Encrypted files will be extracted as raw data.");
2362 if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
2363 WARNING("Volume does not support transparent compression!\n"
2364 " Compressed files will be extracted as non-compressed.");
2366 if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
2367 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
2368 ERROR("Strict ACLs requested, but the volume does not "
2370 return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
2372 WARNING("Volume does not support persistent ACLS!\n"
2373 " File permissions will not be extracted.");
2380 * Try extracting a hard link.
2382 * @output_path: Path to link to be extracted.
2384 * @inode: WIM inode that the link is to; inode->i_extracted_file
2385 * the path to a name of the file that has already been
2386 * extracted (we use this to create the hard link).
2388 * @args: Additional apply context, used here to keep track of
2389 * the number of times creating a hard link failed due to
2390 * ERROR_INVALID_FUNCTION. This error should indicate that hard
2391 * links are not supported by the volume, and we would like to
2392 * warn the user a few times, but not too many times.
2394 * Returns 0 if the hard link was successfully extracted. Returns
2395 * WIMLIB_ERR_LINK (> 0) if an error occurred, other than hard links possibly
2396 * being unsupported by the volume. Returns a negative value if creating the
2397 * hard link failed due to ERROR_INVALID_FUNCTION.
2400 win32_try_hard_link(const wchar_t *output_path, const struct wim_inode *inode,
2401 struct apply_args *args)
2405 /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
2406 * but it's only available on Windows 7 and later. So no use
2407 * even checking it, really. Instead, CreateHardLinkW() will
2408 * apparently return ERROR_INVALID_FUNCTION if the volume does
2409 * not support hard links. */
2410 DEBUG("Creating hard link \"%ls => %ls\"",
2411 output_path, inode->i_extracted_file);
2412 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
2415 err = GetLastError();
2416 if (err != ERROR_INVALID_FUNCTION) {
2417 ERROR("Can't create hard link \"%ls => %ls\"",
2418 output_path, inode->i_extracted_file);
2420 return WIMLIB_ERR_LINK;
2422 args->num_hard_links_failed++;
2423 if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
2424 WARNING("Can't create hard link \"%ls => %ls\":\n"
2425 " Volume does not support hard links!\n"
2426 " Falling back to extracting a copy of the file.",
2427 output_path, inode->i_extracted_file);
2428 } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
2429 WARNING("Suppressing further hard linking warnings...");
2435 /* Extract a file, directory, reparse point, or hard link to an
2436 * already-extracted file using the Win32 API */
2438 win32_do_apply_dentry(const wchar_t *output_path,
2439 size_t output_path_num_chars,
2440 struct wim_dentry *dentry,
2441 struct apply_args *args)
2444 struct wim_inode *inode = dentry->d_inode;
2446 ret = win32_check_vol_flags(output_path, args);
2449 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
2450 /* Linked file, with another name already extracted. Create a
2452 ret = win32_try_hard_link(output_path, inode, args);
2455 /* Negative return value from win32_try_hard_link() indicates
2456 * that hard links are probably not supported by the volume.
2457 * Fall back to extracting a copy of the file. */
2460 /* If this is a reparse point and the volume does not support reparse
2461 * points, just skip it completely. */
2462 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2463 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2465 WARNING("Skipping extraction of reparse point \"%ls\":\n"
2466 " Not supported by destination filesystem",
2469 /* Create the file, directory, or reparse point, and extract the
2471 ret = win32_extract_streams(dentry, output_path, args);
2475 if (inode->i_extracted_file == NULL) {
2476 const struct wim_lookup_table_entry *lte;
2478 /* Tally bytes extracted, including all alternate data streams,
2479 * unless we extracted a hard link (or, at least extracted a
2480 * name that was supposed to be a hard link) */
2481 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
2482 lte = inode_stream_lte_resolved(inode, i);
2484 args->progress.extract.completed_bytes +=
2485 wim_resource_size(lte);
2487 if (inode->i_nlink > 1) {
2488 /* Save extracted path for a later call to
2489 * CreateHardLinkW() if this inode has multiple links.
2491 inode->i_extracted_file = WSTRDUP(output_path);
2492 if (!inode->i_extracted_file)
2493 return WIMLIB_ERR_NOMEM;
2499 /* Set timestamps on an extracted file using the Win32 API */
2501 win32_do_apply_dentry_timestamps(const wchar_t *path,
2502 size_t path_num_chars,
2503 const struct wim_dentry *dentry,
2504 const struct apply_args *args)
2508 const struct wim_inode *inode = dentry->d_inode;
2510 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2511 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2513 /* Skip reparse points not extracted */
2517 /* Windows doesn't let you change the timestamps of the root directory
2518 * (at least on FAT, which is dumb but expected since FAT doesn't store
2519 * any metadata about the root directory...) */
2520 if (path_is_root_of_drive(path))
2523 DEBUG("Opening \"%ls\" to set timestamps", path);
2524 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
2525 if (h == INVALID_HANDLE_VALUE) {
2526 err = GetLastError();
2530 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
2531 .dwHighDateTime = inode->i_creation_time >> 32};
2532 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
2533 .dwHighDateTime = inode->i_last_access_time >> 32};
2534 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
2535 .dwHighDateTime = inode->i_last_write_time >> 32};
2537 DEBUG("Calling SetFileTime() on \"%ls\"", path);
2538 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
2539 err = GetLastError();
2543 DEBUG("Closing \"%ls\"", path);
2544 if (!CloseHandle(h)) {
2545 err = GetLastError();
2550 /* Only warn if setting timestamps failed; still return 0. */
2551 WARNING("Can't set timestamps on \"%ls\"", path);
2557 /* Replacement for POSIX fsync() */
2564 h = (HANDLE)_get_osfhandle(fd);
2565 if (h == INVALID_HANDLE_VALUE) {
2566 err = GetLastError();
2567 ERROR("Could not get Windows handle for file descriptor");
2572 if (!FlushFileBuffers(h)) {
2573 err = GetLastError();
2574 ERROR("Could not flush file buffers to disk");
2582 /* Use the Win32 API to get the number of processors */
2584 win32_get_number_of_processors()
2586 SYSTEM_INFO sysinfo;
2587 GetSystemInfo(&sysinfo);
2588 return sysinfo.dwNumberOfProcessors;
2591 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
2592 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
2593 * really does the right thing under all circumstances. */
2595 realpath(const wchar_t *path, wchar_t *resolved_path)
2598 wimlib_assert(resolved_path == NULL);
2601 ret = GetFullPathNameW(path, 0, NULL, NULL);
2603 err = GetLastError();
2607 resolved_path = TMALLOC(ret);
2610 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2612 err = GetLastError();
2613 free(resolved_path);
2614 resolved_path = NULL;
2622 return resolved_path;
2625 /* rename() on Windows fails if the destination file exists. And we need to
2626 * make it work on wide characters. Fix it. */
2628 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2630 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2633 /* As usual, the possible error values are not documented */
2634 DWORD err = GetLastError();
2635 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2643 /* Replacement for POSIX fnmatch() (partial functionality only) */
2645 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2647 if (PathMatchSpecW(string, pattern))
2653 /* truncate() replacement */
2655 win32_truncate_replacement(const wchar_t *path, off_t size)
2657 DWORD err = NO_ERROR;
2658 LARGE_INTEGER liOffset;
2660 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2661 if (h == INVALID_HANDLE_VALUE)
2664 liOffset.QuadPart = size;
2665 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2666 goto fail_close_handle;
2668 if (!SetEndOfFile(h))
2669 goto fail_close_handle;
2674 err = GetLastError();
2677 if (err == NO_ERROR)
2678 err = GetLastError();
2679 ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2686 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2687 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2688 * linked in by Visual Studio...?). */
2690 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2692 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2694 pthread_mutex_lock(&strerror_lock);
2695 mbstowcs(buf, strerror(errnum), buflen);
2696 buf[buflen - 1] = '\0';
2697 pthread_mutex_unlock(&strerror_lock);
2701 #endif /* __WIN32__ */