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;
681 target[target_nchars] = L'\0';
682 orig_target = target;
683 target = capture_fixup_absolute_symlink(target + stripped_chars,
684 capture_root_ino, capture_root_dev);
687 target_nchars = wcslen(target);
688 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
689 *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
690 DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
691 if (stripped_chars == 6)
692 return RP_FIXED_FULLPATH;
694 return RP_FIXED_ABSPATH;
697 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
700 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
701 u64 capture_root_ino, u64 capture_root_dev)
703 struct reparse_data rpdata;
706 enum rp_status rp_status;
708 rpbuflen = *rpbuflen_p;
709 ret = parse_reparse_data(rpbuf, rpbuflen, &rpdata);
713 rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
714 &rpdata.substitute_name_nbytes,
717 le32_to_cpu(*(u32*)rpbuf));
718 if (rp_status & RP_FIXED) {
719 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
720 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
721 wmemcpy(substitute_name_copy, rpdata.substitute_name,
722 rpdata.substitute_name_nbytes / 2);
723 rpdata.substitute_name = substitute_name_copy;
724 rpdata.print_name = substitute_name_copy;
725 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
726 if (rp_status == RP_FIXED_FULLPATH) {
727 /* "full path", meaning \??\ prefixed. We should not
728 * include this prefix in the print name, as it is
729 * apparently meant for the filesystem driver only. */
730 rpdata.print_name += 4;
731 rpdata.print_name_nbytes -= 8;
733 ret = make_reparse_buffer(&rpdata, rpbuf);
745 * Loads the reparse point data from a reparse point into memory, optionally
746 * fixing the targets of absolute symbolic links and junction points to be
747 * relative to the root of capture.
749 * @hFile: Open handle to the reparse point.
750 * @path: Path to the reparse point. Used for error messages only.
751 * @params: Additional parameters, including whether to do reparse point fixups
753 * @rpbuf: Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
754 * the reparse point buffer will be loaded.
755 * @rpbuflen_ret: On success, the length of the reparse point buffer in bytes
756 * is written to this location.
759 * On success, returns an `enum rp_status' value that indicates if and/or
760 * how the reparse point fixup was done.
762 * On failure, returns a negative value that is a negated WIMLIB_ERR_*
766 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
767 struct add_image_params *params,
768 u8 *rpbuf, u16 *rpbuflen_ret)
775 DEBUG("Loading reparse data from \"%ls\"", path);
776 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
777 NULL, /* "Not used with this operation; set to NULL" */
778 0, /* "Not used with this operation; set to 0" */
779 rpbuf, /* "A pointer to a buffer that
780 receives the reparse point data */
781 REPARSE_POINT_MAX_SIZE, /* "The size of the output
786 DWORD err = GetLastError();
787 ERROR("Failed to get reparse data of \"%ls\"", path);
789 return -WIMLIB_ERR_READ;
791 if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
792 ERROR("Reparse data on \"%ls\" is invalid", path);
793 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
796 rpbuflen = bytesReturned;
797 reparse_tag = le32_to_cpu(*(u32*)rpbuf);
798 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX &&
799 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
800 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
802 /* Try doing reparse point fixup */
803 ret = win32_capture_try_rpfix(rpbuf,
805 params->capture_root_ino,
806 params->capture_root_dev);
810 *rpbuflen_ret = rpbuflen;
815 win32_tally_encrypted_size_cb(unsigned char *_data, void *_ctx,
819 return ERROR_SUCCESS;
823 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
830 err = OpenEncryptedFileRawW(path, 0, &file_ctx);
831 if (err != ERROR_SUCCESS) {
832 ERROR("Failed to open encrypted file \"%ls\" for raw read", path);
834 return WIMLIB_ERR_OPEN;
836 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
838 if (err != ERROR_SUCCESS) {
839 ERROR("Failed to read raw encrypted data from \"%ls\"", path);
841 ret = WIMLIB_ERR_READ;
845 CloseEncryptedFileRaw(file_ctx);
849 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
850 * stream); calculates its SHA1 message digest and either creates a `struct
851 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
852 * wim_lookup_table_entry' for an identical stream.
854 * @path: Path to the file (UTF-16LE).
856 * @path_num_chars: Number of 2-byte characters in @path.
858 * @inode: WIM inode to save the stream into.
860 * @lookup_table: Stream lookup table for the WIM.
862 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
865 * Returns 0 on success; nonzero on failure.
868 win32_capture_stream(const wchar_t *path,
869 size_t path_num_chars,
870 struct wim_inode *inode,
871 struct wim_lookup_table *lookup_table,
872 WIN32_FIND_STREAM_DATA *dat)
874 struct wim_ads_entry *ads_entry;
875 struct wim_lookup_table_entry *lte;
877 wchar_t *stream_name, *colon;
878 size_t stream_name_nchars;
879 bool is_named_stream;
882 size_t spath_buf_nbytes;
883 const wchar_t *relpath_prefix;
884 const wchar_t *colonchar;
886 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
888 /* The stream name should be returned as :NAME:TYPE */
889 stream_name = dat->cStreamName;
890 if (*stream_name != L':')
891 goto out_invalid_stream_name;
893 colon = wcschr(stream_name, L':');
895 goto out_invalid_stream_name;
897 if (wcscmp(colon + 1, L"$DATA")) {
898 /* Not a DATA stream */
905 stream_name_nchars = colon - stream_name;
906 is_named_stream = (stream_name_nchars != 0);
908 if (is_named_stream) {
909 /* Allocate an ADS entry for the named stream. */
910 ads_entry = inode_add_ads_utf16le(inode, stream_name,
911 stream_name_nchars * sizeof(wchar_t));
913 ret = WIMLIB_ERR_NOMEM;
918 /* If zero length stream, no lookup table entry needed. */
919 if ((u64)dat->StreamSize.QuadPart == 0) {
924 /* Create a UTF-16LE string @spath that gives the filename, then a
925 * colon, then the stream name. Or, if it's an unnamed stream, just the
926 * filename. It is MALLOC()'ed so that it can be saved in the
927 * wim_lookup_table_entry if needed.
929 * As yet another special case, relative paths need to be changed to
930 * begin with an explicit "./" so that, for example, a file t:ads, where
931 * :ads is the part we added, is not interpreted as a file on the t:
933 spath_nchars = path_num_chars;
934 relpath_prefix = L"";
936 if (is_named_stream) {
937 spath_nchars += 1 + stream_name_nchars;
939 if (path_num_chars == 1 &&
944 relpath_prefix = L"./";
948 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
949 spath = MALLOC(spath_buf_nbytes);
951 swprintf(spath, L"%ls%ls%ls%ls",
952 relpath_prefix, path, colonchar, stream_name);
954 /* Make a new wim_lookup_table_entry */
955 lte = new_lookup_table_entry();
957 ret = WIMLIB_ERR_NOMEM;
960 lte->file_on_disk = spath;
962 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
964 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
965 ret = win32_get_encrypted_file_size(path, &encrypted_size);
968 lte->resource_entry.original_size = encrypted_size;
970 lte->resource_location = RESOURCE_WIN32;
971 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
975 if (is_named_stream) {
976 stream_id = ads_entry->stream_id;
977 ads_entry->lte = lte;
982 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
988 out_invalid_stream_name:
989 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
990 ret = WIMLIB_ERR_READ;
994 /* Scans a Win32 file for unnamed and named data streams (not reparse point
997 * @path: Path to the file (UTF-16LE).
999 * @path_num_chars: Number of 2-byte characters in @path.
1001 * @inode: WIM inode to save the stream into.
1003 * @lookup_table: Stream lookup table for the WIM.
1005 * @file_size: Size of unnamed data stream. (Used only if alternate
1006 * data streams API appears to be unavailable.)
1008 * @vol_flags: Flags that specify features of the volume being
1011 * Returns 0 on success; nonzero on failure.
1014 win32_capture_streams(const wchar_t *path,
1015 size_t path_num_chars,
1016 struct wim_inode *inode,
1017 struct wim_lookup_table *lookup_table,
1021 WIN32_FIND_STREAM_DATA dat;
1026 DEBUG("Capturing streams from \"%ls\"", path);
1028 if (win32func_FindFirstStreamW == NULL ||
1029 !(vol_flags & FILE_NAMED_STREAMS))
1032 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1033 if (hFind == INVALID_HANDLE_VALUE) {
1034 err = GetLastError();
1035 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1038 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1039 * points and directories */
1040 if ((inode->i_attributes &
1041 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1042 && err == ERROR_HANDLE_EOF)
1044 DEBUG("ERROR_HANDLE_EOF (ok)");
1047 if (err == ERROR_ACCESS_DENIED) {
1048 WARNING("Failed to look up data streams "
1049 "of \"%ls\": Access denied!\n%ls",
1050 path, capture_access_denied_msg);
1053 ERROR("Failed to look up data streams "
1054 "of \"%ls\"", path);
1056 return WIMLIB_ERR_READ;
1061 ret = win32_capture_stream(path,
1063 inode, lookup_table,
1066 goto out_find_close;
1067 } while (win32func_FindNextStreamW(hFind, &dat));
1068 err = GetLastError();
1069 if (err != ERROR_HANDLE_EOF) {
1070 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
1072 ret = WIMLIB_ERR_READ;
1078 /* FindFirstStreamW() API is not available, or the volume does not
1079 * support named streams. Only capture the unnamed data stream. */
1080 DEBUG("Only capturing unnamed data stream");
1081 if (inode->i_attributes &
1082 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1086 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
1087 * stream to reduce the code to a call to the
1088 * already-implemented win32_capture_stream() */
1089 wcscpy(dat.cStreamName, L"::$DATA");
1090 dat.StreamSize.QuadPart = file_size;
1091 ret = win32_capture_stream(path,
1093 inode, lookup_table,
1100 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1102 size_t path_num_chars,
1103 struct add_image_params *params,
1104 struct win32_capture_state *state,
1107 struct wim_dentry *root = NULL;
1108 struct wim_inode *inode;
1116 if (exclude_path(path, path_num_chars, params->config, true)) {
1117 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
1118 ERROR("Cannot exclude the root directory from capture");
1119 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1122 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
1123 && params->progress_func)
1125 union wimlib_progress_info info;
1126 info.scan.cur_path = path;
1127 info.scan.excluded = true;
1128 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1134 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
1135 && params->progress_func)
1137 union wimlib_progress_info info;
1138 info.scan.cur_path = path;
1139 info.scan.excluded = false;
1140 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1143 HANDLE hFile = win32_open_existing_file(path,
1144 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1145 if (hFile == INVALID_HANDLE_VALUE) {
1146 err = GetLastError();
1147 ERROR("Win32 API: Failed to open \"%ls\"", path);
1149 ret = WIMLIB_ERR_OPEN;
1153 BY_HANDLE_FILE_INFORMATION file_info;
1154 if (!GetFileInformationByHandle(hFile, &file_info)) {
1155 err = GetLastError();
1156 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1159 ret = WIMLIB_ERR_STAT;
1160 goto out_close_handle;
1163 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1164 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1165 ret = win32_get_reparse_data(hFile, path, params,
1168 /* WIMLIB_ERR_* (inverted) */
1170 goto out_close_handle;
1171 } else if (ret & RP_FIXED) {
1173 } else if (ret == RP_EXCLUDED) {
1175 goto out_close_handle;
1181 /* Create a WIM dentry with an associated inode, which may be shared.
1183 * However, we need to explicitly check for directories and files with
1184 * only 1 link and refuse to hard link them. This is because Windows
1185 * has a bug where it can return duplicate File IDs for files and
1186 * directories on the FAT filesystem. */
1187 ret = inode_table_new_dentry(params->inode_table,
1188 path_basename_with_len(path, path_num_chars),
1189 ((u64)file_info.nFileIndexHigh << 32) |
1190 (u64)file_info.nFileIndexLow,
1191 file_info.dwVolumeSerialNumber,
1192 (file_info.nNumberOfLinks <= 1 ||
1193 (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1196 goto out_close_handle;
1198 ret = win32_get_short_name(root, path);
1200 goto out_close_handle;
1202 inode = root->d_inode;
1204 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1205 goto out_close_handle;
1207 inode->i_attributes = file_info.dwFileAttributes;
1208 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1209 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1210 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1211 inode->i_resolved = 1;
1213 params->add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
1215 if (!(params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)
1216 && (vol_flags & FILE_PERSISTENT_ACLS))
1218 ret = win32_get_security_descriptor(root, params->sd_set,
1220 params->add_image_flags);
1222 goto out_close_handle;
1225 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1226 (u64)file_info.nFileSizeLow;
1230 /* Capture the unnamed data stream (only should be present for regular
1231 * files) and any alternate data streams. */
1232 ret = win32_capture_streams(path,
1235 params->lookup_table,
1241 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1242 /* Reparse point: set the reparse data (which we read already)
1244 inode->i_not_rpfixed = not_rpfixed;
1245 inode->i_reparse_tag = le32_to_cpu(*(u32*)rpbuf);
1246 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1247 params->lookup_table);
1248 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1249 /* Directory (not a reparse point) --- recurse to children */
1250 ret = win32_recurse_directory(root,
1264 free_dentry_tree(root, params->lookup_table);
1269 win32_do_capture_warnings(const struct win32_capture_state *state,
1270 int add_image_flags)
1272 if (state->num_get_sacl_priv_notheld == 0 &&
1273 state->num_get_sd_access_denied == 0)
1277 WARNING("Built dentry tree successfully, but with the following problem(s):");
1278 if (state->num_get_sacl_priv_notheld != 0) {
1279 WARNING("Could not capture SACL (System Access Control List)\n"
1280 " on %lu files or directories.",
1281 state->num_get_sacl_priv_notheld);
1283 if (state->num_get_sd_access_denied != 0) {
1284 WARNING("Could not capture security descriptor at all\n"
1285 " on %lu files or directories.",
1286 state->num_get_sd_access_denied);
1289 "Try running the program as the Administrator to make sure all the\n"
1290 " desired metadata has been captured exactly. However, if you\n"
1291 " do not care about capturing security descriptors correctly, then\n"
1292 " nothing more needs to be done%ls\n",
1293 (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
1294 L", although you might consider\n"
1295 " passing the --no-acls flag to `wimlib-imagex capture' or\n"
1296 " `wimlib-imagex append' to explicitly capture no security\n"
1300 /* Win32 version of capturing a directory tree */
1302 win32_build_dentry_tree(struct wim_dentry **root_ret,
1303 const wchar_t *root_disk_path,
1304 struct add_image_params *params)
1309 struct win32_capture_state state;
1313 path_nchars = wcslen(root_disk_path);
1314 if (path_nchars > 32767)
1315 return WIMLIB_ERR_INVALID_PARAM;
1317 ret = win32_get_file_and_vol_ids(root_disk_path,
1318 ¶ms->capture_root_ino,
1319 ¶ms->capture_root_dev);
1323 win32_get_vol_flags(root_disk_path, &vol_flags);
1325 /* There is no check for overflow later when this buffer is being used!
1326 * But the max path length on NTFS is 32767 characters, and paths need
1327 * to be written specially to even go past 260 characters, so we should
1328 * be okay with 32770 characters. */
1329 path = MALLOC(32770 * sizeof(wchar_t));
1331 return WIMLIB_ERR_NOMEM;
1333 wmemcpy(path, root_disk_path, path_nchars + 1);
1335 memset(&state, 0, sizeof(state));
1336 ret = win32_build_dentry_tree_recursive(root_ret, path,
1337 path_nchars, params,
1341 win32_do_capture_warnings(&state, params->add_image_flags);
1346 win32_extract_try_rpfix(u8 *rpbuf,
1347 const wchar_t *extract_root_realpath,
1348 unsigned extract_root_realpath_nchars)
1350 struct reparse_data rpdata;
1352 size_t target_nchars;
1353 size_t stripped_nchars;
1354 wchar_t *stripped_target;
1355 wchar_t stripped_target_nchars;
1358 utf16lechar *new_target;
1359 utf16lechar *new_print_name;
1360 size_t new_target_nchars;
1361 size_t new_print_name_nchars;
1364 ret = parse_reparse_data(rpbuf, 8 + le16_to_cpu(*(u16*)(rpbuf + 4)),
1369 if (extract_root_realpath[0] == L'\0' ||
1370 extract_root_realpath[1] != L':' ||
1371 extract_root_realpath[2] != L'\\')
1373 ERROR("Can't understand full path format \"%ls\". "
1374 "Try turning reparse point fixups off...",
1375 extract_root_realpath);
1376 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1379 ret = parse_substitute_name(rpdata.substitute_name,
1380 rpdata.substitute_name_nbytes,
1384 stripped_nchars = ret;
1385 target = rpdata.substitute_name;
1386 target_nchars = rpdata.substitute_name_nbytes / sizeof(utf16lechar);
1387 stripped_target = target + 6;
1388 stripped_target_nchars = target_nchars - stripped_nchars;
1390 new_target = alloca((6 + extract_root_realpath_nchars +
1391 stripped_target_nchars) * sizeof(utf16lechar));
1394 if (stripped_nchars == 6) {
1395 /* Include \??\ prefix if it was present before */
1396 wmemcpy(p, L"\\??\\", 4);
1400 /* Print name excludes the \??\ if present. */
1402 if (target_nchars - stripped_target_nchars != 0) {
1403 /* Get drive letter from real path to extract root, if a drive
1404 * letter was present before. */
1405 *p++ = extract_root_realpath[0];
1406 *p++ = extract_root_realpath[1];
1408 /* Copy the rest of the extract root */
1409 wmemcpy(p, extract_root_realpath + 2, extract_root_realpath_nchars - 2);
1410 p += extract_root_realpath_nchars - 2;
1412 /* Append the stripped target */
1413 wmemcpy(p, stripped_target, stripped_target_nchars);
1414 p += stripped_target_nchars;
1415 new_target_nchars = p - new_target;
1416 new_print_name_nchars = p - new_print_name;
1418 if (new_target_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE ||
1419 new_print_name_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE)
1421 ERROR("Path names too long to do reparse point fixup!");
1422 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1424 rpdata.substitute_name = new_target;
1425 rpdata.substitute_name_nbytes = new_target_nchars * sizeof(utf16lechar);
1426 rpdata.print_name = new_print_name;
1427 rpdata.print_name_nbytes = new_print_name_nchars * sizeof(utf16lechar);
1428 return make_reparse_buffer(&rpdata, rpbuf);
1431 /* Wrapper around the FSCTL_SET_REPARSE_POINT ioctl to set the reparse data on
1432 * an extracted reparse point. */
1434 win32_set_reparse_data(HANDLE h,
1435 const struct wim_inode *inode,
1436 const struct wim_lookup_table_entry *lte,
1437 const wchar_t *path,
1438 const struct apply_args *args)
1441 u8 rpbuf[REPARSE_POINT_MAX_SIZE];
1442 DWORD bytesReturned;
1444 DEBUG("Setting reparse data on \"%ls\"", path);
1446 ret = wim_inode_get_reparse_data(inode, rpbuf);
1450 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX &&
1451 (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1452 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT) &&
1453 !inode->i_not_rpfixed)
1455 ret = win32_extract_try_rpfix(rpbuf,
1456 args->target_realpath,
1457 args->target_realpath_len);
1459 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1462 /* Set the reparse data on the open file using the
1463 * FSCTL_SET_REPARSE_POINT ioctl.
1465 * There are contradictions in Microsoft's documentation for this:
1467 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1468 * lpOverlapped is ignored."
1470 * --- So setting lpOverlapped to NULL is okay since it's ignored.
1472 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1473 * operation returns no output data and lpOutBuffer is NULL,
1474 * DeviceIoControl makes use of lpBytesReturned. After such an
1475 * operation, the value of lpBytesReturned is meaningless."
1477 * --- So lpOverlapped not really ignored, as it affects another
1478 * parameter. This is the actual behavior: lpBytesReturned must be
1479 * specified, even though lpBytesReturned is documented as:
1481 * "Not used with this operation; set to NULL."
1483 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, rpbuf,
1484 8 + le16_to_cpu(*(u16*)(rpbuf + 4)),
1486 &bytesReturned /* lpBytesReturned */,
1487 NULL /* lpOverlapped */))
1489 DWORD err = GetLastError();
1490 ERROR("Failed to set reparse data on \"%ls\"", path);
1492 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1493 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1494 else if (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1495 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT)
1496 return WIMLIB_ERR_LINK;
1498 return WIMLIB_ERR_WRITE;
1503 /* Wrapper around the FSCTL_SET_COMPRESSION ioctl to change the
1504 * FILE_ATTRIBUTE_COMPRESSED flag of a file or directory. */
1506 win32_set_compression_state(HANDLE hFile, USHORT format, const wchar_t *path)
1508 DWORD bytesReturned;
1509 if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1510 &format, sizeof(USHORT),
1512 &bytesReturned, NULL))
1514 /* Could be a warning only, but we only call this if the volume
1515 * supports compression. So I'm calling this an error. */
1516 DWORD err = GetLastError();
1517 ERROR("Failed to set compression flag on \"%ls\"", path);
1519 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1520 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1522 return WIMLIB_ERR_WRITE;
1527 /* Wrapper around FSCTL_SET_SPARSE ioctl to set a file as sparse. */
1529 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1531 DWORD bytesReturned;
1532 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1535 &bytesReturned, NULL))
1537 /* Could be a warning only, but we only call this if the volume
1538 * supports sparse files. So I'm calling this an error. */
1539 DWORD err = GetLastError();
1540 WARNING("Failed to set sparse flag on \"%ls\"", path);
1542 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1543 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1545 return WIMLIB_ERR_WRITE;
1551 * Sets the security descriptor on an extracted file.
1554 win32_set_security_data(const struct wim_inode *inode,
1556 const wchar_t *path,
1557 struct apply_args *args)
1559 PSECURITY_DESCRIPTOR descriptor;
1562 const struct wim_security_data *sd;
1564 SECURITY_INFORMATION securityInformation = 0;
1571 BOOL owner_defaulted;
1572 BOOL group_defaulted;
1574 BOOL dacl_defaulted;
1576 BOOL sacl_defaulted;
1578 sd = wim_const_security_data(args->w);
1579 descriptor = sd->descriptors[inode->i_security_id];
1581 GetSecurityDescriptorOwner(descriptor, &owner, &owner_defaulted);
1583 securityInformation |= OWNER_SECURITY_INFORMATION;
1585 GetSecurityDescriptorGroup(descriptor, &group, &group_defaulted);
1587 securityInformation |= GROUP_SECURITY_INFORMATION;
1589 GetSecurityDescriptorDacl(descriptor, &dacl_present,
1590 &dacl, &dacl_defaulted);
1592 securityInformation |= DACL_SECURITY_INFORMATION;
1594 GetSecurityDescriptorSacl(descriptor, &sacl_present,
1595 &sacl, &sacl_defaulted);
1597 securityInformation |= SACL_SECURITY_INFORMATION;
1600 if (securityInformation == 0)
1602 if (SetSecurityInfo(hFile, SE_FILE_OBJECT,
1603 securityInformation, owner, group, dacl, sacl))
1605 err = GetLastError();
1606 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1609 case ERROR_PRIVILEGE_NOT_HELD:
1610 if (securityInformation & SACL_SECURITY_INFORMATION) {
1611 n = args->num_set_sacl_priv_notheld++;
1612 securityInformation &= ~SACL_SECURITY_INFORMATION;
1614 if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1616 "We don't have enough privileges to set the full security\n"
1617 " descriptor on \"%ls\"!\n", path);
1618 if (args->num_set_sd_access_denied +
1619 args->num_set_sacl_priv_notheld == 1)
1621 WARNING("%ls", apply_access_denied_msg);
1623 WARNING("Re-trying with SACL omitted.\n", path);
1624 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1626 "Suppressing further 'privileges not held' error messages when setting\n"
1627 " security descriptors.");
1632 case ERROR_INVALID_OWNER:
1633 case ERROR_ACCESS_DENIED:
1634 n = args->num_set_sd_access_denied++;
1635 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1636 WARNING("Failed to set security descriptor on \"%ls\": "
1637 "Access denied!\n", path);
1638 if (args->num_set_sd_access_denied +
1639 args->num_set_sacl_priv_notheld == 1)
1641 WARNING("%ls", apply_access_denied_msg);
1643 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1645 "Suppressing further access denied error messages when setting\n"
1646 " security descriptors");
1651 ERROR("Failed to set security descriptor on \"%ls\"", path);
1653 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1654 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1656 return WIMLIB_ERR_WRITE;
1662 win32_extract_chunk(const void *buf, size_t len, void *arg)
1664 HANDLE hStream = arg;
1666 DWORD nbytes_written;
1667 wimlib_assert(len <= 0xffffffff);
1669 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1670 nbytes_written != len)
1672 DWORD err = GetLastError();
1673 ERROR("WriteFile(): write error");
1675 return WIMLIB_ERR_WRITE;
1681 do_win32_extract_stream(HANDLE hStream, const struct wim_lookup_table_entry *lte)
1683 return extract_wim_resource(lte, wim_resource_size(lte),
1684 win32_extract_chunk, hStream);
1687 struct win32_encrypted_extract_ctx {
1689 int wimlib_err_code;
1691 pthread_cond_t cond;
1692 pthread_mutex_t mutex;
1693 u8 buf[WIM_CHUNK_SIZE];
1698 win32_encrypted_import_cb(unsigned char *data, void *_ctx,
1699 unsigned long *len_p)
1701 struct win32_encrypted_extract_ctx *ctx = _ctx;
1702 unsigned long len = *len_p;
1704 pthread_mutex_lock(&ctx->mutex);
1706 size_t bytes_to_copy;
1708 DEBUG("Importing up to %lu more bytes of raw encrypted data", len);
1709 while (ctx->buf_filled == 0) {
1712 pthread_cond_wait(&ctx->cond, &ctx->mutex);
1714 bytes_to_copy = min(len, ctx->buf_filled);
1715 memcpy(data, ctx->buf, bytes_to_copy);
1716 len -= bytes_to_copy;
1717 data += bytes_to_copy;
1718 ctx->buf_filled -= bytes_to_copy;
1719 memmove(ctx->buf, ctx->buf + bytes_to_copy, ctx->buf_filled);
1720 pthread_cond_signal(&ctx->cond);
1724 pthread_mutex_unlock(&ctx->mutex);
1725 return ERROR_SUCCESS;
1728 /* Extract ("Import") an encrypted file in a different thread. */
1730 win32_encrypted_import_proc(void *arg)
1732 struct win32_encrypted_extract_ctx *ctx = arg;
1734 ret = WriteEncryptedFileRaw(win32_encrypted_import_cb, ctx,
1736 pthread_mutex_lock(&ctx->mutex);
1737 if (ret == ERROR_SUCCESS) {
1738 ctx->wimlib_err_code = 0;
1741 ctx->wimlib_err_code = WIMLIB_ERR_WRITE;
1744 pthread_cond_signal(&ctx->cond);
1745 pthread_mutex_unlock(&ctx->mutex);
1751 win32_extract_raw_encrypted_chunk(const void *buf, size_t len, void *arg)
1753 struct win32_encrypted_extract_ctx *ctx = arg;
1754 size_t bytes_to_copy;
1757 DEBUG("Extracting up to %zu more bytes of encrypted data", len);
1758 pthread_mutex_lock(&ctx->mutex);
1759 while (ctx->buf_filled == WIM_CHUNK_SIZE) {
1761 pthread_mutex_unlock(&ctx->mutex);
1762 return ctx->wimlib_err_code;
1764 pthread_cond_wait(&ctx->cond, &ctx->mutex);
1766 bytes_to_copy = min(len, WIM_CHUNK_SIZE - ctx->buf_filled);
1767 memcpy(&ctx->buf[ctx->buf_filled], buf, bytes_to_copy);
1768 len -= bytes_to_copy;
1769 buf += bytes_to_copy;
1770 ctx->buf_filled += bytes_to_copy;
1771 pthread_cond_signal(&ctx->cond);
1772 pthread_mutex_unlock(&ctx->mutex);
1777 /* Create an encrypted file and extract the raw encrypted data to it.
1779 * @path: Path to encrypted file to create.
1780 * @lte: WIM lookup_table entry for the raw encrypted data.
1782 * This is separate from do_win32_extract_stream() because the WIM is supposed
1783 * to contain the *raw* encrypted data, which needs to be extracted ("imported")
1784 * using the special APIs OpenEncryptedFileRawW(), WriteEncryptedFileRaw(), and
1785 * CloseEncryptedFileRaw().
1787 * Returns 0 on success; nonzero on failure.
1790 do_win32_extract_encrypted_stream(const wchar_t *path,
1791 const struct wim_lookup_table_entry *lte)
1793 struct win32_encrypted_extract_ctx ctx;
1795 pthread_t import_thread;
1799 DEBUG("Opening file \"%ls\" to extract raw encrypted data", path);
1801 ret = OpenEncryptedFileRawW(path, CREATE_FOR_IMPORT, &file_ctx);
1803 ERROR("Failed to open \"%ls\" to write raw encrypted data", path);
1805 return WIMLIB_ERR_OPEN;
1811 /* Hack alert: WriteEncryptedFileRaw() requires the callback function
1812 * to work with a buffer whose size we cannot control. This doesn't
1813 * play well with our read_resource_prefix() function, which itself uses
1814 * a callback function to extract WIM_CHUNK_SIZE chunks of data. We
1815 * work around this problem by calling WriteEncryptedFileRaw() in a
1816 * different thread and feeding it the data as needed. */
1817 ctx.file_ctx = file_ctx;
1820 ctx.wimlib_err_code = 0;
1821 if (pthread_mutex_init(&ctx.mutex, NULL)) {
1822 ERROR_WITH_ERRNO("Can't create mutex");
1823 ret = WIMLIB_ERR_NOMEM;
1826 if (pthread_cond_init(&ctx.cond, NULL)) {
1827 ERROR_WITH_ERRNO("Can't create condition variable");
1828 ret = WIMLIB_ERR_NOMEM;
1829 goto out_pthread_mutex_destroy;
1831 ret = pthread_create(&import_thread, NULL,
1832 win32_encrypted_import_proc, &ctx);
1835 ERROR_WITH_ERRNO("Failed to create thread");
1836 ret = WIMLIB_ERR_FORK;
1837 goto out_pthread_cond_destroy;
1840 ret = extract_wim_resource(lte, wim_resource_size(lte),
1841 win32_extract_raw_encrypted_chunk, &ctx);
1842 pthread_mutex_lock(&ctx.mutex);
1844 pthread_cond_signal(&ctx.cond);
1845 pthread_mutex_unlock(&ctx.mutex);
1846 ret2 = pthread_join(import_thread, NULL);
1849 ERROR_WITH_ERRNO("Failed to join encrypted import thread");
1851 ret = WIMLIB_ERR_WRITE;
1854 ret = ctx.wimlib_err_code;
1855 out_pthread_cond_destroy:
1856 pthread_cond_destroy(&ctx.cond);
1857 out_pthread_mutex_destroy:
1858 pthread_mutex_destroy(&ctx.mutex);
1860 CloseEncryptedFileRaw(file_ctx);
1862 ERROR("Failed to extract encrypted file \"%ls\"", path);
1867 path_is_root_of_drive(const wchar_t *path)
1872 if (*path != L'/' && *path != L'\\') {
1873 if (*(path + 1) == L':')
1878 while (*path == L'/' || *path == L'\\')
1880 return (*path == L'\0');
1884 win32_mask_attributes(DWORD i_attributes)
1886 return i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1887 FILE_ATTRIBUTE_COMPRESSED |
1888 FILE_ATTRIBUTE_REPARSE_POINT |
1889 FILE_ATTRIBUTE_DIRECTORY |
1890 FILE_ATTRIBUTE_ENCRYPTED |
1891 FILE_FLAG_DELETE_ON_CLOSE |
1892 FILE_FLAG_NO_BUFFERING |
1893 FILE_FLAG_OPEN_NO_RECALL |
1894 FILE_FLAG_OVERLAPPED |
1895 FILE_FLAG_RANDOM_ACCESS |
1896 /*FILE_FLAG_SESSION_AWARE |*/
1897 FILE_FLAG_SEQUENTIAL_SCAN |
1898 FILE_FLAG_WRITE_THROUGH);
1902 win32_get_create_flags_and_attributes(DWORD i_attributes)
1905 * Some attributes cannot be set by passing them to CreateFile(). In
1908 * FILE_ATTRIBUTE_DIRECTORY:
1909 * CreateDirectory() must be called instead of CreateFile().
1911 * FILE_ATTRIBUTE_SPARSE_FILE:
1913 * See: win32_set_sparse().
1915 * FILE_ATTRIBUTE_COMPRESSED:
1916 * Not clear from the documentation, but apparently this needs an
1918 * See: win32_set_compressed().
1920 * FILE_ATTRIBUTE_REPARSE_POINT:
1921 * Needs an ioctl, with the reparse data specified.
1922 * See: win32_set_reparse_data().
1924 * In addition, clear any file flags in the attributes that we don't
1925 * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1926 * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1928 return win32_mask_attributes(i_attributes) |
1929 FILE_FLAG_OPEN_REPARSE_POINT |
1930 FILE_FLAG_BACKUP_SEMANTICS;
1933 /* Set compression and/or sparse attributes on a stream, if supported by the
1936 win32_set_special_stream_attributes(HANDLE hFile, const struct wim_inode *inode,
1937 struct wim_lookup_table_entry *unnamed_stream_lte,
1938 const wchar_t *path, unsigned vol_flags)
1942 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1943 if (vol_flags & FILE_FILE_COMPRESSION) {
1944 ret = win32_set_compression_state(hFile,
1945 COMPRESSION_FORMAT_DEFAULT,
1950 DEBUG("Cannot set compression attribute on \"%ls\": "
1951 "volume does not support transparent compression",
1956 if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1957 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1958 DEBUG("Setting sparse flag on \"%ls\"", path);
1959 ret = win32_set_sparse(hFile, path);
1963 DEBUG("Cannot set sparse attribute on \"%ls\": "
1964 "volume does not support sparse files",
1971 /* Pre-create directories; extract encrypted streams */
1973 win32_begin_extract_unnamed_stream(const struct wim_inode *inode,
1974 const struct wim_lookup_table_entry *lte,
1975 const wchar_t *path,
1976 DWORD *creationDisposition_ret,
1977 unsigned int vol_flags)
1982 /* Directories must be created with CreateDirectoryW(). Then the call
1983 * to CreateFileW() will merely open the directory that was already
1984 * created rather than creating a new file. */
1985 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY &&
1986 !path_is_root_of_drive(path)) {
1987 if (!CreateDirectoryW(path, NULL)) {
1988 err = GetLastError();
1989 if (err != ERROR_ALREADY_EXISTS) {
1990 ERROR("Failed to create directory \"%ls\"",
1993 return WIMLIB_ERR_MKDIR;
1996 DEBUG("Created directory \"%ls\"", path);
1997 *creationDisposition_ret = OPEN_EXISTING;
1999 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED &&
2000 vol_flags & FILE_SUPPORTS_ENCRYPTION)
2002 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
2003 if (!EncryptFile(path)) {
2004 err = GetLastError();
2005 ERROR("Failed to encrypt directory \"%ls\"",
2008 return WIMLIB_ERR_WRITE;
2011 ret = do_win32_extract_encrypted_stream(path, lte);
2014 DEBUG("Extracted encrypted file \"%ls\"", path);
2016 *creationDisposition_ret = OPEN_EXISTING;
2019 /* Set file attributes if we created the file. Otherwise, we haven't
2020 * created the file set and we will set the attributes in the call to
2023 * The FAT filesystem does not let you change the attributes of the root
2024 * directory, so treat that as a special case and do not set attributes.
2026 if (*creationDisposition_ret == OPEN_EXISTING &&
2027 !path_is_root_of_drive(path))
2029 if (!SetFileAttributesW(path,
2030 win32_mask_attributes(inode->i_attributes)))
2032 err = GetLastError();
2033 ERROR("Failed to set attributes on \"%ls\"", path);
2035 return WIMLIB_ERR_WRITE;
2041 /* Set security descriptor and extract stream data or reparse data (skip the
2042 * unnamed data stream of encrypted files, which was already extracted). */
2044 win32_finish_extract_stream(HANDLE h, const struct wim_inode *inode,
2045 const struct wim_lookup_table_entry *lte,
2046 const wchar_t *stream_path,
2047 const wchar_t *stream_name_utf16,
2048 struct apply_args *args)
2051 if (stream_name_utf16 == NULL) {
2052 /* Unnamed stream. */
2054 /* Set security descriptor, unless the extract_flags indicate
2055 * not to or the volume does not supported it. Note that this
2056 * is only done when the unnamed stream is being extracted, as
2057 * security descriptors are per-file and not per-stream. */
2058 if (inode->i_security_id >= 0 &&
2059 !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
2060 && (args->vol_flags & FILE_PERSISTENT_ACLS))
2062 ret = win32_set_security_data(inode, h, stream_path, args);
2067 /* Handle reparse points. The data for them needs to be set
2068 * using a special ioctl. Note that the reparse point may have
2069 * been created using CreateFileW() in the case of
2070 * non-directories or CreateDirectoryW() in the case of
2071 * directories; but the ioctl works either way. Also, it is
2072 * only this step that actually sets the
2073 * FILE_ATTRIBUTE_REPARSE_POINT, as it is not valid to set it
2074 * using SetFileAttributesW() or CreateFileW().
2076 * If the volume does not support reparse points we simply
2077 * ignore the reparse data. (N.B. the code currently doesn't
2078 * actually reach this case because reparse points are skipped
2079 * entirely on such volumes.) */
2080 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2081 if (args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
2082 ret = win32_set_reparse_data(h, inode,
2088 DEBUG("Cannot set reparse data on \"%ls\": volume "
2089 "does not support reparse points", stream_path);
2091 } else if (lte != NULL &&
2092 !(args->vol_flags & FILE_SUPPORTS_ENCRYPTION &&
2093 inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2095 /* Extract the data of the unnamed stream, unless the
2096 * lookup table entry is NULL (indicating an empty
2097 * stream for which no data needs to be extracted), or
2098 * the stream is encrypted and therefore was already
2099 * extracted as a special case. */
2100 ret = do_win32_extract_stream(h, lte);
2103 /* Extract the data for a named data stream. */
2105 DEBUG("Extracting named data stream \"%ls\" (len = %"PRIu64")",
2106 stream_path, wim_resource_size(lte));
2107 ret = do_win32_extract_stream(h, lte);
2114 win32_decrypt_file(HANDLE open_handle, const wchar_t *path)
2117 /* We cannot call DecryptFileW() while there is an open handle to the
2118 * file. So close it first. */
2119 if (!CloseHandle(open_handle)) {
2120 err = GetLastError();
2121 ERROR("Failed to close handle for \"%ls\"", path);
2123 return WIMLIB_ERR_WRITE;
2125 if (!DecryptFileW(path, 0 /* reserved parameter; set to 0 */)) {
2126 err = GetLastError();
2127 ERROR("Failed to decrypt file \"%ls\"", path);
2129 return WIMLIB_ERR_WRITE;
2135 * Create and extract a stream to a file, or create a directory, using the
2138 * This handles reparse points, directories, alternate data streams, encrypted
2139 * files, compressed files, etc.
2141 * @inode: WIM inode containing the stream.
2143 * @path: Path to extract the file to.
2145 * @stream_name_utf16:
2146 * Name of the stream, or NULL if the stream is unnamed. This will
2147 * be called with a NULL stream_name_utf16 before any non-NULL
2148 * stream_name_utf16's.
2150 * @lte: WIM lookup table entry for the stream. May be NULL to indicate
2151 * a stream of length 0.
2153 * @args: Additional apply context, including flags indicating supported
2156 * Returns 0 on success; nonzero on failure.
2159 win32_extract_stream(const struct wim_inode *inode,
2160 const wchar_t *path,
2161 const wchar_t *stream_name_utf16,
2162 struct wim_lookup_table_entry *lte,
2163 struct apply_args *args)
2165 wchar_t *stream_path;
2169 DWORD creationDisposition = CREATE_ALWAYS;
2170 DWORD requestedAccess;
2171 BY_HANDLE_FILE_INFORMATION file_info;
2173 if (stream_name_utf16) {
2174 /* Named stream. Create a buffer that contains the UTF-16LE
2175 * string [./]path:stream_name_utf16. This is needed to
2176 * create and open the stream using CreateFileW(). I'm not
2177 * aware of any other APIs to do this. Note: the '$DATA' suffix
2178 * seems to be unneeded. Additional note: a "./" prefix needs
2179 * to be added when the path is not absolute to avoid ambiguity
2180 * with drive letters. */
2181 size_t stream_path_nchars;
2183 size_t stream_name_nchars;
2184 const wchar_t *prefix;
2186 path_nchars = wcslen(path);
2187 stream_name_nchars = wcslen(stream_name_utf16);
2188 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
2189 if (path[0] != cpu_to_le16(L'\0') &&
2190 path[0] != cpu_to_le16(L'/') &&
2191 path[0] != cpu_to_le16(L'\\') &&
2192 path[1] != cpu_to_le16(L':'))
2195 stream_path_nchars += 2;
2199 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
2200 swprintf(stream_path, L"%ls%ls:%ls",
2201 prefix, path, stream_name_utf16);
2203 /* Unnamed stream; its path is just the path to the file itself.
2205 stream_path = (wchar_t*)path;
2207 ret = win32_begin_extract_unnamed_stream(inode, lte, path,
2208 &creationDisposition,
2214 DEBUG("Opening \"%ls\"", stream_path);
2215 requestedAccess = GENERIC_READ | GENERIC_WRITE |
2216 ACCESS_SYSTEM_SECURITY;
2218 /* Open the stream to be extracted. Depending on what we have set
2219 * creationDisposition to, we may be creating this for the first time,
2220 * or we may be opening on existing stream we already created using
2221 * CreateDirectoryW() or OpenEncryptedFileRawW(). */
2222 h = CreateFileW(stream_path,
2226 creationDisposition,
2227 win32_get_create_flags_and_attributes(inode->i_attributes),
2229 if (h == INVALID_HANDLE_VALUE) {
2230 err = GetLastError();
2231 if (err == ERROR_ACCESS_DENIED &&
2232 path_is_root_of_drive(stream_path))
2237 if ((err == ERROR_PRIVILEGE_NOT_HELD ||
2238 err == ERROR_ACCESS_DENIED) &&
2239 (requestedAccess & ACCESS_SYSTEM_SECURITY))
2241 /* Try opening the file again without privilege to
2243 requestedAccess &= ~ACCESS_SYSTEM_SECURITY;
2244 goto try_open_again;
2246 ERROR("Failed to create \"%ls\"", stream_path);
2248 ret = WIMLIB_ERR_OPEN;
2252 /* Check the attributes of the file we just opened, and remove
2253 * encryption or compression if either was set by default but is not
2254 * supposed to be set based on the WIM inode attributes. */
2255 if (!GetFileInformationByHandle(h, &file_info)) {
2256 err = GetLastError();
2257 ERROR("Failed to get attributes of \"%ls\"", stream_path);
2259 ret = WIMLIB_ERR_STAT;
2260 goto fail_close_handle;
2263 /* Remove encryption? */
2264 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED &&
2265 !(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2267 /* File defaulted to encrypted due to being in an encrypted
2268 * directory, but is not actually supposed to be encrypted.
2270 * This is a workaround, because I'm not aware of any way to
2271 * directly (e.g. with CreateFileW()) create an unencrypted file
2272 * in a directory with FILE_ATTRIBUTE_ENCRYPTED set. */
2273 ret = win32_decrypt_file(h, stream_path);
2275 goto fail; /* win32_decrypt_file() closed the handle. */
2276 creationDisposition = OPEN_EXISTING;
2277 goto try_open_again;
2280 /* Remove compression? */
2281 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED &&
2282 !(inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED))
2284 /* Similar to the encrypted case, above, if the file defaulted
2285 * to compressed due to being in an compressed directory, but is
2286 * not actually supposed to be compressed, explicitly set the
2287 * compression format to COMPRESSION_FORMAT_NONE. */
2288 ret = win32_set_compression_state(h, COMPRESSION_FORMAT_NONE,
2291 goto fail_close_handle;
2294 /* Set compression and/or sparse attributes if needed */
2295 ret = win32_set_special_stream_attributes(h, inode, lte, path,
2299 goto fail_close_handle;
2301 /* At this point we have at least created the needed stream with the
2302 * appropriate attributes. We have yet to set the appropriate security
2303 * descriptor and actually extract the stream data (other than for
2304 * extracted files, which were already extracted).
2305 * win32_finish_extract_stream() handles these additional steps. */
2306 ret = win32_finish_extract_stream(h, inode, lte, stream_path,
2307 stream_name_utf16, args);
2309 goto fail_close_handle;
2311 /* Done extracting the stream. Close the handle and return. */
2312 DEBUG("Closing \"%ls\"", stream_path);
2313 if (!CloseHandle(h)) {
2314 err = GetLastError();
2315 ERROR("Failed to close \"%ls\"", stream_path);
2317 ret = WIMLIB_ERR_WRITE;
2325 ERROR("Error extracting \"%ls\"", stream_path);
2331 * Creates a file, directory, or reparse point and extracts all streams to it
2332 * (unnamed data stream and/or reparse point stream, plus any alternate data
2333 * streams). Handles sparse, compressed, and/or encrypted files.
2335 * @inode: WIM inode for this file or directory.
2336 * @path: UTF-16LE external path to extract the inode to.
2337 * @args: Additional extraction context.
2339 * Returns 0 on success; nonzero on failure.
2342 win32_extract_streams(const struct wim_inode *inode,
2343 const wchar_t *path, struct apply_args *args)
2345 struct wim_lookup_table_entry *unnamed_lte;
2348 /* First extract the unnamed stream. */
2350 unnamed_lte = inode_unnamed_lte_resolved(inode);
2351 ret = win32_extract_stream(inode, path, NULL, unnamed_lte, args);
2355 /* Extract any named streams, if supported by the volume. */
2357 if (!(args->vol_flags & FILE_NAMED_STREAMS))
2359 for (u16 i = 0; i < inode->i_num_ads; i++) {
2360 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
2362 /* Skip the unnamed stream if it's in the ADS entries (we
2363 * already extracted it...) */
2364 if (ads_entry->stream_name_nbytes == 0)
2367 /* Skip special UNIX data entries (see documentation for
2368 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
2369 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
2370 && !memcmp(ads_entry->stream_name,
2371 WIMLIB_UNIX_DATA_TAG_UTF16LE,
2372 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
2375 /* Extract the named stream */
2376 ret = win32_extract_stream(inode,
2378 ads_entry->stream_name,
2388 /* If not done already, load the supported feature flags for the volume onto
2389 * which the image is being extracted, and warn the user about any missing
2390 * features that could be important. */
2392 win32_check_vol_flags(const wchar_t *output_path, struct apply_args *args)
2394 if (args->have_vol_flags)
2397 win32_get_vol_flags(output_path, &args->vol_flags);
2398 args->have_vol_flags = true;
2399 /* Warn the user about data that may not be extracted. */
2400 if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
2401 WARNING("Volume does not support sparse files!\n"
2402 " Sparse files will be extracted as non-sparse.");
2403 if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2404 WARNING("Volume does not support reparse points!\n"
2405 " Reparse point data will not be extracted.");
2406 if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
2407 WARNING("Volume does not support named data streams!\n"
2408 " Named data streams will not be extracted.");
2410 if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
2411 WARNING("Volume does not support encryption!\n"
2412 " Encrypted files will be extracted as raw data.");
2414 if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
2415 WARNING("Volume does not support transparent compression!\n"
2416 " Compressed files will be extracted as non-compressed.");
2418 if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
2419 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
2420 ERROR("Strict ACLs requested, but the volume does not "
2422 return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
2424 WARNING("Volume does not support persistent ACLS!\n"
2425 " File permissions will not be extracted.");
2432 * Try extracting a hard link.
2434 * @output_path: Path to link to be extracted.
2436 * @inode: WIM inode that the link is to; inode->i_extracted_file
2437 * the path to a name of the file that has already been
2438 * extracted (we use this to create the hard link).
2440 * @args: Additional apply context, used here to keep track of
2441 * the number of times creating a hard link failed due to
2442 * ERROR_INVALID_FUNCTION. This error should indicate that hard
2443 * links are not supported by the volume, and we would like to
2444 * warn the user a few times, but not too many times.
2446 * Returns 0 if the hard link was successfully extracted. Returns
2447 * WIMLIB_ERR_LINK (> 0) if an error occurred, other than hard links possibly
2448 * being unsupported by the volume. Returns a negative value if creating the
2449 * hard link failed due to ERROR_INVALID_FUNCTION.
2452 win32_try_hard_link(const wchar_t *output_path, const struct wim_inode *inode,
2453 struct apply_args *args)
2457 /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
2458 * but it's only available on Windows 7 and later. So no use
2459 * even checking it, really. Instead, CreateHardLinkW() will
2460 * apparently return ERROR_INVALID_FUNCTION if the volume does
2461 * not support hard links. */
2462 DEBUG("Creating hard link \"%ls => %ls\"",
2463 output_path, inode->i_extracted_file);
2464 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
2467 err = GetLastError();
2468 if (err != ERROR_INVALID_FUNCTION) {
2469 ERROR("Can't create hard link \"%ls => %ls\"",
2470 output_path, inode->i_extracted_file);
2472 return WIMLIB_ERR_LINK;
2474 args->num_hard_links_failed++;
2475 if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
2476 WARNING("Can't create hard link \"%ls => %ls\":\n"
2477 " Volume does not support hard links!\n"
2478 " Falling back to extracting a copy of the file.",
2479 output_path, inode->i_extracted_file);
2480 } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
2481 WARNING("Suppressing further hard linking warnings...");
2487 /* Extract a file, directory, reparse point, or hard link to an
2488 * already-extracted file using the Win32 API */
2490 win32_do_apply_dentry(const wchar_t *output_path,
2491 size_t output_path_num_chars,
2492 struct wim_dentry *dentry,
2493 struct apply_args *args)
2496 struct wim_inode *inode = dentry->d_inode;
2498 ret = win32_check_vol_flags(output_path, args);
2501 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
2502 /* Linked file, with another name already extracted. Create a
2504 ret = win32_try_hard_link(output_path, inode, args);
2507 /* Negative return value from win32_try_hard_link() indicates
2508 * that hard links are probably not supported by the volume.
2509 * Fall back to extracting a copy of the file. */
2512 /* If this is a reparse point and the volume does not support reparse
2513 * points, just skip it completely. */
2514 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2515 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2517 WARNING("Skipping extraction of reparse point \"%ls\":\n"
2518 " Not supported by destination filesystem",
2521 /* Create the file, directory, or reparse point, and extract the
2523 ret = win32_extract_streams(inode, output_path, args);
2527 if (inode->i_extracted_file == NULL) {
2528 const struct wim_lookup_table_entry *lte;
2530 /* Tally bytes extracted, including all alternate data streams,
2531 * unless we extracted a hard link (or, at least extracted a
2532 * name that was supposed to be a hard link) */
2533 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
2534 lte = inode_stream_lte_resolved(inode, i);
2536 args->progress.extract.completed_bytes +=
2537 wim_resource_size(lte);
2539 if (inode->i_nlink > 1) {
2540 /* Save extracted path for a later call to
2541 * CreateHardLinkW() if this inode has multiple links.
2543 inode->i_extracted_file = WSTRDUP(output_path);
2544 if (!inode->i_extracted_file)
2545 return WIMLIB_ERR_NOMEM;
2551 /* Set timestamps on an extracted file using the Win32 API */
2553 win32_do_apply_dentry_timestamps(const wchar_t *path,
2554 size_t path_num_chars,
2555 const struct wim_dentry *dentry,
2556 const struct apply_args *args)
2560 const struct wim_inode *inode = dentry->d_inode;
2562 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2563 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2565 /* Skip reparse points not extracted */
2569 /* Windows doesn't let you change the timestamps of the root directory
2570 * (at least on FAT, which is dumb but expected since FAT doesn't store
2571 * any metadata about the root directory...) */
2572 if (path_is_root_of_drive(path))
2575 DEBUG("Opening \"%ls\" to set timestamps", path);
2576 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
2577 if (h == INVALID_HANDLE_VALUE) {
2578 err = GetLastError();
2582 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
2583 .dwHighDateTime = inode->i_creation_time >> 32};
2584 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
2585 .dwHighDateTime = inode->i_last_access_time >> 32};
2586 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
2587 .dwHighDateTime = inode->i_last_write_time >> 32};
2589 DEBUG("Calling SetFileTime() on \"%ls\"", path);
2590 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
2591 err = GetLastError();
2595 DEBUG("Closing \"%ls\"", path);
2596 if (!CloseHandle(h)) {
2597 err = GetLastError();
2602 /* Only warn if setting timestamps failed; still return 0. */
2603 WARNING("Can't set timestamps on \"%ls\"", path);
2609 /* Replacement for POSIX fsync() */
2616 h = (HANDLE)_get_osfhandle(fd);
2617 if (h == INVALID_HANDLE_VALUE) {
2618 err = GetLastError();
2619 ERROR("Could not get Windows handle for file descriptor");
2624 if (!FlushFileBuffers(h)) {
2625 err = GetLastError();
2626 ERROR("Could not flush file buffers to disk");
2634 /* Use the Win32 API to get the number of processors */
2636 win32_get_number_of_processors()
2638 SYSTEM_INFO sysinfo;
2639 GetSystemInfo(&sysinfo);
2640 return sysinfo.dwNumberOfProcessors;
2643 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
2644 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
2645 * really does the right thing under all circumstances. */
2647 realpath(const wchar_t *path, wchar_t *resolved_path)
2650 wimlib_assert(resolved_path == NULL);
2653 ret = GetFullPathNameW(path, 0, NULL, NULL);
2655 err = GetLastError();
2659 resolved_path = TMALLOC(ret);
2662 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2664 err = GetLastError();
2665 free(resolved_path);
2666 resolved_path = NULL;
2674 return resolved_path;
2677 /* rename() on Windows fails if the destination file exists. And we need to
2678 * make it work on wide characters. Fix it. */
2680 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2682 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2685 /* As usual, the possible error values are not documented */
2686 DWORD err = GetLastError();
2687 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2695 /* Replacement for POSIX fnmatch() (partial functionality only) */
2697 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2699 if (PathMatchSpecW(string, pattern))
2705 /* truncate() replacement */
2707 win32_truncate_replacement(const wchar_t *path, off_t size)
2709 DWORD err = NO_ERROR;
2710 LARGE_INTEGER liOffset;
2712 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2713 if (h == INVALID_HANDLE_VALUE)
2716 liOffset.QuadPart = size;
2717 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2718 goto fail_close_handle;
2720 if (!SetEndOfFile(h))
2721 goto fail_close_handle;
2726 err = GetLastError();
2729 if (err == NO_ERROR)
2730 err = GetLastError();
2731 ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2738 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2739 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2740 * linked in by Visual Studio...?). */
2742 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2744 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2746 pthread_mutex_lock(&strerror_lock);
2747 mbstowcs(buf, strerror(errnum), buflen);
2748 buf[buflen - 1] = '\0';
2749 pthread_mutex_unlock(&strerror_lock);
2753 #endif /* __WIN32__ */