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 WARNING("Failed to open \"%ls\" to get file and volume IDs",
605 return WIMLIB_ERR_OPEN;
608 if (!GetFileInformationByHandle(hFile, &file_info)) {
609 err = GetLastError();
610 ERROR("Failed to get file information for \"%ls\"", path);
612 ret = WIMLIB_ERR_STAT;
614 *ino_ret = ((u64)file_info.nFileIndexHigh << 32) |
615 (u64)file_info.nFileIndexLow;
616 *dev_ret = file_info.dwVolumeSerialNumber;
623 /* Reparse point fixup status code */
625 /* Reparse point corresponded to an absolute symbolic link or junction
626 * point that pointed outside the directory tree being captured, and
627 * therefore was excluded. */
630 /* Reparse point was not fixed as it was either a relative symbolic
631 * link, a mount point, or something else we could not understand. */
634 /* Reparse point corresponded to an absolute symbolic link or junction
635 * point that pointed inside the directory tree being captured, where
636 * the target was specified by a "full" \??\ prefixed path, and
637 * therefore was fixed to be relative to the root of the directory tree
639 RP_FIXED_FULLPATH = 0x2,
641 /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
642 * have the \??\ prefix. It may have begun with a drive letter though.
644 RP_FIXED_ABSPATH = 0x4,
646 /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
647 RP_FIXED = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
650 /* Given the "substitute name" target of a Windows reparse point, try doing a
651 * fixup where we change it to be absolute relative to the root of the directory
652 * tree being captured.
654 * Note that this is only executed when WIMLIB_ADD_IMAGE_FLAG_RPFIX has been
657 * @capture_root_ino and @capture_root_dev indicate the inode number and device
658 * of the root of the directory tree being captured. They are meant to identify
659 * this directory (as an alternative to its actual path, which could potentially
660 * be reached via multiple destinations due to other symbolic links). This may
661 * not work properly on FAT, which doesn't seem to supply proper inode numbers
662 * or file IDs. However, FAT doesn't support reparse points so this function
663 * wouldn't even be called anyway.
665 static enum rp_status
666 win32_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
667 u64 capture_root_ino, u64 capture_root_dev,
670 u16 target_nchars = *target_nbytes_p / 2;
671 size_t stripped_chars;
672 wchar_t *orig_target;
675 ret = parse_substitute_name(target, *target_nbytes_p, rptag);
678 stripped_chars = ret;
679 target[target_nchars] = L'\0';
680 orig_target = target;
681 target = fixup_symlink(target + stripped_chars,
682 capture_root_ino, capture_root_dev);
685 target_nchars = wcslen(target);
686 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
687 *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
688 DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
689 if (stripped_chars == 6)
690 return RP_FIXED_FULLPATH;
692 return RP_FIXED_ABSPATH;
695 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
698 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
699 u64 capture_root_ino, u64 capture_root_dev)
701 struct reparse_data rpdata;
704 enum rp_status rp_status;
706 rpbuflen = *rpbuflen_p;
707 ret = parse_reparse_data(rpbuf, rpbuflen, &rpdata);
711 rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
712 &rpdata.substitute_name_nbytes,
715 le32_to_cpu(*(u32*)rpbuf));
716 if (rp_status & RP_FIXED) {
717 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
718 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
719 wmemcpy(substitute_name_copy, rpdata.substitute_name,
720 rpdata.substitute_name_nbytes / 2);
721 rpdata.substitute_name = substitute_name_copy;
722 rpdata.print_name = substitute_name_copy;
723 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
724 if (rp_status == RP_FIXED_FULLPATH) {
725 /* "full path", meaning \??\ prefixed. We should not
726 * include this prefix in the print name, as it is
727 * apparently meant for the filesystem driver only. */
728 rpdata.print_name += 4;
729 rpdata.print_name_nbytes -= 8;
731 ret = make_reparse_buffer(&rpdata, rpbuf);
743 * Loads the reparse point data from a reparse point into memory, optionally
744 * fixing the targets of absolute symbolic links and junction points to be
745 * relative to the root of capture.
747 * @hFile: Open handle to the reparse point.
748 * @path: Path to the reparse point. Used for error messages only.
749 * @params: Additional parameters, including whether to do reparse point fixups
751 * @rpbuf: Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
752 * the reparse point buffer will be loaded.
753 * @rpbuflen_ret: On success, the length of the reparse point buffer in bytes
754 * is written to this location.
757 * On success, returns an `enum rp_status' value that indicates if and/or
758 * how the reparse point fixup was done.
760 * On failure, returns a negative value that is a negated WIMLIB_ERR_*
764 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
765 struct add_image_params *params,
766 u8 *rpbuf, u16 *rpbuflen_ret)
773 DEBUG("Loading reparse data from \"%ls\"", path);
774 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
775 NULL, /* "Not used with this operation; set to NULL" */
776 0, /* "Not used with this operation; set to 0" */
777 rpbuf, /* "A pointer to a buffer that
778 receives the reparse point data */
779 REPARSE_POINT_MAX_SIZE, /* "The size of the output
784 DWORD err = GetLastError();
785 ERROR("Failed to get reparse data of \"%ls\"", path);
787 return -WIMLIB_ERR_READ;
789 if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
790 ERROR("Reparse data on \"%ls\" is invalid", path);
791 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
794 rpbuflen = bytesReturned;
795 reparse_tag = le32_to_cpu(*(u32*)rpbuf);
796 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX &&
797 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
798 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
800 /* Try doing reparse point fixup */
801 ret = win32_capture_try_rpfix(rpbuf,
803 params->capture_root_ino,
804 params->capture_root_dev);
808 *rpbuflen_ret = rpbuflen;
813 win32_tally_encrypted_size_cb(unsigned char *_data, void *_ctx,
817 return ERROR_SUCCESS;
821 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
828 err = OpenEncryptedFileRawW(path, 0, &file_ctx);
829 if (err != ERROR_SUCCESS) {
830 ERROR("Failed to open encrypted file \"%ls\" for raw read", path);
832 return WIMLIB_ERR_OPEN;
834 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
836 if (err != ERROR_SUCCESS) {
837 ERROR("Failed to read raw encrypted data from \"%ls\"", path);
839 ret = WIMLIB_ERR_READ;
843 CloseEncryptedFileRaw(file_ctx);
847 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
848 * stream); calculates its SHA1 message digest and either creates a `struct
849 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
850 * wim_lookup_table_entry' for an identical stream.
852 * @path: Path to the file (UTF-16LE).
854 * @path_num_chars: Number of 2-byte characters in @path.
856 * @inode: WIM inode to save the stream into.
858 * @lookup_table: Stream lookup table for the WIM.
860 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
863 * Returns 0 on success; nonzero on failure.
866 win32_capture_stream(const wchar_t *path,
867 size_t path_num_chars,
868 struct wim_inode *inode,
869 struct wim_lookup_table *lookup_table,
870 WIN32_FIND_STREAM_DATA *dat)
872 struct wim_ads_entry *ads_entry;
873 struct wim_lookup_table_entry *lte;
875 wchar_t *stream_name, *colon;
876 size_t stream_name_nchars;
877 bool is_named_stream;
880 size_t spath_buf_nbytes;
881 const wchar_t *relpath_prefix;
882 const wchar_t *colonchar;
884 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
886 /* The stream name should be returned as :NAME:TYPE */
887 stream_name = dat->cStreamName;
888 if (*stream_name != L':')
889 goto out_invalid_stream_name;
891 colon = wcschr(stream_name, L':');
893 goto out_invalid_stream_name;
895 if (wcscmp(colon + 1, L"$DATA")) {
896 /* Not a DATA stream */
903 stream_name_nchars = colon - stream_name;
904 is_named_stream = (stream_name_nchars != 0);
906 if (is_named_stream) {
907 /* Allocate an ADS entry for the named stream. */
908 ads_entry = inode_add_ads_utf16le(inode, stream_name,
909 stream_name_nchars * sizeof(wchar_t));
911 ret = WIMLIB_ERR_NOMEM;
916 /* If zero length stream, no lookup table entry needed. */
917 if ((u64)dat->StreamSize.QuadPart == 0) {
922 /* Create a UTF-16LE string @spath that gives the filename, then a
923 * colon, then the stream name. Or, if it's an unnamed stream, just the
924 * filename. It is MALLOC()'ed so that it can be saved in the
925 * wim_lookup_table_entry if needed.
927 * As yet another special case, relative paths need to be changed to
928 * begin with an explicit "./" so that, for example, a file t:ads, where
929 * :ads is the part we added, is not interpreted as a file on the t:
931 spath_nchars = path_num_chars;
932 relpath_prefix = L"";
934 if (is_named_stream) {
935 spath_nchars += 1 + stream_name_nchars;
937 if (path_num_chars == 1 &&
942 relpath_prefix = L"./";
946 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
947 spath = MALLOC(spath_buf_nbytes);
949 swprintf(spath, L"%ls%ls%ls%ls",
950 relpath_prefix, path, colonchar, stream_name);
952 /* Make a new wim_lookup_table_entry */
953 lte = new_lookup_table_entry();
955 ret = WIMLIB_ERR_NOMEM;
958 lte->file_on_disk = spath;
960 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
962 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
963 ret = win32_get_encrypted_file_size(path, &encrypted_size);
966 lte->resource_entry.original_size = encrypted_size;
968 lte->resource_location = RESOURCE_WIN32;
969 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
973 if (is_named_stream) {
974 stream_id = ads_entry->stream_id;
975 ads_entry->lte = lte;
980 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
986 out_invalid_stream_name:
987 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
988 ret = WIMLIB_ERR_READ;
992 /* Scans a Win32 file for unnamed and named data streams (not reparse point
995 * @path: Path to the file (UTF-16LE).
997 * @path_num_chars: Number of 2-byte characters in @path.
999 * @inode: WIM inode to save the stream into.
1001 * @lookup_table: Stream lookup table for the WIM.
1003 * @file_size: Size of unnamed data stream. (Used only if alternate
1004 * data streams API appears to be unavailable.)
1006 * @vol_flags: Flags that specify features of the volume being
1009 * Returns 0 on success; nonzero on failure.
1012 win32_capture_streams(const wchar_t *path,
1013 size_t path_num_chars,
1014 struct wim_inode *inode,
1015 struct wim_lookup_table *lookup_table,
1019 WIN32_FIND_STREAM_DATA dat;
1024 DEBUG("Capturing streams from \"%ls\"", path);
1026 if (win32func_FindFirstStreamW == NULL ||
1027 !(vol_flags & FILE_NAMED_STREAMS))
1030 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1031 if (hFind == INVALID_HANDLE_VALUE) {
1032 err = GetLastError();
1033 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1036 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1037 * points and directories */
1038 if ((inode->i_attributes &
1039 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1040 && err == ERROR_HANDLE_EOF)
1042 DEBUG("ERROR_HANDLE_EOF (ok)");
1045 if (err == ERROR_ACCESS_DENIED) {
1046 ERROR("Failed to look up data streams "
1047 "of \"%ls\": Access denied!\n%ls",
1048 path, capture_access_denied_msg);
1049 return WIMLIB_ERR_READ;
1051 ERROR("Failed to look up data streams "
1052 "of \"%ls\"", path);
1054 return WIMLIB_ERR_READ;
1059 ret = win32_capture_stream(path,
1061 inode, lookup_table,
1064 goto out_find_close;
1065 } while (win32func_FindNextStreamW(hFind, &dat));
1066 err = GetLastError();
1067 if (err != ERROR_HANDLE_EOF) {
1068 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
1070 ret = WIMLIB_ERR_READ;
1076 /* FindFirstStreamW() API is not available, or the volume does not
1077 * support named streams. Only capture the unnamed data stream. */
1078 DEBUG("Only capturing unnamed data stream");
1079 if (inode->i_attributes &
1080 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1084 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
1085 * stream to reduce the code to a call to the
1086 * already-implemented win32_capture_stream() */
1087 wcscpy(dat.cStreamName, L"::$DATA");
1088 dat.StreamSize.QuadPart = file_size;
1089 ret = win32_capture_stream(path,
1091 inode, lookup_table,
1098 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1100 size_t path_num_chars,
1101 struct add_image_params *params,
1102 struct win32_capture_state *state,
1105 struct wim_dentry *root = NULL;
1106 struct wim_inode *inode;
1114 if (exclude_path(path, path_num_chars, params->config, true)) {
1115 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
1116 ERROR("Cannot exclude the root directory from capture");
1117 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1120 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
1121 && params->progress_func)
1123 union wimlib_progress_info info;
1124 info.scan.cur_path = path;
1125 info.scan.excluded = true;
1126 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1132 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
1133 && params->progress_func)
1135 union wimlib_progress_info info;
1136 info.scan.cur_path = path;
1137 info.scan.excluded = false;
1138 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1141 HANDLE hFile = win32_open_existing_file(path,
1142 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1143 if (hFile == INVALID_HANDLE_VALUE) {
1144 err = GetLastError();
1145 ERROR("Win32 API: Failed to open \"%ls\"", path);
1147 ret = WIMLIB_ERR_OPEN;
1151 BY_HANDLE_FILE_INFORMATION file_info;
1152 if (!GetFileInformationByHandle(hFile, &file_info)) {
1153 err = GetLastError();
1154 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1157 ret = WIMLIB_ERR_STAT;
1158 goto out_close_handle;
1161 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1162 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1163 ret = win32_get_reparse_data(hFile, path, params,
1166 /* WIMLIB_ERR_* (inverted) */
1168 goto out_close_handle;
1169 } else if (ret & RP_FIXED) {
1171 } else if (ret == RP_EXCLUDED) {
1173 goto out_close_handle;
1179 /* Create a WIM dentry with an associated inode, which may be shared.
1181 * However, we need to explicitly check for directories and files with
1182 * only 1 link and refuse to hard link them. This is because Windows
1183 * has a bug where it can return duplicate File IDs for files and
1184 * directories on the FAT filesystem. */
1185 ret = inode_table_new_dentry(params->inode_table,
1186 path_basename_with_len(path, path_num_chars),
1187 ((u64)file_info.nFileIndexHigh << 32) |
1188 (u64)file_info.nFileIndexLow,
1189 file_info.dwVolumeSerialNumber,
1190 (file_info.nNumberOfLinks <= 1 ||
1191 (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1194 goto out_close_handle;
1196 ret = win32_get_short_name(root, path);
1198 goto out_close_handle;
1200 inode = root->d_inode;
1202 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1203 goto out_close_handle;
1205 inode->i_attributes = file_info.dwFileAttributes;
1206 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1207 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1208 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1209 inode->i_resolved = 1;
1211 params->add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
1213 if (!(params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)
1214 && (vol_flags & FILE_PERSISTENT_ACLS))
1216 ret = win32_get_security_descriptor(root, params->sd_set,
1218 params->add_image_flags);
1220 goto out_close_handle;
1223 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1224 (u64)file_info.nFileSizeLow;
1228 /* Capture the unnamed data stream (only should be present for regular
1229 * files) and any alternate data streams. */
1230 ret = win32_capture_streams(path,
1233 params->lookup_table,
1239 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1240 /* Reparse point: set the reparse data (which we read already)
1242 inode->i_not_rpfixed = not_rpfixed;
1243 inode->i_reparse_tag = le32_to_cpu(*(u32*)rpbuf);
1244 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1245 params->lookup_table);
1246 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1247 /* Directory (not a reparse point) --- recurse to children */
1248 ret = win32_recurse_directory(root,
1262 free_dentry_tree(root, params->lookup_table);
1267 win32_do_capture_warnings(const struct win32_capture_state *state,
1268 int add_image_flags)
1270 if (state->num_get_sacl_priv_notheld == 0 &&
1271 state->num_get_sd_access_denied == 0)
1275 WARNING("Built dentry tree successfully, but with the following problem(s):");
1276 if (state->num_get_sacl_priv_notheld != 0) {
1277 WARNING("Could not capture SACL (System Access Control List)\n"
1278 " on %lu files or directories.",
1279 state->num_get_sacl_priv_notheld);
1281 if (state->num_get_sd_access_denied != 0) {
1282 WARNING("Could not capture security descriptor at all\n"
1283 " on %lu files or directories.",
1284 state->num_get_sd_access_denied);
1287 "Try running the program as the Administrator to make sure all the\n"
1288 " desired metadata has been captured exactly. However, if you\n"
1289 " do not care about capturing security descriptors correctly, then\n"
1290 " nothing more needs to be done%ls\n",
1291 (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
1292 L", although you might consider\n"
1293 " passing the --no-acls flag to `wimlib-imagex capture' or\n"
1294 " `wimlib-imagex append' to explicitly capture no security\n"
1298 /* Win32 version of capturing a directory tree */
1300 win32_build_dentry_tree(struct wim_dentry **root_ret,
1301 const wchar_t *root_disk_path,
1302 struct add_image_params *params)
1307 struct win32_capture_state state;
1311 path_nchars = wcslen(root_disk_path);
1312 if (path_nchars > 32767)
1313 return WIMLIB_ERR_INVALID_PARAM;
1315 ret = win32_get_file_and_vol_ids(root_disk_path,
1316 ¶ms->capture_root_ino,
1317 ¶ms->capture_root_dev);
1321 win32_get_vol_flags(root_disk_path, &vol_flags);
1323 /* There is no check for overflow later when this buffer is being used!
1324 * But the max path length on NTFS is 32767 characters, and paths need
1325 * to be written specially to even go past 260 characters, so we should
1326 * be okay with 32770 characters. */
1327 path = MALLOC(32770 * sizeof(wchar_t));
1329 return WIMLIB_ERR_NOMEM;
1331 wmemcpy(path, root_disk_path, path_nchars + 1);
1333 memset(&state, 0, sizeof(state));
1334 ret = win32_build_dentry_tree_recursive(root_ret, path,
1335 path_nchars, params,
1339 win32_do_capture_warnings(&state, params->add_image_flags);
1344 win32_extract_try_rpfix(u8 *rpbuf,
1345 const wchar_t *extract_root_realpath,
1346 unsigned extract_root_realpath_nchars)
1348 struct reparse_data rpdata;
1350 size_t target_nchars;
1351 size_t stripped_nchars;
1352 wchar_t *stripped_target;
1353 wchar_t stripped_target_nchars;
1356 utf16lechar *new_target;
1357 utf16lechar *new_print_name;
1358 size_t new_target_nchars;
1359 size_t new_print_name_nchars;
1362 ret = parse_reparse_data(rpbuf, 8 + le16_to_cpu(*(u16*)(rpbuf + 4)),
1367 if (extract_root_realpath[0] == L'\0' ||
1368 extract_root_realpath[1] != L':' ||
1369 extract_root_realpath[2] != L'\\')
1371 ERROR("Can't understand full path format \"%ls\". "
1372 "Try turning reparse point fixups off...",
1373 extract_root_realpath);
1374 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1377 ret = parse_substitute_name(rpdata.substitute_name,
1378 rpdata.substitute_name_nbytes,
1382 stripped_nchars = ret;
1383 target = rpdata.substitute_name;
1384 target_nchars = rpdata.substitute_name_nbytes / sizeof(utf16lechar);
1385 stripped_target = target + 6;
1386 stripped_target_nchars = target_nchars - stripped_nchars;
1388 new_target = alloca((6 + extract_root_realpath_nchars +
1389 stripped_target_nchars) * sizeof(utf16lechar));
1392 if (stripped_nchars == 6) {
1393 /* Include \??\ prefix if it was present before */
1394 wmemcpy(p, L"\\??\\", 4);
1398 /* Print name excludes the \??\ if present. */
1400 if (target_nchars - stripped_target_nchars != 0) {
1401 /* Get drive letter from real path to extract root, if a drive
1402 * letter was present before. */
1403 *p++ = extract_root_realpath[0];
1404 *p++ = extract_root_realpath[1];
1406 /* Copy the rest of the extract root */
1407 wmemcpy(p, extract_root_realpath + 2, extract_root_realpath_nchars - 2);
1408 p += extract_root_realpath_nchars - 2;
1410 /* Append the stripped target */
1411 wmemcpy(p, stripped_target, stripped_target_nchars);
1412 p += stripped_target_nchars;
1413 new_target_nchars = p - new_target;
1414 new_print_name_nchars = p - new_print_name;
1416 if (new_target_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE ||
1417 new_print_name_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE)
1419 ERROR("Path names too long to do reparse point fixup!");
1420 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1422 rpdata.substitute_name = new_target;
1423 rpdata.substitute_name_nbytes = new_target_nchars * sizeof(utf16lechar);
1424 rpdata.print_name = new_print_name;
1425 rpdata.print_name_nbytes = new_print_name_nchars * sizeof(utf16lechar);
1426 return make_reparse_buffer(&rpdata, rpbuf);
1429 /* Wrapper around the FSCTL_SET_REPARSE_POINT ioctl to set the reparse data on
1430 * an extracted reparse point. */
1432 win32_set_reparse_data(HANDLE h,
1433 const struct wim_inode *inode,
1434 const struct wim_lookup_table_entry *lte,
1435 const wchar_t *path,
1436 const struct apply_args *args)
1439 u8 rpbuf[REPARSE_POINT_MAX_SIZE];
1440 DWORD bytesReturned;
1442 DEBUG("Setting reparse data on \"%ls\"", path);
1444 ret = wim_inode_get_reparse_data(inode, rpbuf);
1448 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX &&
1449 (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1450 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT) &&
1451 !inode->i_not_rpfixed)
1453 ret = win32_extract_try_rpfix(rpbuf,
1454 args->target_realpath,
1455 args->target_realpath_len);
1457 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1460 /* Set the reparse data on the open file using the
1461 * FSCTL_SET_REPARSE_POINT ioctl.
1463 * There are contradictions in Microsoft's documentation for this:
1465 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1466 * lpOverlapped is ignored."
1468 * --- So setting lpOverlapped to NULL is okay since it's ignored.
1470 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1471 * operation returns no output data and lpOutBuffer is NULL,
1472 * DeviceIoControl makes use of lpBytesReturned. After such an
1473 * operation, the value of lpBytesReturned is meaningless."
1475 * --- So lpOverlapped not really ignored, as it affects another
1476 * parameter. This is the actual behavior: lpBytesReturned must be
1477 * specified, even though lpBytesReturned is documented as:
1479 * "Not used with this operation; set to NULL."
1481 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, rpbuf,
1482 8 + le16_to_cpu(*(u16*)(rpbuf + 4)),
1484 &bytesReturned /* lpBytesReturned */,
1485 NULL /* lpOverlapped */))
1487 DWORD err = GetLastError();
1488 ERROR("Failed to set reparse data on \"%ls\"", path);
1490 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1491 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1492 else if (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1493 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT)
1494 return WIMLIB_ERR_LINK;
1496 return WIMLIB_ERR_WRITE;
1501 /* Wrapper around the FSCTL_SET_COMPRESSION ioctl to change the
1502 * FILE_ATTRIBUTE_COMPRESSED flag of a file or directory. */
1504 win32_set_compression_state(HANDLE hFile, USHORT format, const wchar_t *path)
1506 DWORD bytesReturned;
1507 if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1508 &format, sizeof(USHORT),
1510 &bytesReturned, NULL))
1512 /* Could be a warning only, but we only call this if the volume
1513 * supports compression. So I'm calling this an error. */
1514 DWORD err = GetLastError();
1515 ERROR("Failed to set compression flag on \"%ls\"", path);
1517 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1518 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1520 return WIMLIB_ERR_WRITE;
1525 /* Wrapper around FSCTL_SET_SPARSE ioctl to set a file as sparse. */
1527 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1529 DWORD bytesReturned;
1530 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1533 &bytesReturned, NULL))
1535 /* Could be a warning only, but we only call this if the volume
1536 * supports sparse files. So I'm calling this an error. */
1537 DWORD err = GetLastError();
1538 WARNING("Failed to set sparse flag on \"%ls\"", path);
1540 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1541 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1543 return WIMLIB_ERR_WRITE;
1549 * Sets the security descriptor on an extracted file.
1552 win32_set_security_data(const struct wim_inode *inode,
1554 const wchar_t *path,
1555 struct apply_args *args)
1557 PSECURITY_DESCRIPTOR descriptor;
1560 const struct wim_security_data *sd;
1562 SECURITY_INFORMATION securityInformation = 0;
1569 BOOL owner_defaulted;
1570 BOOL group_defaulted;
1572 BOOL dacl_defaulted;
1574 BOOL sacl_defaulted;
1576 sd = wim_const_security_data(args->w);
1577 descriptor = sd->descriptors[inode->i_security_id];
1579 GetSecurityDescriptorOwner(descriptor, &owner, &owner_defaulted);
1581 securityInformation |= OWNER_SECURITY_INFORMATION;
1583 GetSecurityDescriptorGroup(descriptor, &group, &group_defaulted);
1585 securityInformation |= GROUP_SECURITY_INFORMATION;
1587 GetSecurityDescriptorDacl(descriptor, &dacl_present,
1588 &dacl, &dacl_defaulted);
1590 securityInformation |= DACL_SECURITY_INFORMATION;
1592 GetSecurityDescriptorSacl(descriptor, &sacl_present,
1593 &sacl, &sacl_defaulted);
1595 securityInformation |= SACL_SECURITY_INFORMATION;
1598 if (securityInformation == 0)
1600 if (SetSecurityInfo(hFile, SE_FILE_OBJECT,
1601 securityInformation, owner, group, dacl, sacl))
1603 err = GetLastError();
1604 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1607 case ERROR_PRIVILEGE_NOT_HELD:
1608 if (securityInformation & SACL_SECURITY_INFORMATION) {
1609 n = args->num_set_sacl_priv_notheld++;
1610 securityInformation &= ~SACL_SECURITY_INFORMATION;
1612 if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1614 "We don't have enough privileges to set the full security\n"
1615 " descriptor on \"%ls\"!\n", path);
1616 if (args->num_set_sd_access_denied +
1617 args->num_set_sacl_priv_notheld == 1)
1619 WARNING("%ls", apply_access_denied_msg);
1621 WARNING("Re-trying with SACL omitted.\n", path);
1622 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1624 "Suppressing further 'privileges not held' error messages when setting\n"
1625 " security descriptors.");
1630 case ERROR_INVALID_OWNER:
1631 case ERROR_ACCESS_DENIED:
1632 n = args->num_set_sd_access_denied++;
1633 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1634 WARNING("Failed to set security descriptor on \"%ls\": "
1635 "Access denied!\n", path);
1636 if (args->num_set_sd_access_denied +
1637 args->num_set_sacl_priv_notheld == 1)
1639 WARNING("%ls", apply_access_denied_msg);
1641 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1643 "Suppressing further access denied error messages when setting\n"
1644 " security descriptors");
1649 ERROR("Failed to set security descriptor on \"%ls\"", path);
1651 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1652 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1654 return WIMLIB_ERR_WRITE;
1660 win32_extract_chunk(const void *buf, size_t len, void *arg)
1662 HANDLE hStream = arg;
1664 DWORD nbytes_written;
1665 wimlib_assert(len <= 0xffffffff);
1667 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1668 nbytes_written != len)
1670 DWORD err = GetLastError();
1671 ERROR("WriteFile(): write error");
1673 return WIMLIB_ERR_WRITE;
1679 do_win32_extract_stream(HANDLE hStream, const struct wim_lookup_table_entry *lte)
1681 return extract_wim_resource(lte, wim_resource_size(lte),
1682 win32_extract_chunk, hStream);
1685 struct win32_encrypted_extract_ctx {
1687 int wimlib_err_code;
1689 pthread_cond_t cond;
1690 pthread_mutex_t mutex;
1691 u8 buf[WIM_CHUNK_SIZE];
1696 win32_encrypted_import_cb(unsigned char *data, void *_ctx,
1697 unsigned long *len_p)
1699 struct win32_encrypted_extract_ctx *ctx = _ctx;
1700 unsigned long len = *len_p;
1702 pthread_mutex_lock(&ctx->mutex);
1704 size_t bytes_to_copy;
1706 DEBUG("Importing up to %lu more bytes of raw encrypted data", len);
1707 while (ctx->buf_filled == 0) {
1710 pthread_cond_wait(&ctx->cond, &ctx->mutex);
1712 bytes_to_copy = min(len, ctx->buf_filled);
1713 memcpy(data, ctx->buf, bytes_to_copy);
1714 len -= bytes_to_copy;
1715 data += bytes_to_copy;
1716 ctx->buf_filled -= bytes_to_copy;
1717 memmove(ctx->buf, ctx->buf + bytes_to_copy, ctx->buf_filled);
1718 pthread_cond_signal(&ctx->cond);
1722 pthread_mutex_unlock(&ctx->mutex);
1723 return ERROR_SUCCESS;
1726 /* Extract ("Import") an encrypted file in a different thread. */
1728 win32_encrypted_import_proc(void *arg)
1730 struct win32_encrypted_extract_ctx *ctx = arg;
1732 ret = WriteEncryptedFileRaw(win32_encrypted_import_cb, ctx,
1734 pthread_mutex_lock(&ctx->mutex);
1735 if (ret == ERROR_SUCCESS) {
1736 ctx->wimlib_err_code = 0;
1739 ctx->wimlib_err_code = WIMLIB_ERR_WRITE;
1742 pthread_cond_signal(&ctx->cond);
1743 pthread_mutex_unlock(&ctx->mutex);
1749 win32_extract_raw_encrypted_chunk(const void *buf, size_t len, void *arg)
1751 struct win32_encrypted_extract_ctx *ctx = arg;
1752 size_t bytes_to_copy;
1755 DEBUG("Extracting up to %zu more bytes of encrypted data", len);
1756 pthread_mutex_lock(&ctx->mutex);
1757 while (ctx->buf_filled == WIM_CHUNK_SIZE) {
1759 pthread_mutex_unlock(&ctx->mutex);
1760 return ctx->wimlib_err_code;
1762 pthread_cond_wait(&ctx->cond, &ctx->mutex);
1764 bytes_to_copy = min(len, WIM_CHUNK_SIZE - ctx->buf_filled);
1765 memcpy(&ctx->buf[ctx->buf_filled], buf, bytes_to_copy);
1766 len -= bytes_to_copy;
1767 buf += bytes_to_copy;
1768 ctx->buf_filled += bytes_to_copy;
1769 pthread_cond_signal(&ctx->cond);
1770 pthread_mutex_unlock(&ctx->mutex);
1775 /* Create an encrypted file and extract the raw encrypted data to it.
1777 * @path: Path to encrypted file to create.
1778 * @lte: WIM lookup_table entry for the raw encrypted data.
1780 * This is separate from do_win32_extract_stream() because the WIM is supposed
1781 * to contain the *raw* encrypted data, which needs to be extracted ("imported")
1782 * using the special APIs OpenEncryptedFileRawW(), WriteEncryptedFileRaw(), and
1783 * CloseEncryptedFileRaw().
1785 * Returns 0 on success; nonzero on failure.
1788 do_win32_extract_encrypted_stream(const wchar_t *path,
1789 const struct wim_lookup_table_entry *lte)
1791 struct win32_encrypted_extract_ctx ctx;
1793 pthread_t import_thread;
1797 DEBUG("Opening file \"%ls\" to extract raw encrypted data", path);
1799 ret = OpenEncryptedFileRawW(path, CREATE_FOR_IMPORT, &file_ctx);
1801 ERROR("Failed to open \"%ls\" to write raw encrypted data", path);
1803 return WIMLIB_ERR_OPEN;
1809 /* Hack alert: WriteEncryptedFileRaw() requires the callback function
1810 * to work with a buffer whose size we cannot control. This doesn't
1811 * play well with our read_resource_prefix() function, which itself uses
1812 * a callback function to extract WIM_CHUNK_SIZE chunks of data. We
1813 * work around this problem by calling WriteEncryptedFileRaw() in a
1814 * different thread and feeding it the data as needed. */
1815 ctx.file_ctx = file_ctx;
1818 ctx.wimlib_err_code = 0;
1819 if (pthread_mutex_init(&ctx.mutex, NULL)) {
1820 ERROR_WITH_ERRNO("Can't create mutex");
1821 ret = WIMLIB_ERR_NOMEM;
1824 if (pthread_cond_init(&ctx.cond, NULL)) {
1825 ERROR_WITH_ERRNO("Can't create condition variable");
1826 ret = WIMLIB_ERR_NOMEM;
1827 goto out_pthread_mutex_destroy;
1829 ret = pthread_create(&import_thread, NULL,
1830 win32_encrypted_import_proc, &ctx);
1833 ERROR_WITH_ERRNO("Failed to create thread");
1834 ret = WIMLIB_ERR_FORK;
1835 goto out_pthread_cond_destroy;
1838 ret = extract_wim_resource(lte, wim_resource_size(lte),
1839 win32_extract_raw_encrypted_chunk, &ctx);
1840 pthread_mutex_lock(&ctx.mutex);
1842 pthread_cond_signal(&ctx.cond);
1843 pthread_mutex_unlock(&ctx.mutex);
1844 ret2 = pthread_join(import_thread, NULL);
1847 ERROR_WITH_ERRNO("Failed to join encrypted import thread");
1849 ret = WIMLIB_ERR_WRITE;
1852 ret = ctx.wimlib_err_code;
1853 out_pthread_cond_destroy:
1854 pthread_cond_destroy(&ctx.cond);
1855 out_pthread_mutex_destroy:
1856 pthread_mutex_destroy(&ctx.mutex);
1858 CloseEncryptedFileRaw(file_ctx);
1860 ERROR("Failed to extract encrypted file \"%ls\"", path);
1865 path_is_root_of_drive(const wchar_t *path)
1870 if (*path != L'/' && *path != L'\\') {
1871 if (*(path + 1) == L':')
1876 while (*path == L'/' || *path == L'\\')
1878 return (*path == L'\0');
1882 win32_mask_attributes(DWORD i_attributes)
1884 return i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1885 FILE_ATTRIBUTE_COMPRESSED |
1886 FILE_ATTRIBUTE_REPARSE_POINT |
1887 FILE_ATTRIBUTE_DIRECTORY |
1888 FILE_ATTRIBUTE_ENCRYPTED |
1889 FILE_FLAG_DELETE_ON_CLOSE |
1890 FILE_FLAG_NO_BUFFERING |
1891 FILE_FLAG_OPEN_NO_RECALL |
1892 FILE_FLAG_OVERLAPPED |
1893 FILE_FLAG_RANDOM_ACCESS |
1894 /*FILE_FLAG_SESSION_AWARE |*/
1895 FILE_FLAG_SEQUENTIAL_SCAN |
1896 FILE_FLAG_WRITE_THROUGH);
1900 win32_get_create_flags_and_attributes(DWORD i_attributes)
1903 * Some attributes cannot be set by passing them to CreateFile(). In
1906 * FILE_ATTRIBUTE_DIRECTORY:
1907 * CreateDirectory() must be called instead of CreateFile().
1909 * FILE_ATTRIBUTE_SPARSE_FILE:
1911 * See: win32_set_sparse().
1913 * FILE_ATTRIBUTE_COMPRESSED:
1914 * Not clear from the documentation, but apparently this needs an
1916 * See: win32_set_compressed().
1918 * FILE_ATTRIBUTE_REPARSE_POINT:
1919 * Needs an ioctl, with the reparse data specified.
1920 * See: win32_set_reparse_data().
1922 * In addition, clear any file flags in the attributes that we don't
1923 * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1924 * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1926 return win32_mask_attributes(i_attributes) |
1927 FILE_FLAG_OPEN_REPARSE_POINT |
1928 FILE_FLAG_BACKUP_SEMANTICS;
1931 /* Set compression and/or sparse attributes on a stream, if supported by the
1934 win32_set_special_stream_attributes(HANDLE hFile, const struct wim_inode *inode,
1935 struct wim_lookup_table_entry *unnamed_stream_lte,
1936 const wchar_t *path, unsigned vol_flags)
1940 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1941 if (vol_flags & FILE_FILE_COMPRESSION) {
1942 ret = win32_set_compression_state(hFile,
1943 COMPRESSION_FORMAT_DEFAULT,
1948 DEBUG("Cannot set compression attribute on \"%ls\": "
1949 "volume does not support transparent compression",
1954 if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1955 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1956 DEBUG("Setting sparse flag on \"%ls\"", path);
1957 ret = win32_set_sparse(hFile, path);
1961 DEBUG("Cannot set sparse attribute on \"%ls\": "
1962 "volume does not support sparse files",
1969 /* Pre-create directories; extract encrypted streams */
1971 win32_begin_extract_unnamed_stream(const struct wim_inode *inode,
1972 const struct wim_lookup_table_entry *lte,
1973 const wchar_t *path,
1974 DWORD *creationDisposition_ret,
1975 unsigned int vol_flags)
1980 /* Directories must be created with CreateDirectoryW(). Then the call
1981 * to CreateFileW() will merely open the directory that was already
1982 * created rather than creating a new file. */
1983 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY &&
1984 !path_is_root_of_drive(path)) {
1985 if (!CreateDirectoryW(path, NULL)) {
1986 err = GetLastError();
1987 if (err != ERROR_ALREADY_EXISTS) {
1988 ERROR("Failed to create directory \"%ls\"",
1991 return WIMLIB_ERR_MKDIR;
1994 DEBUG("Created directory \"%ls\"", path);
1995 *creationDisposition_ret = OPEN_EXISTING;
1997 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED &&
1998 vol_flags & FILE_SUPPORTS_ENCRYPTION)
2000 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
2001 if (!EncryptFile(path)) {
2002 err = GetLastError();
2003 ERROR("Failed to encrypt directory \"%ls\"",
2006 return WIMLIB_ERR_WRITE;
2009 ret = do_win32_extract_encrypted_stream(path, lte);
2012 DEBUG("Extracted encrypted file \"%ls\"", path);
2014 *creationDisposition_ret = OPEN_EXISTING;
2017 /* Set file attributes if we created the file. Otherwise, we haven't
2018 * created the file set and we will set the attributes in the call to
2021 * The FAT filesystem does not let you change the attributes of the root
2022 * directory, so treat that as a special case and do not set attributes.
2024 if (*creationDisposition_ret == OPEN_EXISTING &&
2025 !path_is_root_of_drive(path))
2027 if (!SetFileAttributesW(path,
2028 win32_mask_attributes(inode->i_attributes)))
2030 err = GetLastError();
2031 ERROR("Failed to set attributes on \"%ls\"", path);
2033 return WIMLIB_ERR_WRITE;
2039 /* Set security descriptor and extract stream data or reparse data (skip the
2040 * unnamed data stream of encrypted files, which was already extracted). */
2042 win32_finish_extract_stream(HANDLE h, const struct wim_inode *inode,
2043 const struct wim_lookup_table_entry *lte,
2044 const wchar_t *stream_path,
2045 const wchar_t *stream_name_utf16,
2046 struct apply_args *args)
2049 if (stream_name_utf16 == NULL) {
2050 /* Unnamed stream. */
2052 /* Set security descriptor, unless the extract_flags indicate
2053 * not to or the volume does not supported it. Note that this
2054 * is only done when the unnamed stream is being extracted, as
2055 * security descriptors are per-file and not per-stream. */
2056 if (inode->i_security_id >= 0 &&
2057 !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
2058 && (args->vol_flags & FILE_PERSISTENT_ACLS))
2060 ret = win32_set_security_data(inode, h, stream_path, args);
2065 /* Handle reparse points. The data for them needs to be set
2066 * using a special ioctl. Note that the reparse point may have
2067 * been created using CreateFileW() in the case of
2068 * non-directories or CreateDirectoryW() in the case of
2069 * directories; but the ioctl works either way. Also, it is
2070 * only this step that actually sets the
2071 * FILE_ATTRIBUTE_REPARSE_POINT, as it is not valid to set it
2072 * using SetFileAttributesW() or CreateFileW().
2074 * If the volume does not support reparse points we simply
2075 * ignore the reparse data. (N.B. the code currently doesn't
2076 * actually reach this case because reparse points are skipped
2077 * entirely on such volumes.) */
2078 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2079 if (args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
2080 ret = win32_set_reparse_data(h, inode,
2086 DEBUG("Cannot set reparse data on \"%ls\": volume "
2087 "does not support reparse points", stream_path);
2089 } else if (lte != NULL &&
2090 !(args->vol_flags & FILE_SUPPORTS_ENCRYPTION &&
2091 inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2093 /* Extract the data of the unnamed stream, unless the
2094 * lookup table entry is NULL (indicating an empty
2095 * stream for which no data needs to be extracted), or
2096 * the stream is encrypted and therefore was already
2097 * extracted as a special case. */
2098 ret = do_win32_extract_stream(h, lte);
2101 /* Extract the data for a named data stream. */
2103 DEBUG("Extracting named data stream \"%ls\" (len = %"PRIu64")",
2104 stream_path, wim_resource_size(lte));
2105 ret = do_win32_extract_stream(h, lte);
2112 win32_decrypt_file(HANDLE open_handle, const wchar_t *path)
2115 /* We cannot call DecryptFileW() while there is an open handle to the
2116 * file. So close it first. */
2117 if (!CloseHandle(open_handle)) {
2118 err = GetLastError();
2119 ERROR("Failed to close handle for \"%ls\"", path);
2121 return WIMLIB_ERR_WRITE;
2123 if (!DecryptFileW(path, 0 /* reserved parameter; set to 0 */)) {
2124 err = GetLastError();
2125 ERROR("Failed to decrypt file \"%ls\"", path);
2127 return WIMLIB_ERR_WRITE;
2133 * Create and extract a stream to a file, or create a directory, using the
2136 * This handles reparse points, directories, alternate data streams, encrypted
2137 * files, compressed files, etc.
2139 * @inode: WIM inode containing the stream.
2141 * @path: Path to extract the file to.
2143 * @stream_name_utf16:
2144 * Name of the stream, or NULL if the stream is unnamed. This will
2145 * be called with a NULL stream_name_utf16 before any non-NULL
2146 * stream_name_utf16's.
2148 * @lte: WIM lookup table entry for the stream. May be NULL to indicate
2149 * a stream of length 0.
2151 * @args: Additional apply context, including flags indicating supported
2154 * Returns 0 on success; nonzero on failure.
2157 win32_extract_stream(const struct wim_inode *inode,
2158 const wchar_t *path,
2159 const wchar_t *stream_name_utf16,
2160 struct wim_lookup_table_entry *lte,
2161 struct apply_args *args)
2163 wchar_t *stream_path;
2167 DWORD creationDisposition = CREATE_ALWAYS;
2168 DWORD requestedAccess;
2169 BY_HANDLE_FILE_INFORMATION file_info;
2171 if (stream_name_utf16) {
2172 /* Named stream. Create a buffer that contains the UTF-16LE
2173 * string [./]path:stream_name_utf16. This is needed to
2174 * create and open the stream using CreateFileW(). I'm not
2175 * aware of any other APIs to do this. Note: the '$DATA' suffix
2176 * seems to be unneeded. Additional note: a "./" prefix needs
2177 * to be added when the path is not absolute to avoid ambiguity
2178 * with drive letters. */
2179 size_t stream_path_nchars;
2181 size_t stream_name_nchars;
2182 const wchar_t *prefix;
2184 path_nchars = wcslen(path);
2185 stream_name_nchars = wcslen(stream_name_utf16);
2186 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
2187 if (path[0] != cpu_to_le16(L'\0') &&
2188 path[0] != cpu_to_le16(L'/') &&
2189 path[0] != cpu_to_le16(L'\\') &&
2190 path[1] != cpu_to_le16(L':'))
2193 stream_path_nchars += 2;
2197 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
2198 swprintf(stream_path, L"%ls%ls:%ls",
2199 prefix, path, stream_name_utf16);
2201 /* Unnamed stream; its path is just the path to the file itself.
2203 stream_path = (wchar_t*)path;
2205 ret = win32_begin_extract_unnamed_stream(inode, lte, path,
2206 &creationDisposition,
2212 DEBUG("Opening \"%ls\"", stream_path);
2213 requestedAccess = GENERIC_READ | GENERIC_WRITE |
2214 ACCESS_SYSTEM_SECURITY;
2216 /* Open the stream to be extracted. Depending on what we have set
2217 * creationDisposition to, we may be creating this for the first time,
2218 * or we may be opening on existing stream we already created using
2219 * CreateDirectoryW() or OpenEncryptedFileRawW(). */
2220 h = CreateFileW(stream_path,
2224 creationDisposition,
2225 win32_get_create_flags_and_attributes(inode->i_attributes),
2227 if (h == INVALID_HANDLE_VALUE) {
2228 err = GetLastError();
2229 if (err == ERROR_ACCESS_DENIED &&
2230 path_is_root_of_drive(stream_path))
2235 if ((err == ERROR_PRIVILEGE_NOT_HELD ||
2236 err == ERROR_ACCESS_DENIED) &&
2237 (requestedAccess & ACCESS_SYSTEM_SECURITY))
2239 /* Try opening the file again without privilege to
2241 requestedAccess &= ~ACCESS_SYSTEM_SECURITY;
2242 goto try_open_again;
2244 ERROR("Failed to create \"%ls\"", stream_path);
2246 ret = WIMLIB_ERR_OPEN;
2250 /* Check the attributes of the file we just opened, and remove
2251 * encryption or compression if either was set by default but is not
2252 * supposed to be set based on the WIM inode attributes. */
2253 if (!GetFileInformationByHandle(h, &file_info)) {
2254 err = GetLastError();
2255 ERROR("Failed to get attributes of \"%ls\"", stream_path);
2257 ret = WIMLIB_ERR_STAT;
2258 goto fail_close_handle;
2261 /* Remove encryption? */
2262 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED &&
2263 !(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2265 /* File defaulted to encrypted due to being in an encrypted
2266 * directory, but is not actually supposed to be encrypted.
2268 * This is a workaround, because I'm not aware of any way to
2269 * directly (e.g. with CreateFileW()) create an unencrypted file
2270 * in a directory with FILE_ATTRIBUTE_ENCRYPTED set. */
2271 ret = win32_decrypt_file(h, stream_path);
2273 goto fail; /* win32_decrypt_file() closed the handle. */
2274 creationDisposition = OPEN_EXISTING;
2275 goto try_open_again;
2278 /* Remove compression? */
2279 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED &&
2280 !(inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED))
2282 /* Similar to the encrypted case, above, if the file defaulted
2283 * to compressed due to being in an compressed directory, but is
2284 * not actually supposed to be compressed, explicitly set the
2285 * compression format to COMPRESSION_FORMAT_NONE. */
2286 ret = win32_set_compression_state(h, COMPRESSION_FORMAT_NONE,
2289 goto fail_close_handle;
2292 /* Set compression and/or sparse attributes if needed */
2293 ret = win32_set_special_stream_attributes(h, inode, lte, path,
2297 goto fail_close_handle;
2299 /* At this point we have at least created the needed stream with the
2300 * appropriate attributes. We have yet to set the appropriate security
2301 * descriptor and actually extract the stream data (other than for
2302 * extracted files, which were already extracted).
2303 * win32_finish_extract_stream() handles these additional steps. */
2304 ret = win32_finish_extract_stream(h, inode, lte, stream_path,
2305 stream_name_utf16, args);
2307 goto fail_close_handle;
2309 /* Done extracting the stream. Close the handle and return. */
2310 DEBUG("Closing \"%ls\"", stream_path);
2311 if (!CloseHandle(h)) {
2312 err = GetLastError();
2313 ERROR("Failed to close \"%ls\"", stream_path);
2315 ret = WIMLIB_ERR_WRITE;
2323 ERROR("Error extracting \"%ls\"", stream_path);
2329 * Creates a file, directory, or reparse point and extracts all streams to it
2330 * (unnamed data stream and/or reparse point stream, plus any alternate data
2331 * streams). Handles sparse, compressed, and/or encrypted files.
2333 * @inode: WIM inode for this file or directory.
2334 * @path: UTF-16LE external path to extract the inode to.
2335 * @args: Additional extraction context.
2337 * Returns 0 on success; nonzero on failure.
2340 win32_extract_streams(const struct wim_inode *inode,
2341 const wchar_t *path, struct apply_args *args)
2343 struct wim_lookup_table_entry *unnamed_lte;
2346 /* First extract the unnamed stream. */
2348 unnamed_lte = inode_unnamed_lte_resolved(inode);
2349 ret = win32_extract_stream(inode, path, NULL, unnamed_lte, args);
2353 /* Extract any named streams, if supported by the volume. */
2355 if (!(args->vol_flags & FILE_NAMED_STREAMS))
2357 for (u16 i = 0; i < inode->i_num_ads; i++) {
2358 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
2360 /* Skip the unnamed stream if it's in the ADS entries (we
2361 * already extracted it...) */
2362 if (ads_entry->stream_name_nbytes == 0)
2365 /* Skip special UNIX data entries (see documentation for
2366 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
2367 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
2368 && !memcmp(ads_entry->stream_name,
2369 WIMLIB_UNIX_DATA_TAG_UTF16LE,
2370 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
2373 /* Extract the named stream */
2374 ret = win32_extract_stream(inode,
2376 ads_entry->stream_name,
2386 /* If not done already, load the supported feature flags for the volume onto
2387 * which the image is being extracted, and warn the user about any missing
2388 * features that could be important. */
2390 win32_check_vol_flags(const wchar_t *output_path, struct apply_args *args)
2392 if (args->have_vol_flags)
2395 win32_get_vol_flags(output_path, &args->vol_flags);
2396 args->have_vol_flags = true;
2397 /* Warn the user about data that may not be extracted. */
2398 if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
2399 WARNING("Volume does not support sparse files!\n"
2400 " Sparse files will be extracted as non-sparse.");
2401 if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2402 WARNING("Volume does not support reparse points!\n"
2403 " Reparse point data will not be extracted.");
2404 if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
2405 WARNING("Volume does not support named data streams!\n"
2406 " Named data streams will not be extracted.");
2408 if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
2409 WARNING("Volume does not support encryption!\n"
2410 " Encrypted files will be extracted as raw data.");
2412 if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
2413 WARNING("Volume does not support transparent compression!\n"
2414 " Compressed files will be extracted as non-compressed.");
2416 if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
2417 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
2418 ERROR("Strict ACLs requested, but the volume does not "
2420 return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
2422 WARNING("Volume does not support persistent ACLS!\n"
2423 " File permissions will not be extracted.");
2430 * Try extracting a hard link.
2432 * @output_path: Path to link to be extracted.
2434 * @inode: WIM inode that the link is to; inode->i_extracted_file
2435 * the path to a name of the file that has already been
2436 * extracted (we use this to create the hard link).
2438 * @args: Additional apply context, used here to keep track of
2439 * the number of times creating a hard link failed due to
2440 * ERROR_INVALID_FUNCTION. This error should indicate that hard
2441 * links are not supported by the volume, and we would like to
2442 * warn the user a few times, but not too many times.
2444 * Returns 0 if the hard link was successfully extracted. Returns
2445 * WIMLIB_ERR_LINK (> 0) if an error occurred, other than hard links possibly
2446 * being unsupported by the volume. Returns a negative value if creating the
2447 * hard link failed due to ERROR_INVALID_FUNCTION.
2450 win32_try_hard_link(const wchar_t *output_path, const struct wim_inode *inode,
2451 struct apply_args *args)
2455 /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
2456 * but it's only available on Windows 7 and later. So no use
2457 * even checking it, really. Instead, CreateHardLinkW() will
2458 * apparently return ERROR_INVALID_FUNCTION if the volume does
2459 * not support hard links. */
2460 DEBUG("Creating hard link \"%ls => %ls\"",
2461 output_path, inode->i_extracted_file);
2462 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
2465 err = GetLastError();
2466 if (err != ERROR_INVALID_FUNCTION) {
2467 ERROR("Can't create hard link \"%ls => %ls\"",
2468 output_path, inode->i_extracted_file);
2470 return WIMLIB_ERR_LINK;
2472 args->num_hard_links_failed++;
2473 if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
2474 WARNING("Can't create hard link \"%ls => %ls\":\n"
2475 " Volume does not support hard links!\n"
2476 " Falling back to extracting a copy of the file.",
2477 output_path, inode->i_extracted_file);
2478 } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
2479 WARNING("Suppressing further hard linking warnings...");
2485 /* Extract a file, directory, reparse point, or hard link to an
2486 * already-extracted file using the Win32 API */
2488 win32_do_apply_dentry(const wchar_t *output_path,
2489 size_t output_path_num_chars,
2490 struct wim_dentry *dentry,
2491 struct apply_args *args)
2494 struct wim_inode *inode = dentry->d_inode;
2496 ret = win32_check_vol_flags(output_path, args);
2499 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
2500 /* Linked file, with another name already extracted. Create a
2502 ret = win32_try_hard_link(output_path, inode, args);
2505 /* Negative return value from win32_try_hard_link() indicates
2506 * that hard links are probably not supported by the volume.
2507 * Fall back to extracting a copy of the file. */
2510 /* If this is a reparse point and the volume does not support reparse
2511 * points, just skip it completely. */
2512 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2513 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2515 WARNING("Skipping extraction of reparse point \"%ls\":\n"
2516 " Not supported by destination filesystem",
2519 /* Create the file, directory, or reparse point, and extract the
2521 ret = win32_extract_streams(inode, output_path, args);
2525 if (inode->i_extracted_file == NULL) {
2526 const struct wim_lookup_table_entry *lte;
2528 /* Tally bytes extracted, including all alternate data streams,
2529 * unless we extracted a hard link (or, at least extracted a
2530 * name that was supposed to be a hard link) */
2531 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
2532 lte = inode_stream_lte_resolved(inode, i);
2534 args->progress.extract.completed_bytes +=
2535 wim_resource_size(lte);
2537 if (inode->i_nlink > 1) {
2538 /* Save extracted path for a later call to
2539 * CreateHardLinkW() if this inode has multiple links.
2541 inode->i_extracted_file = WSTRDUP(output_path);
2542 if (!inode->i_extracted_file)
2543 return WIMLIB_ERR_NOMEM;
2549 /* Set timestamps on an extracted file using the Win32 API */
2551 win32_do_apply_dentry_timestamps(const wchar_t *path,
2552 size_t path_num_chars,
2553 const struct wim_dentry *dentry,
2554 const struct apply_args *args)
2558 const struct wim_inode *inode = dentry->d_inode;
2560 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2561 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2563 /* Skip reparse points not extracted */
2567 /* Windows doesn't let you change the timestamps of the root directory
2568 * (at least on FAT, which is dumb but expected since FAT doesn't store
2569 * any metadata about the root directory...) */
2570 if (path_is_root_of_drive(path))
2573 DEBUG("Opening \"%ls\" to set timestamps", path);
2574 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
2575 if (h == INVALID_HANDLE_VALUE) {
2576 err = GetLastError();
2580 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
2581 .dwHighDateTime = inode->i_creation_time >> 32};
2582 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
2583 .dwHighDateTime = inode->i_last_access_time >> 32};
2584 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
2585 .dwHighDateTime = inode->i_last_write_time >> 32};
2587 DEBUG("Calling SetFileTime() on \"%ls\"", path);
2588 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
2589 err = GetLastError();
2593 DEBUG("Closing \"%ls\"", path);
2594 if (!CloseHandle(h)) {
2595 err = GetLastError();
2600 /* Only warn if setting timestamps failed; still return 0. */
2601 WARNING("Can't set timestamps on \"%ls\"", path);
2607 /* Replacement for POSIX fsync() */
2614 h = (HANDLE)_get_osfhandle(fd);
2615 if (h == INVALID_HANDLE_VALUE) {
2616 err = GetLastError();
2617 ERROR("Could not get Windows handle for file descriptor");
2622 if (!FlushFileBuffers(h)) {
2623 err = GetLastError();
2624 ERROR("Could not flush file buffers to disk");
2632 /* Use the Win32 API to get the number of processors */
2634 win32_get_number_of_processors()
2636 SYSTEM_INFO sysinfo;
2637 GetSystemInfo(&sysinfo);
2638 return sysinfo.dwNumberOfProcessors;
2641 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
2642 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
2643 * really does the right thing under all circumstances. */
2645 realpath(const wchar_t *path, wchar_t *resolved_path)
2648 wimlib_assert(resolved_path == NULL);
2651 ret = GetFullPathNameW(path, 0, NULL, NULL);
2653 err = GetLastError();
2657 resolved_path = TMALLOC(ret);
2660 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2662 err = GetLastError();
2663 free(resolved_path);
2664 resolved_path = NULL;
2672 return resolved_path;
2675 /* rename() on Windows fails if the destination file exists. And we need to
2676 * make it work on wide characters. Fix it. */
2678 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2680 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2683 /* As usual, the possible error values are not documented */
2684 DWORD err = GetLastError();
2685 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2693 /* Replacement for POSIX fnmatch() (partial functionality only) */
2695 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2697 if (PathMatchSpecW(string, pattern))
2703 /* truncate() replacement */
2705 win32_truncate_replacement(const wchar_t *path, off_t size)
2707 DWORD err = NO_ERROR;
2708 LARGE_INTEGER liOffset;
2710 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2711 if (h == INVALID_HANDLE_VALUE)
2714 liOffset.QuadPart = size;
2715 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2716 goto fail_close_handle;
2718 if (!SetEndOfFile(h))
2719 goto fail_close_handle;
2724 err = GetLastError();
2727 if (err == NO_ERROR)
2728 err = GetLastError();
2729 ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2736 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2737 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2738 * linked in by Visual Studio...?). */
2740 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2742 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2744 pthread_mutex_lock(&strerror_lock);
2745 mbstowcs(buf, strerror(errnum), buflen);
2746 buf[buflen - 1] = '\0';
2747 pthread_mutex_unlock(&strerror_lock);
2751 #endif /* __WIN32__ */