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. */
664 static enum rp_status
665 win32_maybe_rpfix_target(wchar_t *target, size_t *target_nchars_p,
666 u64 capture_root_ino, u64 capture_root_dev)
668 size_t target_nchars= *target_nchars_p;
669 size_t stripped_chars;
670 wchar_t *orig_target;
672 if (target_nchars == 0)
673 /* Invalid reparse point (empty target) */
676 if (target[0] == L'\\') {
677 if (target_nchars >= 2 && target[1] == L'\\') {
678 /* Probably a volume. Can't do anything with it. */
679 DEBUG("Not fixing target (probably a volume)");
681 } else if (target_nchars >= 7 &&
689 DEBUG("Full style path");
690 /* Full \??\x:\ style path (may be junction or symlink)
694 DEBUG("Absolute target without drive letter");
695 /* Absolute target, without drive letter */
698 } else if (target_nchars >= 3 &&
699 target[0] != L'\0' &&
703 DEBUG("Absolute target with drive letter");
704 /* Absolute target, with drive letter */
707 DEBUG("Relative symlink or other link");
708 /* Relative symlink or other unexpected format */
711 target[target_nchars] = L'\0';
712 orig_target = target;
713 target = fixup_symlink(target + stripped_chars, capture_root_ino, capture_root_dev);
716 target_nchars = wcslen(target);
717 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
718 *target_nchars_p = target_nchars + stripped_chars;
719 DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
720 if (stripped_chars == 6)
721 return RP_FIXED_FULLPATH;
723 return RP_FIXED_ABSPATH;
726 static enum rp_status
727 win32_try_capture_rpfix(char *rpbuf, DWORD *rpbuflen_p,
728 u64 capture_root_ino, u64 capture_root_dev)
732 u16 substitute_name_offset;
733 u16 substitute_name_len;
735 size_t target_nchars;
736 enum rp_status status;
738 DWORD rpbuflen = *rpbuflen_p;
740 if (rpbuflen < 16) /* Invalid reparse point (length too small) */
742 p_get = get_u32(rpbuf, &rptag);
744 p_get = get_u16(p_get, &substitute_name_offset);
745 p_get = get_u16(p_get, &substitute_name_len);
747 if (rptag == WIM_IO_REPARSE_TAG_SYMLINK) {
748 if (rpbuflen < 20) /* Invalid reparse point (length too small) */
752 if ((DWORD)substitute_name_offset +
753 substitute_name_len + (p_get - rpbuf) > rpbuflen)
754 /* Invalid reparse point (length too small) */
757 target = (wchar_t*)&p_get[substitute_name_offset];
758 target_nchars = substitute_name_len / 2;
759 /* Note: target is not necessarily null-terminated */
761 status = win32_maybe_rpfix_target(target, &target_nchars,
762 capture_root_ino, capture_root_dev);
763 if (status & RP_FIXED) {
764 size_t target_nbytes = target_nchars * 2;
765 size_t print_nbytes = target_nbytes;
766 wchar_t target_copy[target_nchars];
767 wchar_t *print_name = target_copy;
769 if (status == RP_FIXED_FULLPATH) {
770 /* "full path", meaning \??\ prefixed. We should not
771 * include this prefix in the print name, as it is
772 * apparently meant for the filesystem driver only. */
776 wmemcpy(target_copy, target, target_nchars);
778 p_put = put_u16(p_put, 0); /* Substitute name offset */
779 p_put = put_u16(p_put, target_nbytes); /* Substitute name length */
780 p_put = put_u16(p_put, target_nbytes + 2); /* Print name offset */
781 p_put = put_u16(p_put, print_nbytes); /* Print name length */
782 if (rptag == WIM_IO_REPARSE_TAG_SYMLINK)
783 p_put = put_u32(p_put, 1);
784 p_put = put_bytes(p_put, target_nbytes, target_copy);
785 p_put = put_u16(p_put, 0);
786 p_put = put_bytes(p_put, print_nbytes, print_name);
787 p_put = put_u16(p_put, 0);
789 /* Wrote the end of the reparse data. Recalculate the length,
790 * set the length field correctly, and return it. */
791 rpbuflen = p_put - rpbuf;
792 put_u16(rpbuf + 4, rpbuflen - 8);
793 *rpbuflen_p = rpbuflen;
799 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
800 struct add_image_params *params,
801 void *reparse_data, size_t *reparse_data_len_ret)
805 enum rp_status status;
807 DEBUG("Loading reparse data from \"%ls\"", path);
808 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
809 NULL, /* "Not used with this operation; set to NULL" */
810 0, /* "Not used with this operation; set to 0" */
811 reparse_data, /* "A pointer to a buffer that
812 receives the reparse point data */
813 REPARSE_POINT_MAX_SIZE, /* "The size of the output
818 DWORD err = GetLastError();
819 ERROR("Failed to get reparse data of \"%ls\"", path);
821 return -WIMLIB_ERR_READ;
823 if (bytesReturned < 8) {
824 ERROR("Reparse data on \"%ls\" is invalid", path);
825 return -WIMLIB_ERR_READ;
828 reparse_tag = le32_to_cpu(*(u32*)reparse_data);
829 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX &&
830 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
831 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
833 /* Try doing reparse point fixup */
834 status = win32_try_capture_rpfix(reparse_data,
836 params->capture_root_ino,
837 params->capture_root_dev);
839 status = RP_NOT_FIXED;
841 *reparse_data_len_ret = bytesReturned;
846 win32_tally_encrypted_size_cb(unsigned char *_data, void *_ctx,
850 return ERROR_SUCCESS;
854 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
861 err = OpenEncryptedFileRawW(path, 0, &file_ctx);
862 if (err != ERROR_SUCCESS) {
863 ERROR("Failed to open encrypted file \"%ls\" for raw read", path);
865 return WIMLIB_ERR_OPEN;
867 err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
869 if (err != ERROR_SUCCESS) {
870 ERROR("Failed to read raw encrypted data from \"%ls\"", path);
872 ret = WIMLIB_ERR_READ;
876 CloseEncryptedFileRaw(file_ctx);
880 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
881 * stream); calculates its SHA1 message digest and either creates a `struct
882 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
883 * wim_lookup_table_entry' for an identical stream.
885 * @path: Path to the file (UTF-16LE).
887 * @path_num_chars: Number of 2-byte characters in @path.
889 * @inode: WIM inode to save the stream into.
891 * @lookup_table: Stream lookup table for the WIM.
893 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
896 * Returns 0 on success; nonzero on failure.
899 win32_capture_stream(const wchar_t *path,
900 size_t path_num_chars,
901 struct wim_inode *inode,
902 struct wim_lookup_table *lookup_table,
903 WIN32_FIND_STREAM_DATA *dat)
905 struct wim_ads_entry *ads_entry;
906 struct wim_lookup_table_entry *lte;
908 wchar_t *stream_name, *colon;
909 size_t stream_name_nchars;
910 bool is_named_stream;
913 size_t spath_buf_nbytes;
914 const wchar_t *relpath_prefix;
915 const wchar_t *colonchar;
917 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
919 /* The stream name should be returned as :NAME:TYPE */
920 stream_name = dat->cStreamName;
921 if (*stream_name != L':')
922 goto out_invalid_stream_name;
924 colon = wcschr(stream_name, L':');
926 goto out_invalid_stream_name;
928 if (wcscmp(colon + 1, L"$DATA")) {
929 /* Not a DATA stream */
936 stream_name_nchars = colon - stream_name;
937 is_named_stream = (stream_name_nchars != 0);
939 if (is_named_stream) {
940 /* Allocate an ADS entry for the named stream. */
941 ads_entry = inode_add_ads_utf16le(inode, stream_name,
942 stream_name_nchars * sizeof(wchar_t));
944 ret = WIMLIB_ERR_NOMEM;
949 /* If zero length stream, no lookup table entry needed. */
950 if ((u64)dat->StreamSize.QuadPart == 0) {
955 /* Create a UTF-16LE string @spath that gives the filename, then a
956 * colon, then the stream name. Or, if it's an unnamed stream, just the
957 * filename. It is MALLOC()'ed so that it can be saved in the
958 * wim_lookup_table_entry if needed.
960 * As yet another special case, relative paths need to be changed to
961 * begin with an explicit "./" so that, for example, a file t:ads, where
962 * :ads is the part we added, is not interpreted as a file on the t:
964 spath_nchars = path_num_chars;
965 relpath_prefix = L"";
967 if (is_named_stream) {
968 spath_nchars += 1 + stream_name_nchars;
970 if (path_num_chars == 1 &&
975 relpath_prefix = L"./";
979 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
980 spath = MALLOC(spath_buf_nbytes);
982 swprintf(spath, L"%ls%ls%ls%ls",
983 relpath_prefix, path, colonchar, stream_name);
985 /* Make a new wim_lookup_table_entry */
986 lte = new_lookup_table_entry();
988 ret = WIMLIB_ERR_NOMEM;
991 lte->file_on_disk = spath;
993 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
995 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
996 ret = win32_get_encrypted_file_size(path, &encrypted_size);
999 lte->resource_entry.original_size = encrypted_size;
1001 lte->resource_location = RESOURCE_WIN32;
1002 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
1006 if (is_named_stream) {
1007 stream_id = ads_entry->stream_id;
1008 ads_entry->lte = lte;
1013 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
1019 out_invalid_stream_name:
1020 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
1021 ret = WIMLIB_ERR_READ;
1025 /* Scans a Win32 file for unnamed and named data streams (not reparse point
1028 * @path: Path to the file (UTF-16LE).
1030 * @path_num_chars: Number of 2-byte characters in @path.
1032 * @inode: WIM inode to save the stream into.
1034 * @lookup_table: Stream lookup table for the WIM.
1036 * @file_size: Size of unnamed data stream. (Used only if alternate
1037 * data streams API appears to be unavailable.)
1039 * @vol_flags: Flags that specify features of the volume being
1042 * Returns 0 on success; nonzero on failure.
1045 win32_capture_streams(const wchar_t *path,
1046 size_t path_num_chars,
1047 struct wim_inode *inode,
1048 struct wim_lookup_table *lookup_table,
1052 WIN32_FIND_STREAM_DATA dat;
1057 DEBUG("Capturing streams from \"%ls\"", path);
1059 if (win32func_FindFirstStreamW == NULL ||
1060 !(vol_flags & FILE_NAMED_STREAMS))
1063 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1064 if (hFind == INVALID_HANDLE_VALUE) {
1065 err = GetLastError();
1066 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1069 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1070 * points and directories */
1071 if ((inode->i_attributes &
1072 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1073 && err == ERROR_HANDLE_EOF)
1075 DEBUG("ERROR_HANDLE_EOF (ok)");
1078 if (err == ERROR_ACCESS_DENIED) {
1079 ERROR("Failed to look up data streams "
1080 "of \"%ls\": Access denied!\n%ls",
1081 path, capture_access_denied_msg);
1082 return WIMLIB_ERR_READ;
1084 ERROR("Failed to look up data streams "
1085 "of \"%ls\"", path);
1087 return WIMLIB_ERR_READ;
1092 ret = win32_capture_stream(path,
1094 inode, lookup_table,
1097 goto out_find_close;
1098 } while (win32func_FindNextStreamW(hFind, &dat));
1099 err = GetLastError();
1100 if (err != ERROR_HANDLE_EOF) {
1101 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
1103 ret = WIMLIB_ERR_READ;
1109 /* FindFirstStreamW() API is not available, or the volume does not
1110 * support named streams. Only capture the unnamed data stream. */
1111 DEBUG("Only capturing unnamed data stream");
1112 if (inode->i_attributes &
1113 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1117 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
1118 * stream to reduce the code to a call to the
1119 * already-implemented win32_capture_stream() */
1120 wcscpy(dat.cStreamName, L"::$DATA");
1121 dat.StreamSize.QuadPart = file_size;
1122 ret = win32_capture_stream(path,
1124 inode, lookup_table,
1131 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1133 size_t path_num_chars,
1134 struct add_image_params *params,
1135 struct win32_capture_state *state,
1138 struct wim_dentry *root = NULL;
1139 struct wim_inode *inode;
1144 size_t reparse_data_len;
1147 if (exclude_path(path, path_num_chars, params->config, true)) {
1148 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
1149 ERROR("Cannot exclude the root directory from capture");
1150 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1153 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
1154 && params->progress_func)
1156 union wimlib_progress_info info;
1157 info.scan.cur_path = path;
1158 info.scan.excluded = true;
1159 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1165 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
1166 && params->progress_func)
1168 union wimlib_progress_info info;
1169 info.scan.cur_path = path;
1170 info.scan.excluded = false;
1171 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1174 HANDLE hFile = win32_open_existing_file(path,
1175 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1176 if (hFile == INVALID_HANDLE_VALUE) {
1177 err = GetLastError();
1178 ERROR("Win32 API: Failed to open \"%ls\"", path);
1180 ret = WIMLIB_ERR_OPEN;
1184 BY_HANDLE_FILE_INFORMATION file_info;
1185 if (!GetFileInformationByHandle(hFile, &file_info)) {
1186 err = GetLastError();
1187 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1190 ret = WIMLIB_ERR_STAT;
1191 goto out_close_handle;
1194 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1195 reparse_data = alloca(REPARSE_POINT_MAX_SIZE);
1196 ret = win32_get_reparse_data(hFile, path, params,
1197 reparse_data, &reparse_data_len);
1199 /* WIMLIB_ERR_* (inverted) */
1201 goto out_close_handle;
1202 } else if (ret & RP_FIXED) {
1204 } else if (ret == RP_EXCLUDED) {
1206 goto out_close_handle;
1212 /* Create a WIM dentry with an associated inode, which may be shared.
1214 * However, we need to explicitly check for directories and files with
1215 * only 1 link and refuse to hard link them. This is because Windows
1216 * has a bug where it can return duplicate File IDs for files and
1217 * directories on the FAT filesystem. */
1218 ret = inode_table_new_dentry(params->inode_table,
1219 path_basename_with_len(path, path_num_chars),
1220 ((u64)file_info.nFileIndexHigh << 32) |
1221 (u64)file_info.nFileIndexLow,
1222 file_info.dwVolumeSerialNumber,
1223 (file_info.nNumberOfLinks <= 1 ||
1224 (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1227 goto out_close_handle;
1229 ret = win32_get_short_name(root, path);
1231 goto out_close_handle;
1233 inode = root->d_inode;
1235 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1236 goto out_close_handle;
1238 inode->i_attributes = file_info.dwFileAttributes;
1239 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1240 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1241 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1242 inode->i_resolved = 1;
1244 params->add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
1246 if (!(params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)
1247 && (vol_flags & FILE_PERSISTENT_ACLS))
1249 ret = win32_get_security_descriptor(root, params->sd_set,
1251 params->add_image_flags);
1253 goto out_close_handle;
1256 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1257 (u64)file_info.nFileSizeLow;
1261 /* Capture the unnamed data stream (only should be present for regular
1262 * files) and any alternate data streams. */
1263 ret = win32_capture_streams(path,
1266 params->lookup_table,
1272 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1273 /* Reparse point: set the reparse data (which we read already)
1275 inode->i_not_rpfixed = not_rpfixed;
1276 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_data);
1277 ret = inode_set_unnamed_stream(inode, reparse_data + 8,
1278 reparse_data_len - 8,
1279 params->lookup_table);
1280 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1281 /* Directory (not a reparse point) --- recurse to children */
1282 ret = win32_recurse_directory(root,
1296 free_dentry_tree(root, params->lookup_table);
1301 win32_do_capture_warnings(const struct win32_capture_state *state,
1302 int add_image_flags)
1304 if (state->num_get_sacl_priv_notheld == 0 &&
1305 state->num_get_sd_access_denied == 0)
1309 WARNING("Built dentry tree successfully, but with the following problem(s):");
1310 if (state->num_get_sacl_priv_notheld != 0) {
1311 WARNING("Could not capture SACL (System Access Control List)\n"
1312 " on %lu files or directories.",
1313 state->num_get_sacl_priv_notheld);
1315 if (state->num_get_sd_access_denied != 0) {
1316 WARNING("Could not capture security descriptor at all\n"
1317 " on %lu files or directories.",
1318 state->num_get_sd_access_denied);
1321 "Try running the program as the Administrator to make sure all the\n"
1322 " desired metadata has been captured exactly. However, if you\n"
1323 " do not care about capturing security descriptors correctly, then\n"
1324 " nothing more needs to be done%ls\n",
1325 (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
1326 L", although you might consider\n"
1327 " passing the --no-acls flag to `wimlib-imagex capture' or\n"
1328 " `wimlib-imagex append' to explicitly capture no security\n"
1332 /* Win32 version of capturing a directory tree */
1334 win32_build_dentry_tree(struct wim_dentry **root_ret,
1335 const wchar_t *root_disk_path,
1336 struct add_image_params *params)
1341 struct win32_capture_state state;
1345 path_nchars = wcslen(root_disk_path);
1346 if (path_nchars > 32767)
1347 return WIMLIB_ERR_INVALID_PARAM;
1349 ret = win32_get_file_and_vol_ids(root_disk_path,
1350 ¶ms->capture_root_ino,
1351 ¶ms->capture_root_dev);
1355 win32_get_vol_flags(root_disk_path, &vol_flags);
1357 /* There is no check for overflow later when this buffer is being used!
1358 * But the max path length on NTFS is 32767 characters, and paths need
1359 * to be written specially to even go past 260 characters, so we should
1360 * be okay with 32770 characters. */
1361 path = MALLOC(32770 * sizeof(wchar_t));
1363 return WIMLIB_ERR_NOMEM;
1365 wmemcpy(path, root_disk_path, path_nchars + 1);
1367 memset(&state, 0, sizeof(state));
1368 ret = win32_build_dentry_tree_recursive(root_ret, path,
1369 path_nchars, params,
1373 win32_do_capture_warnings(&state, params->add_image_flags);
1377 /* Wrapper around the FSCTL_SET_REPARSE_POINT ioctl to set the reparse data on
1378 * an extracted reparse point. */
1380 win32_set_reparse_data(HANDLE h,
1382 const struct wim_lookup_table_entry *lte,
1383 const wchar_t *path)
1390 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
1394 len = wim_resource_size(lte);
1395 if (len > 16 * 1024 - 8) {
1396 WARNING("\"%ls\": reparse data too long!", path);
1400 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
1401 * leave 8 bytes of space for them at the beginning of the buffer, then
1402 * set them manually. */
1403 buf = alloca(len + 8);
1404 ret = read_full_resource_into_buf(lte, buf + 8, false);
1407 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
1408 *(u16*)(buf + 4) = cpu_to_le16(len);
1409 *(u16*)(buf + 6) = 0;
1411 /* Set the reparse data on the open file using the
1412 * FSCTL_SET_REPARSE_POINT ioctl.
1414 * There are contradictions in Microsoft's documentation for this:
1416 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1417 * lpOverlapped is ignored."
1419 * --- So setting lpOverlapped to NULL is okay since it's ignored.
1421 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1422 * operation returns no output data and lpOutBuffer is NULL,
1423 * DeviceIoControl makes use of lpBytesReturned. After such an
1424 * operation, the value of lpBytesReturned is meaningless."
1426 * --- So lpOverlapped not really ignored, as it affects another
1427 * parameter. This is the actual behavior: lpBytesReturned must be
1428 * specified, even though lpBytesReturned is documented as:
1430 * "Not used with this operation; set to NULL."
1432 DWORD bytesReturned;
1433 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
1435 &bytesReturned /* lpBytesReturned */,
1436 NULL /* lpOverlapped */))
1438 DWORD err = GetLastError();
1439 ERROR("Failed to set reparse data on \"%ls\"", path);
1441 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1442 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1443 else if (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1444 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT)
1445 return WIMLIB_ERR_LINK;
1447 return WIMLIB_ERR_WRITE;
1452 /* Wrapper around the FSCTL_SET_COMPRESSION ioctl to change the
1453 * FILE_ATTRIBUTE_COMPRESSED flag of a file or directory. */
1455 win32_set_compression_state(HANDLE hFile, USHORT format, const wchar_t *path)
1457 DWORD bytesReturned;
1458 if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1459 &format, sizeof(USHORT),
1461 &bytesReturned, NULL))
1463 /* Could be a warning only, but we only call this if the volume
1464 * supports compression. So I'm calling this an error. */
1465 DWORD err = GetLastError();
1466 ERROR("Failed to set compression flag on \"%ls\"", path);
1468 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1469 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1471 return WIMLIB_ERR_WRITE;
1476 /* Wrapper around FSCTL_SET_SPARSE ioctl to set a file as sparse. */
1478 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1480 DWORD bytesReturned;
1481 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1484 &bytesReturned, NULL))
1486 /* Could be a warning only, but we only call this if the volume
1487 * supports sparse files. So I'm calling this an error. */
1488 DWORD err = GetLastError();
1489 WARNING("Failed to set sparse flag on \"%ls\"", path);
1491 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1492 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1494 return WIMLIB_ERR_WRITE;
1500 * Sets the security descriptor on an extracted file.
1503 win32_set_security_data(const struct wim_inode *inode,
1505 const wchar_t *path,
1506 struct apply_args *args)
1508 PSECURITY_DESCRIPTOR descriptor;
1511 const struct wim_security_data *sd;
1513 SECURITY_INFORMATION securityInformation = 0;
1520 BOOL owner_defaulted;
1521 BOOL group_defaulted;
1523 BOOL dacl_defaulted;
1525 BOOL sacl_defaulted;
1527 sd = wim_const_security_data(args->w);
1528 descriptor = sd->descriptors[inode->i_security_id];
1530 GetSecurityDescriptorOwner(descriptor, &owner, &owner_defaulted);
1532 securityInformation |= OWNER_SECURITY_INFORMATION;
1534 GetSecurityDescriptorGroup(descriptor, &group, &group_defaulted);
1536 securityInformation |= GROUP_SECURITY_INFORMATION;
1538 GetSecurityDescriptorDacl(descriptor, &dacl_present,
1539 &dacl, &dacl_defaulted);
1541 securityInformation |= DACL_SECURITY_INFORMATION;
1543 GetSecurityDescriptorSacl(descriptor, &sacl_present,
1544 &sacl, &sacl_defaulted);
1546 securityInformation |= SACL_SECURITY_INFORMATION;
1549 if (securityInformation == 0)
1551 if (SetSecurityInfo(hFile, SE_FILE_OBJECT,
1552 securityInformation, owner, group, dacl, sacl))
1554 err = GetLastError();
1555 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1558 case ERROR_PRIVILEGE_NOT_HELD:
1559 if (securityInformation & SACL_SECURITY_INFORMATION) {
1560 n = args->num_set_sacl_priv_notheld++;
1561 securityInformation &= ~SACL_SECURITY_INFORMATION;
1563 if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1565 "We don't have enough privileges to set the full security\n"
1566 " descriptor on \"%ls\"!\n", path);
1567 if (args->num_set_sd_access_denied +
1568 args->num_set_sacl_priv_notheld == 1)
1570 WARNING("%ls", apply_access_denied_msg);
1572 WARNING("Re-trying with SACL omitted.\n", path);
1573 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1575 "Suppressing further 'privileges not held' error messages when setting\n"
1576 " security descriptors.");
1581 case ERROR_INVALID_OWNER:
1582 case ERROR_ACCESS_DENIED:
1583 n = args->num_set_sd_access_denied++;
1584 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1585 WARNING("Failed to set security descriptor on \"%ls\": "
1586 "Access denied!\n", path);
1587 if (args->num_set_sd_access_denied +
1588 args->num_set_sacl_priv_notheld == 1)
1590 WARNING("%ls", apply_access_denied_msg);
1592 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1594 "Suppressing further access denied error messages when setting\n"
1595 " security descriptors");
1600 ERROR("Failed to set security descriptor on \"%ls\"", path);
1602 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1603 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1605 return WIMLIB_ERR_WRITE;
1611 win32_extract_chunk(const void *buf, size_t len, void *arg)
1613 HANDLE hStream = arg;
1615 DWORD nbytes_written;
1616 wimlib_assert(len <= 0xffffffff);
1618 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1619 nbytes_written != len)
1621 DWORD err = GetLastError();
1622 ERROR("WriteFile(): write error");
1624 return WIMLIB_ERR_WRITE;
1630 do_win32_extract_stream(HANDLE hStream, const struct wim_lookup_table_entry *lte)
1632 return extract_wim_resource(lte, wim_resource_size(lte),
1633 win32_extract_chunk, hStream);
1636 struct win32_encrypted_extract_ctx {
1638 int wimlib_err_code;
1640 pthread_cond_t cond;
1641 pthread_mutex_t mutex;
1642 u8 buf[WIM_CHUNK_SIZE];
1647 win32_encrypted_import_cb(unsigned char *data, void *_ctx,
1648 unsigned long *len_p)
1650 struct win32_encrypted_extract_ctx *ctx = _ctx;
1651 unsigned long len = *len_p;
1653 pthread_mutex_lock(&ctx->mutex);
1655 size_t bytes_to_copy;
1657 DEBUG("Importing up to %lu more bytes of raw encrypted data", len);
1658 while (ctx->buf_filled == 0) {
1661 pthread_cond_wait(&ctx->cond, &ctx->mutex);
1663 bytes_to_copy = min(len, ctx->buf_filled);
1664 memcpy(data, ctx->buf, bytes_to_copy);
1665 len -= bytes_to_copy;
1666 data += bytes_to_copy;
1667 ctx->buf_filled -= bytes_to_copy;
1668 memmove(ctx->buf, ctx->buf + bytes_to_copy, ctx->buf_filled);
1669 pthread_cond_signal(&ctx->cond);
1673 pthread_mutex_unlock(&ctx->mutex);
1674 return ERROR_SUCCESS;
1677 /* Extract ("Import") an encrypted file in a different thread. */
1679 win32_encrypted_import_proc(void *arg)
1681 struct win32_encrypted_extract_ctx *ctx = arg;
1683 ret = WriteEncryptedFileRaw(win32_encrypted_import_cb, ctx,
1685 pthread_mutex_lock(&ctx->mutex);
1686 if (ret == ERROR_SUCCESS) {
1687 ctx->wimlib_err_code = 0;
1690 ctx->wimlib_err_code = WIMLIB_ERR_WRITE;
1693 pthread_cond_signal(&ctx->cond);
1694 pthread_mutex_unlock(&ctx->mutex);
1700 win32_extract_raw_encrypted_chunk(const void *buf, size_t len, void *arg)
1702 struct win32_encrypted_extract_ctx *ctx = arg;
1703 size_t bytes_to_copy;
1706 DEBUG("Extracting up to %zu more bytes of encrypted data", len);
1707 pthread_mutex_lock(&ctx->mutex);
1708 while (ctx->buf_filled == WIM_CHUNK_SIZE) {
1710 pthread_mutex_unlock(&ctx->mutex);
1711 return ctx->wimlib_err_code;
1713 pthread_cond_wait(&ctx->cond, &ctx->mutex);
1715 bytes_to_copy = min(len, WIM_CHUNK_SIZE - ctx->buf_filled);
1716 memcpy(&ctx->buf[ctx->buf_filled], buf, bytes_to_copy);
1717 len -= bytes_to_copy;
1718 buf += bytes_to_copy;
1719 ctx->buf_filled += bytes_to_copy;
1720 pthread_cond_signal(&ctx->cond);
1721 pthread_mutex_unlock(&ctx->mutex);
1726 /* Create an encrypted file and extract the raw encrypted data to it.
1728 * @path: Path to encrypted file to create.
1729 * @lte: WIM lookup_table entry for the raw encrypted data.
1731 * This is separate from do_win32_extract_stream() because the WIM is supposed
1732 * to contain the *raw* encrypted data, which needs to be extracted ("imported")
1733 * using the special APIs OpenEncryptedFileRawW(), WriteEncryptedFileRaw(), and
1734 * CloseEncryptedFileRaw().
1736 * Returns 0 on success; nonzero on failure.
1739 do_win32_extract_encrypted_stream(const wchar_t *path,
1740 const struct wim_lookup_table_entry *lte)
1742 struct win32_encrypted_extract_ctx ctx;
1744 pthread_t import_thread;
1748 DEBUG("Opening file \"%ls\" to extract raw encrypted data", path);
1750 ret = OpenEncryptedFileRawW(path, CREATE_FOR_IMPORT, &file_ctx);
1752 ERROR("Failed to open \"%ls\" to write raw encrypted data", path);
1754 return WIMLIB_ERR_OPEN;
1760 /* Hack alert: WriteEncryptedFileRaw() requires the callback function
1761 * to work with a buffer whose size we cannot control. This doesn't
1762 * play well with our read_resource_prefix() function, which itself uses
1763 * a callback function to extract WIM_CHUNK_SIZE chunks of data. We
1764 * work around this problem by calling WriteEncryptedFileRaw() in a
1765 * different thread and feeding it the data as needed. */
1766 ctx.file_ctx = file_ctx;
1769 ctx.wimlib_err_code = 0;
1770 if (pthread_mutex_init(&ctx.mutex, NULL)) {
1771 ERROR_WITH_ERRNO("Can't create mutex");
1772 ret = WIMLIB_ERR_NOMEM;
1775 if (pthread_cond_init(&ctx.cond, NULL)) {
1776 ERROR_WITH_ERRNO("Can't create condition variable");
1777 ret = WIMLIB_ERR_NOMEM;
1778 goto out_pthread_mutex_destroy;
1780 ret = pthread_create(&import_thread, NULL,
1781 win32_encrypted_import_proc, &ctx);
1784 ERROR_WITH_ERRNO("Failed to create thread");
1785 ret = WIMLIB_ERR_FORK;
1786 goto out_pthread_cond_destroy;
1789 ret = extract_wim_resource(lte, wim_resource_size(lte),
1790 win32_extract_raw_encrypted_chunk, &ctx);
1791 pthread_mutex_lock(&ctx.mutex);
1793 pthread_cond_signal(&ctx.cond);
1794 pthread_mutex_unlock(&ctx.mutex);
1795 ret2 = pthread_join(import_thread, NULL);
1798 ERROR_WITH_ERRNO("Failed to join encrypted import thread");
1800 ret = WIMLIB_ERR_WRITE;
1803 ret = ctx.wimlib_err_code;
1804 out_pthread_cond_destroy:
1805 pthread_cond_destroy(&ctx.cond);
1806 out_pthread_mutex_destroy:
1807 pthread_mutex_destroy(&ctx.mutex);
1809 CloseEncryptedFileRaw(file_ctx);
1811 ERROR("Failed to extract encrypted file \"%ls\"", path);
1816 path_is_root_of_drive(const wchar_t *path)
1821 if (*path != L'/' && *path != L'\\') {
1822 if (*(path + 1) == L':')
1827 while (*path == L'/' || *path == L'\\')
1829 return (*path == L'\0');
1833 win32_mask_attributes(DWORD i_attributes)
1835 return i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1836 FILE_ATTRIBUTE_COMPRESSED |
1837 FILE_ATTRIBUTE_REPARSE_POINT |
1838 FILE_ATTRIBUTE_DIRECTORY |
1839 FILE_ATTRIBUTE_ENCRYPTED |
1840 FILE_FLAG_DELETE_ON_CLOSE |
1841 FILE_FLAG_NO_BUFFERING |
1842 FILE_FLAG_OPEN_NO_RECALL |
1843 FILE_FLAG_OVERLAPPED |
1844 FILE_FLAG_RANDOM_ACCESS |
1845 /*FILE_FLAG_SESSION_AWARE |*/
1846 FILE_FLAG_SEQUENTIAL_SCAN |
1847 FILE_FLAG_WRITE_THROUGH);
1851 win32_get_create_flags_and_attributes(DWORD i_attributes)
1854 * Some attributes cannot be set by passing them to CreateFile(). In
1857 * FILE_ATTRIBUTE_DIRECTORY:
1858 * CreateDirectory() must be called instead of CreateFile().
1860 * FILE_ATTRIBUTE_SPARSE_FILE:
1862 * See: win32_set_sparse().
1864 * FILE_ATTRIBUTE_COMPRESSED:
1865 * Not clear from the documentation, but apparently this needs an
1867 * See: win32_set_compressed().
1869 * FILE_ATTRIBUTE_REPARSE_POINT:
1870 * Needs an ioctl, with the reparse data specified.
1871 * See: win32_set_reparse_data().
1873 * In addition, clear any file flags in the attributes that we don't
1874 * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1875 * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1877 return win32_mask_attributes(i_attributes) |
1878 FILE_FLAG_OPEN_REPARSE_POINT |
1879 FILE_FLAG_BACKUP_SEMANTICS;
1882 /* Set compression and/or sparse attributes on a stream, if supported by the
1885 win32_set_special_stream_attributes(HANDLE hFile, const struct wim_inode *inode,
1886 struct wim_lookup_table_entry *unnamed_stream_lte,
1887 const wchar_t *path, unsigned vol_flags)
1891 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1892 if (vol_flags & FILE_FILE_COMPRESSION) {
1893 ret = win32_set_compression_state(hFile,
1894 COMPRESSION_FORMAT_DEFAULT,
1899 DEBUG("Cannot set compression attribute on \"%ls\": "
1900 "volume does not support transparent compression",
1905 if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1906 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1907 DEBUG("Setting sparse flag on \"%ls\"", path);
1908 ret = win32_set_sparse(hFile, path);
1912 DEBUG("Cannot set sparse attribute on \"%ls\": "
1913 "volume does not support sparse files",
1920 /* Pre-create directories; extract encrypted streams */
1922 win32_begin_extract_unnamed_stream(const struct wim_inode *inode,
1923 const struct wim_lookup_table_entry *lte,
1924 const wchar_t *path,
1925 DWORD *creationDisposition_ret,
1926 unsigned int vol_flags)
1931 /* Directories must be created with CreateDirectoryW(). Then the call
1932 * to CreateFileW() will merely open the directory that was already
1933 * created rather than creating a new file. */
1934 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1935 if (!CreateDirectoryW(path, NULL)) {
1936 err = GetLastError();
1938 case ERROR_ALREADY_EXISTS:
1940 case ERROR_ACCESS_DENIED:
1941 if (path_is_root_of_drive(path))
1945 ERROR("Failed to create directory \"%ls\"",
1948 return WIMLIB_ERR_MKDIR;
1951 DEBUG("Created directory \"%ls\"", path);
1952 *creationDisposition_ret = OPEN_EXISTING;
1954 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED &&
1955 vol_flags & FILE_SUPPORTS_ENCRYPTION)
1957 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1958 if (!EncryptFile(path)) {
1959 err = GetLastError();
1960 ERROR("Failed to encrypt directory \"%ls\"",
1963 return WIMLIB_ERR_WRITE;
1966 ret = do_win32_extract_encrypted_stream(path, lte);
1969 DEBUG("Extracted encrypted file \"%ls\"", path);
1971 *creationDisposition_ret = OPEN_EXISTING;
1974 /* Set file attributes if we created the file. Otherwise, we haven't
1975 * created the file set and we will set the attributes in the call to
1978 * The FAT filesystem does not let you change the attributes of the root
1979 * directory, so treat that as a special case and do not set attributes.
1981 if (*creationDisposition_ret == OPEN_EXISTING &&
1982 !path_is_root_of_drive(path))
1984 if (!SetFileAttributesW(path,
1985 win32_mask_attributes(inode->i_attributes)))
1987 err = GetLastError();
1988 ERROR("Failed to set attributes on \"%ls\"", path);
1990 return WIMLIB_ERR_WRITE;
1996 /* Set security descriptor and extract stream data or reparse data (skip the
1997 * unnamed data stream of encrypted files, which was already extracted). */
1999 win32_finish_extract_stream(HANDLE h, const struct wim_inode *inode,
2000 const struct wim_lookup_table_entry *lte,
2001 const wchar_t *stream_path,
2002 const wchar_t *stream_name_utf16,
2003 struct apply_args *args)
2006 if (stream_name_utf16 == NULL) {
2007 /* Unnamed stream. */
2009 /* Set security descriptor, unless the extract_flags indicate
2010 * not to or the volume does not supported it. Note that this
2011 * is only done when the unnamed stream is being extracted, as
2012 * security descriptors are per-file and not per-stream. */
2013 if (inode->i_security_id >= 0 &&
2014 !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
2015 && (args->vol_flags & FILE_PERSISTENT_ACLS))
2017 ret = win32_set_security_data(inode, h, stream_path, args);
2022 /* Handle reparse points. The data for them needs to be set
2023 * using a special ioctl. Note that the reparse point may have
2024 * been created using CreateFileW() in the case of
2025 * non-directories or CreateDirectoryW() in the case of
2026 * directories; but the ioctl works either way. Also, it is
2027 * only this step that actually sets the
2028 * FILE_ATTRIBUTE_REPARSE_POINT, as it is not valid to set it
2029 * using SetFileAttributesW() or CreateFileW().
2031 * If the volume does not support reparse points we simply
2032 * ignore the reparse data. (N.B. the code currently doesn't
2033 * actually reach this case because reparse points are skipped
2034 * entirely on such volumes.) */
2035 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2036 if (args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
2037 DEBUG("Setting reparse data on \"%ls\"",
2039 ret = win32_set_reparse_data(h,
2040 inode->i_reparse_tag,
2045 DEBUG("Cannot set reparse data on \"%ls\": volume "
2046 "does not support reparse points", stream_path);
2048 } else if (lte != NULL &&
2049 !(args->vol_flags & FILE_SUPPORTS_ENCRYPTION &&
2050 inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2052 /* Extract the data of the unnamed stream, unless the
2053 * lookup table entry is NULL (indicating an empty
2054 * stream for which no data needs to be extracted), or
2055 * the stream is encrypted and therefore was already
2056 * extracted as a special case. */
2057 ret = do_win32_extract_stream(h, lte);
2060 /* Extract the data for a named data stream. */
2062 DEBUG("Extracting named data stream \"%ls\" (len = %"PRIu64")",
2063 stream_path, wim_resource_size(lte));
2064 ret = do_win32_extract_stream(h, lte);
2071 win32_decrypt_file(HANDLE open_handle, const wchar_t *path)
2074 /* We cannot call DecryptFileW() while there is an open handle to the
2075 * file. So close it first. */
2076 if (!CloseHandle(open_handle)) {
2077 err = GetLastError();
2078 ERROR("Failed to close handle for \"%ls\"", path);
2080 return WIMLIB_ERR_WRITE;
2082 if (!DecryptFileW(path, 0 /* reserved parameter; set to 0 */)) {
2083 err = GetLastError();
2084 ERROR("Failed to decrypt file \"%ls\"", path);
2086 return WIMLIB_ERR_WRITE;
2092 * Create and extract a stream to a file, or create a directory, using the
2095 * This handles reparse points, directories, alternate data streams, encrypted
2096 * files, compressed files, etc.
2098 * @inode: WIM inode containing the stream.
2100 * @path: Path to extract the file to.
2102 * @stream_name_utf16:
2103 * Name of the stream, or NULL if the stream is unnamed. This will
2104 * be called with a NULL stream_name_utf16 before any non-NULL
2105 * stream_name_utf16's.
2107 * @lte: WIM lookup table entry for the stream. May be NULL to indicate
2108 * a stream of length 0.
2110 * @args: Additional apply context, including flags indicating supported
2113 * Returns 0 on success; nonzero on failure.
2116 win32_extract_stream(const struct wim_inode *inode,
2117 const wchar_t *path,
2118 const wchar_t *stream_name_utf16,
2119 struct wim_lookup_table_entry *lte,
2120 struct apply_args *args)
2122 wchar_t *stream_path;
2126 DWORD creationDisposition = CREATE_ALWAYS;
2127 DWORD requestedAccess;
2128 BY_HANDLE_FILE_INFORMATION file_info;
2130 if (stream_name_utf16) {
2131 /* Named stream. Create a buffer that contains the UTF-16LE
2132 * string [./]path:stream_name_utf16. This is needed to
2133 * create and open the stream using CreateFileW(). I'm not
2134 * aware of any other APIs to do this. Note: the '$DATA' suffix
2135 * seems to be unneeded. Additional note: a "./" prefix needs
2136 * to be added when the path is not absolute to avoid ambiguity
2137 * with drive letters. */
2138 size_t stream_path_nchars;
2140 size_t stream_name_nchars;
2141 const wchar_t *prefix;
2143 path_nchars = wcslen(path);
2144 stream_name_nchars = wcslen(stream_name_utf16);
2145 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
2146 if (path[0] != cpu_to_le16(L'\0') &&
2147 path[0] != cpu_to_le16(L'/') &&
2148 path[0] != cpu_to_le16(L'\\') &&
2149 path[1] != cpu_to_le16(L':'))
2152 stream_path_nchars += 2;
2156 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
2157 swprintf(stream_path, L"%ls%ls:%ls",
2158 prefix, path, stream_name_utf16);
2160 /* Unnamed stream; its path is just the path to the file itself.
2162 stream_path = (wchar_t*)path;
2164 ret = win32_begin_extract_unnamed_stream(inode, lte, path,
2165 &creationDisposition,
2171 DEBUG("Opening \"%ls\"", stream_path);
2172 requestedAccess = GENERIC_READ | GENERIC_WRITE |
2173 ACCESS_SYSTEM_SECURITY;
2175 /* Open the stream to be extracted. Depending on what we have set
2176 * creationDisposition to, we may be creating this for the first time,
2177 * or we may be opening on existing stream we already created using
2178 * CreateDirectoryW() or OpenEncryptedFileRawW(). */
2179 h = CreateFileW(stream_path,
2183 creationDisposition,
2184 win32_get_create_flags_and_attributes(inode->i_attributes),
2186 if (h == INVALID_HANDLE_VALUE) {
2187 err = GetLastError();
2188 if (err == ERROR_PRIVILEGE_NOT_HELD &&
2189 (requestedAccess & ACCESS_SYSTEM_SECURITY))
2191 /* Try opening the file again without privilege to
2193 requestedAccess &= ~ACCESS_SYSTEM_SECURITY;
2194 goto try_open_again;
2196 ERROR("Failed to create \"%ls\"", stream_path);
2198 ret = WIMLIB_ERR_OPEN;
2202 /* Check the attributes of the file we just opened, and remove
2203 * encryption or compression if either was set by default but is not
2204 * supposed to be set based on the WIM inode attributes. */
2205 if (!GetFileInformationByHandle(h, &file_info)) {
2206 err = GetLastError();
2207 ERROR("Failed to get attributes of \"%ls\"", stream_path);
2209 ret = WIMLIB_ERR_STAT;
2210 goto fail_close_handle;
2213 /* Remove encryption? */
2214 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED &&
2215 !(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2217 /* File defaulted to encrypted due to being in an encrypted
2218 * directory, but is not actually supposed to be encrypted.
2220 * This is a workaround, because I'm not aware of any way to
2221 * directly (e.g. with CreateFileW()) create an unencrypted file
2222 * in a directory with FILE_ATTRIBUTE_ENCRYPTED set. */
2223 ret = win32_decrypt_file(h, stream_path);
2225 goto fail; /* win32_decrypt_file() closed the handle. */
2226 creationDisposition = OPEN_EXISTING;
2227 goto try_open_again;
2230 /* Remove compression? */
2231 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED &&
2232 !(inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED))
2234 /* Similar to the encrypted case, above, if the file defaulted
2235 * to compressed due to being in an compressed directory, but is
2236 * not actually supposed to be compressed, explicitly set the
2237 * compression format to COMPRESSION_FORMAT_NONE. */
2238 ret = win32_set_compression_state(h, COMPRESSION_FORMAT_NONE,
2241 goto fail_close_handle;
2244 /* Set compression and/or sparse attributes if needed */
2245 ret = win32_set_special_stream_attributes(h, inode, lte, path,
2249 goto fail_close_handle;
2251 /* At this point we have at least created the needed stream with the
2252 * appropriate attributes. We have yet to set the appropriate security
2253 * descriptor and actually extract the stream data (other than for
2254 * extracted files, which were already extracted).
2255 * win32_finish_extract_stream() handles these additional steps. */
2256 ret = win32_finish_extract_stream(h, inode, lte, stream_path,
2257 stream_name_utf16, args);
2259 goto fail_close_handle;
2261 /* Done extracting the stream. Close the handle and return. */
2262 DEBUG("Closing \"%ls\"", stream_path);
2263 if (!CloseHandle(h)) {
2264 err = GetLastError();
2265 ERROR("Failed to close \"%ls\"", stream_path);
2267 ret = WIMLIB_ERR_WRITE;
2275 ERROR("Error extracting \"%ls\"", stream_path);
2281 * Creates a file, directory, or reparse point and extracts all streams to it
2282 * (unnamed data stream and/or reparse point stream, plus any alternate data
2283 * streams). Handles sparse, compressed, and/or encrypted files.
2285 * @inode: WIM inode for this file or directory.
2286 * @path: UTF-16LE external path to extract the inode to.
2287 * @args: Additional extraction context.
2289 * Returns 0 on success; nonzero on failure.
2292 win32_extract_streams(const struct wim_inode *inode,
2293 const wchar_t *path, struct apply_args *args)
2295 struct wim_lookup_table_entry *unnamed_lte;
2298 /* First extract the unnamed stream. */
2300 unnamed_lte = inode_unnamed_lte_resolved(inode);
2301 ret = win32_extract_stream(inode, path, NULL, unnamed_lte, args);
2305 /* Extract any named streams, if supported by the volume. */
2307 if (!(args->vol_flags & FILE_NAMED_STREAMS))
2309 for (u16 i = 0; i < inode->i_num_ads; i++) {
2310 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
2312 /* Skip the unnamed stream if it's in the ADS entries (we
2313 * already extracted it...) */
2314 if (ads_entry->stream_name_nbytes == 0)
2317 /* Skip special UNIX data entries (see documentation for
2318 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
2319 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
2320 && !memcmp(ads_entry->stream_name,
2321 WIMLIB_UNIX_DATA_TAG_UTF16LE,
2322 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
2325 /* Extract the named stream */
2326 ret = win32_extract_stream(inode,
2328 ads_entry->stream_name,
2338 /* If not done already, load the supported feature flags for the volume onto
2339 * which the image is being extracted, and warn the user about any missing
2340 * features that could be important. */
2342 win32_check_vol_flags(const wchar_t *output_path, struct apply_args *args)
2344 if (args->have_vol_flags)
2347 win32_get_vol_flags(output_path, &args->vol_flags);
2348 args->have_vol_flags = true;
2349 /* Warn the user about data that may not be extracted. */
2350 if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
2351 WARNING("Volume does not support sparse files!\n"
2352 " Sparse files will be extracted as non-sparse.");
2353 if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2354 WARNING("Volume does not support reparse points!\n"
2355 " Reparse point data will not be extracted.");
2356 if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
2357 WARNING("Volume does not support named data streams!\n"
2358 " Named data streams will not be extracted.");
2360 if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
2361 WARNING("Volume does not support encryption!\n"
2362 " Encrypted files will be extracted as raw data.");
2364 if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
2365 WARNING("Volume does not support transparent compression!\n"
2366 " Compressed files will be extracted as non-compressed.");
2368 if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
2369 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
2370 ERROR("Strict ACLs requested, but the volume does not "
2372 return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
2374 WARNING("Volume does not support persistent ACLS!\n"
2375 " File permissions will not be extracted.");
2382 * Try extracting a hard link.
2384 * @output_path: Path to link to be extracted.
2386 * @inode: WIM inode that the link is to; inode->i_extracted_file
2387 * the path to a name of the file that has already been
2388 * extracted (we use this to create the hard link).
2390 * @args: Additional apply context, used here to keep track of
2391 * the number of times creating a hard link failed due to
2392 * ERROR_INVALID_FUNCTION. This error should indicate that hard
2393 * links are not supported by the volume, and we would like to
2394 * warn the user a few times, but not too many times.
2396 * Returns 0 if the hard link was successfully extracted. Returns
2397 * WIMLIB_ERR_LINK (> 0) if an error occurred, other than hard links possibly
2398 * being unsupported by the volume. Returns a negative value if creating the
2399 * hard link failed due to ERROR_INVALID_FUNCTION.
2402 win32_try_hard_link(const wchar_t *output_path, const struct wim_inode *inode,
2403 struct apply_args *args)
2407 /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
2408 * but it's only available on Windows 7 and later. So no use
2409 * even checking it, really. Instead, CreateHardLinkW() will
2410 * apparently return ERROR_INVALID_FUNCTION if the volume does
2411 * not support hard links. */
2412 DEBUG("Creating hard link \"%ls => %ls\"",
2413 output_path, inode->i_extracted_file);
2414 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
2417 err = GetLastError();
2418 if (err != ERROR_INVALID_FUNCTION) {
2419 ERROR("Can't create hard link \"%ls => %ls\"",
2420 output_path, inode->i_extracted_file);
2422 return WIMLIB_ERR_LINK;
2424 args->num_hard_links_failed++;
2425 if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
2426 WARNING("Can't create hard link \"%ls => %ls\":\n"
2427 " Volume does not support hard links!\n"
2428 " Falling back to extracting a copy of the file.",
2429 output_path, inode->i_extracted_file);
2430 } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
2431 WARNING("Suppressing further hard linking warnings...");
2437 /* Extract a file, directory, reparse point, or hard link to an
2438 * already-extracted file using the Win32 API */
2440 win32_do_apply_dentry(const wchar_t *output_path,
2441 size_t output_path_num_chars,
2442 struct wim_dentry *dentry,
2443 struct apply_args *args)
2446 struct wim_inode *inode = dentry->d_inode;
2448 ret = win32_check_vol_flags(output_path, args);
2451 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
2452 /* Linked file, with another name already extracted. Create a
2454 ret = win32_try_hard_link(output_path, inode, args);
2457 /* Negative return value from win32_try_hard_link() indicates
2458 * that hard links are probably not supported by the volume.
2459 * Fall back to extracting a copy of the file. */
2462 /* If this is a reparse point and the volume does not support reparse
2463 * points, just skip it completely. */
2464 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2465 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2467 WARNING("Skipping extraction of reparse point \"%ls\":\n"
2468 " Not supported by destination filesystem",
2471 /* Create the file, directory, or reparse point, and extract the
2473 ret = win32_extract_streams(inode, output_path, args);
2477 if (inode->i_extracted_file == NULL) {
2478 const struct wim_lookup_table_entry *lte;
2480 /* Tally bytes extracted, including all alternate data streams,
2481 * unless we extracted a hard link (or, at least extracted a
2482 * name that was supposed to be a hard link) */
2483 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
2484 lte = inode_stream_lte_resolved(inode, i);
2486 args->progress.extract.completed_bytes +=
2487 wim_resource_size(lte);
2489 if (inode->i_nlink > 1) {
2490 /* Save extracted path for a later call to
2491 * CreateHardLinkW() if this inode has multiple links.
2493 inode->i_extracted_file = WSTRDUP(output_path);
2494 if (!inode->i_extracted_file)
2495 return WIMLIB_ERR_NOMEM;
2501 /* Set timestamps on an extracted file using the Win32 API */
2503 win32_do_apply_dentry_timestamps(const wchar_t *path,
2504 size_t path_num_chars,
2505 const struct wim_dentry *dentry,
2506 const struct apply_args *args)
2510 const struct wim_inode *inode = dentry->d_inode;
2512 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2513 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2515 /* Skip reparse points not extracted */
2519 /* Windows doesn't let you change the timestamps of the root directory
2520 * (at least on FAT, which is dumb but expected since FAT doesn't store
2521 * any metadata about the root directory...) */
2522 if (path_is_root_of_drive(path))
2525 DEBUG("Opening \"%ls\" to set timestamps", path);
2526 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
2527 if (h == INVALID_HANDLE_VALUE) {
2528 err = GetLastError();
2532 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
2533 .dwHighDateTime = inode->i_creation_time >> 32};
2534 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
2535 .dwHighDateTime = inode->i_last_access_time >> 32};
2536 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
2537 .dwHighDateTime = inode->i_last_write_time >> 32};
2539 DEBUG("Calling SetFileTime() on \"%ls\"", path);
2540 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
2541 err = GetLastError();
2545 DEBUG("Closing \"%ls\"", path);
2546 if (!CloseHandle(h)) {
2547 err = GetLastError();
2552 /* Only warn if setting timestamps failed; still return 0. */
2553 WARNING("Can't set timestamps on \"%ls\"", path);
2559 /* Replacement for POSIX fsync() */
2566 h = (HANDLE)_get_osfhandle(fd);
2567 if (h == INVALID_HANDLE_VALUE) {
2568 err = GetLastError();
2569 ERROR("Could not get Windows handle for file descriptor");
2574 if (!FlushFileBuffers(h)) {
2575 err = GetLastError();
2576 ERROR("Could not flush file buffers to disk");
2584 /* Use the Win32 API to get the number of processors */
2586 win32_get_number_of_processors()
2588 SYSTEM_INFO sysinfo;
2589 GetSystemInfo(&sysinfo);
2590 return sysinfo.dwNumberOfProcessors;
2593 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
2594 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
2595 * really does the right thing under all circumstances. */
2597 realpath(const wchar_t *path, wchar_t *resolved_path)
2600 wimlib_assert(resolved_path == NULL);
2603 ret = GetFullPathNameW(path, 0, NULL, NULL);
2605 err = GetLastError();
2609 resolved_path = TMALLOC(ret);
2612 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2614 err = GetLastError();
2615 free(resolved_path);
2616 resolved_path = NULL;
2624 return resolved_path;
2627 /* rename() on Windows fails if the destination file exists. And we need to
2628 * make it work on wide characters. Fix it. */
2630 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2632 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2635 /* As usual, the possible error values are not documented */
2636 DWORD err = GetLastError();
2637 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2645 /* Replacement for POSIX fnmatch() (partial functionality only) */
2647 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2649 if (PathMatchSpecW(string, pattern))
2655 /* truncate() replacement */
2657 win32_truncate_replacement(const wchar_t *path, off_t size)
2659 DWORD err = NO_ERROR;
2660 LARGE_INTEGER liOffset;
2662 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2663 if (h == INVALID_HANDLE_VALUE)
2666 liOffset.QuadPart = size;
2667 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2668 goto fail_close_handle;
2670 if (!SetEndOfFile(h))
2671 goto fail_close_handle;
2676 err = GetLastError();
2679 if (err == NO_ERROR)
2680 err = GetLastError();
2681 ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2688 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2689 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2690 * linked in by Visual Studio...?). */
2692 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2694 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2696 pthread_mutex_lock(&strerror_lock);
2697 mbstowcs(buf, strerror(errnum), buflen);
2698 buf[buflen - 1] = '\0';
2699 pthread_mutex_unlock(&strerror_lock);
2703 #endif /* __WIN32__ */