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);
1378 win32_set_reparse_data(HANDLE h,
1380 const struct wim_lookup_table_entry *lte,
1381 const wchar_t *path)
1388 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
1392 len = wim_resource_size(lte);
1393 if (len > 16 * 1024 - 8) {
1394 WARNING("\"%ls\": reparse data too long!", path);
1398 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
1399 * leave 8 bytes of space for them at the beginning of the buffer, then
1400 * set them manually. */
1401 buf = alloca(len + 8);
1402 ret = read_full_resource_into_buf(lte, buf + 8, false);
1405 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
1406 *(u16*)(buf + 4) = cpu_to_le16(len);
1407 *(u16*)(buf + 6) = 0;
1409 /* Set the reparse data on the open file using the
1410 * FSCTL_SET_REPARSE_POINT ioctl.
1412 * There are contradictions in Microsoft's documentation for this:
1414 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1415 * lpOverlapped is ignored."
1417 * --- So setting lpOverlapped to NULL is okay since it's ignored.
1419 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1420 * operation returns no output data and lpOutBuffer is NULL,
1421 * DeviceIoControl makes use of lpBytesReturned. After such an
1422 * operation, the value of lpBytesReturned is meaningless."
1424 * --- So lpOverlapped not really ignored, as it affects another
1425 * parameter. This is the actual behavior: lpBytesReturned must be
1426 * specified, even though lpBytesReturned is documented as:
1428 * "Not used with this operation; set to NULL."
1430 DWORD bytesReturned;
1431 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
1433 &bytesReturned /* lpBytesReturned */,
1434 NULL /* lpOverlapped */))
1436 DWORD err = GetLastError();
1437 ERROR("Failed to set reparse data on \"%ls\"", path);
1439 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1440 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1441 else if (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1442 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT)
1443 return WIMLIB_ERR_LINK;
1445 return WIMLIB_ERR_WRITE;
1451 win32_set_compression_state(HANDLE hFile, USHORT format, const wchar_t *path)
1453 DWORD bytesReturned = 0;
1454 if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1455 &format, sizeof(USHORT),
1457 &bytesReturned, NULL))
1459 /* Could be a warning only, but we only call this if the volume
1460 * supports compression. So I'm calling this an error. */
1461 DWORD err = GetLastError();
1462 ERROR("Failed to set compression flag on \"%ls\"", path);
1464 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1465 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1467 return WIMLIB_ERR_WRITE;
1473 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1475 DWORD bytesReturned = 0;
1476 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1479 &bytesReturned, NULL))
1481 /* Could be a warning only, but we only call this if the volume
1482 * supports sparse files. So I'm calling this an error. */
1483 DWORD err = GetLastError();
1484 WARNING("Failed to set sparse flag on \"%ls\"", path);
1486 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1487 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1489 return WIMLIB_ERR_WRITE;
1495 * Sets the security descriptor on an extracted file.
1498 win32_set_security_data(const struct wim_inode *inode,
1500 const wchar_t *path,
1501 struct apply_args *args)
1503 PSECURITY_DESCRIPTOR descriptor;
1506 const struct wim_security_data *sd;
1508 SECURITY_INFORMATION securityInformation = 0;
1515 BOOL owner_defaulted;
1516 BOOL group_defaulted;
1518 BOOL dacl_defaulted;
1520 BOOL sacl_defaulted;
1522 sd = wim_const_security_data(args->w);
1523 descriptor = sd->descriptors[inode->i_security_id];
1525 GetSecurityDescriptorOwner(descriptor, &owner, &owner_defaulted);
1527 securityInformation |= OWNER_SECURITY_INFORMATION;
1529 GetSecurityDescriptorGroup(descriptor, &group, &group_defaulted);
1531 securityInformation |= GROUP_SECURITY_INFORMATION;
1533 GetSecurityDescriptorDacl(descriptor, &dacl_present,
1534 &dacl, &dacl_defaulted);
1536 securityInformation |= DACL_SECURITY_INFORMATION;
1538 GetSecurityDescriptorSacl(descriptor, &sacl_present,
1539 &sacl, &sacl_defaulted);
1541 securityInformation |= SACL_SECURITY_INFORMATION;
1544 if (securityInformation == 0)
1546 if (SetSecurityInfo(hFile, SE_FILE_OBJECT,
1547 securityInformation, owner, group, dacl, sacl))
1549 err = GetLastError();
1550 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1553 case ERROR_PRIVILEGE_NOT_HELD:
1554 if (securityInformation & SACL_SECURITY_INFORMATION) {
1555 n = args->num_set_sacl_priv_notheld++;
1556 securityInformation &= ~SACL_SECURITY_INFORMATION;
1558 if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1560 "We don't have enough privileges to set the full security\n"
1561 " descriptor on \"%ls\"!\n", path);
1562 if (args->num_set_sd_access_denied +
1563 args->num_set_sacl_priv_notheld == 1)
1565 WARNING("%ls", apply_access_denied_msg);
1567 WARNING("Re-trying with SACL omitted.\n", path);
1568 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1570 "Suppressing further 'privileges not held' error messages when setting\n"
1571 " security descriptors.");
1576 case ERROR_INVALID_OWNER:
1577 case ERROR_ACCESS_DENIED:
1578 n = args->num_set_sd_access_denied++;
1579 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1580 WARNING("Failed to set security descriptor on \"%ls\": "
1581 "Access denied!\n", path);
1582 if (args->num_set_sd_access_denied +
1583 args->num_set_sacl_priv_notheld == 1)
1585 WARNING("%ls", apply_access_denied_msg);
1587 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1589 "Suppressing further access denied error messages when setting\n"
1590 " security descriptors");
1595 ERROR("Failed to set security descriptor on \"%ls\"", path);
1597 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1598 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1600 return WIMLIB_ERR_WRITE;
1606 win32_extract_chunk(const void *buf, size_t len, void *arg)
1608 HANDLE hStream = arg;
1610 DWORD nbytes_written;
1611 wimlib_assert(len <= 0xffffffff);
1613 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1614 nbytes_written != len)
1616 DWORD err = GetLastError();
1617 ERROR("WriteFile(): write error");
1619 return WIMLIB_ERR_WRITE;
1625 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1627 return extract_wim_resource(lte, wim_resource_size(lte),
1628 win32_extract_chunk, hStream);
1632 do_win32_extract_encrypted_stream(const wchar_t *path,
1633 const struct wim_lookup_table_entry *lte)
1635 ERROR("Extracting encryted streams not implemented");
1636 return WIMLIB_ERR_INVALID_PARAM;
1640 path_is_root_of_drive(const wchar_t *path)
1645 if (*path != L'/' && *path != L'\\') {
1646 if (*(path + 1) == L':')
1651 while (*path == L'/' || *path == L'\\')
1653 return (*path == L'\0');
1657 win32_get_create_flags_and_attributes(DWORD i_attributes)
1662 * Some attributes cannot be set by passing them to CreateFile(). In
1665 * FILE_ATTRIBUTE_DIRECTORY:
1666 * CreateDirectory() must be called instead of CreateFile().
1668 * FILE_ATTRIBUTE_SPARSE_FILE:
1670 * See: win32_set_sparse().
1672 * FILE_ATTRIBUTE_COMPRESSED:
1673 * Not clear from the documentation, but apparently this needs an
1675 * See: win32_set_compressed().
1677 * FILE_ATTRIBUTE_REPARSE_POINT:
1678 * Needs an ioctl, with the reparse data specified.
1679 * See: win32_set_reparse_data().
1681 * In addition, clear any file flags in the attributes that we don't
1682 * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1683 * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1685 attributes = i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1686 FILE_ATTRIBUTE_COMPRESSED |
1687 FILE_ATTRIBUTE_REPARSE_POINT |
1688 FILE_ATTRIBUTE_DIRECTORY |
1689 FILE_FLAG_DELETE_ON_CLOSE |
1690 FILE_FLAG_NO_BUFFERING |
1691 FILE_FLAG_OPEN_NO_RECALL |
1692 FILE_FLAG_OVERLAPPED |
1693 FILE_FLAG_RANDOM_ACCESS |
1694 /*FILE_FLAG_SESSION_AWARE |*/
1695 FILE_FLAG_SEQUENTIAL_SCAN |
1696 FILE_FLAG_WRITE_THROUGH);
1698 FILE_FLAG_OPEN_REPARSE_POINT |
1699 FILE_FLAG_BACKUP_SEMANTICS;
1702 /* Set compression or sparse attributes, and reparse data, if supported by the
1705 win32_set_special_attributes(HANDLE hFile, const struct wim_inode *inode,
1706 struct wim_lookup_table_entry *unnamed_stream_lte,
1707 const wchar_t *path, unsigned vol_flags)
1711 /* Encrypted files cannot be [de]compressed. */
1712 if (!(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1713 if (vol_flags & FILE_FILE_COMPRESSION) {
1715 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1716 format = COMPRESSION_FORMAT_DEFAULT;
1717 DEBUG("Setting compression flag on \"%ls\"", path);
1719 format = COMPRESSION_FORMAT_NONE;
1720 DEBUG("Clearing compression flag on \"%ls\"", path);
1722 ret = win32_set_compression_state(hFile, format, path);
1726 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1727 DEBUG("Cannot set compression attribute on \"%ls\": "
1728 "volume does not support transparent compression",
1734 if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1735 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1736 DEBUG("Setting sparse flag on \"%ls\"", path);
1737 ret = win32_set_sparse(hFile, path);
1741 DEBUG("Cannot set sparse attribute on \"%ls\": "
1742 "volume does not support sparse files",
1747 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1748 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
1749 DEBUG("Setting reparse data on \"%ls\"", path);
1750 ret = win32_set_reparse_data(hFile, inode->i_reparse_tag,
1751 unnamed_stream_lte, path);
1755 DEBUG("Cannot set reparse data on \"%ls\": volume "
1756 "does not support reparse points", path);
1763 win32_extract_stream(const struct wim_inode *inode,
1764 const wchar_t *path,
1765 const wchar_t *stream_name_utf16,
1766 struct wim_lookup_table_entry *lte,
1767 struct apply_args *args)
1769 wchar_t *stream_path;
1773 DWORD creationDisposition = CREATE_ALWAYS;
1774 DWORD requestedAccess;
1776 if (stream_name_utf16) {
1777 /* Named stream. Create a buffer that contains the UTF-16LE
1778 * string [./]path:stream_name_utf16. This is needed to
1779 * create and open the stream using CreateFileW(). I'm not
1780 * aware of any other APIs to do this. Note: the '$DATA' suffix
1781 * seems to be unneeded. Additional note: a "./" prefix needs
1782 * to be added when the path is not absolute to avoid ambiguity
1783 * with drive letters. */
1784 size_t stream_path_nchars;
1786 size_t stream_name_nchars;
1787 const wchar_t *prefix;
1789 path_nchars = wcslen(path);
1790 stream_name_nchars = wcslen(stream_name_utf16);
1791 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1792 if (path[0] != cpu_to_le16(L'\0') &&
1793 path[0] != cpu_to_le16(L'/') &&
1794 path[0] != cpu_to_le16(L'\\') &&
1795 path[1] != cpu_to_le16(L':'))
1798 stream_path_nchars += 2;
1802 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1803 swprintf(stream_path, L"%ls%ls:%ls",
1804 prefix, path, stream_name_utf16);
1806 /* Unnamed stream; its path is just the path to the file itself.
1808 stream_path = (wchar_t*)path;
1810 /* Directories must be created with CreateDirectoryW(). Then
1811 * the call to CreateFileW() will merely open the directory that
1812 * was already created rather than creating a new file. */
1813 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1814 if (!CreateDirectoryW(stream_path, NULL)) {
1815 err = GetLastError();
1817 case ERROR_ALREADY_EXISTS:
1819 case ERROR_ACCESS_DENIED:
1820 if (path_is_root_of_drive(path))
1824 ERROR("Failed to create directory \"%ls\"",
1827 ret = WIMLIB_ERR_MKDIR;
1831 DEBUG("Created directory \"%ls\"", stream_path);
1832 creationDisposition = OPEN_EXISTING;
1836 DEBUG("Opening \"%ls\"", stream_path);
1837 requestedAccess = GENERIC_READ | GENERIC_WRITE |
1838 ACCESS_SYSTEM_SECURITY;
1840 h = CreateFileW(stream_path,
1844 creationDisposition,
1845 win32_get_create_flags_and_attributes(inode->i_attributes),
1847 if (h == INVALID_HANDLE_VALUE) {
1848 err = GetLastError();
1849 if (err == ERROR_PRIVILEGE_NOT_HELD &&
1850 (requestedAccess & ACCESS_SYSTEM_SECURITY))
1852 requestedAccess &= ~ACCESS_SYSTEM_SECURITY;
1853 goto try_open_again;
1855 ERROR("Failed to create \"%ls\"", stream_path);
1857 ret = WIMLIB_ERR_OPEN;
1861 if (stream_name_utf16 == NULL) {
1862 if (inode->i_security_id >= 0 &&
1863 !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
1864 && (args->vol_flags & FILE_PERSISTENT_ACLS))
1866 ret = win32_set_security_data(inode, h, path, args);
1868 goto fail_close_handle;
1871 ret = win32_set_special_attributes(h, inode, lte, path,
1874 goto fail_close_handle;
1877 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1879 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1880 stream_path, wim_resource_size(lte));
1881 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED
1882 && stream_name_utf16 == NULL
1883 && (args->vol_flags & FILE_SUPPORTS_ENCRYPTION))
1885 ret = do_win32_extract_encrypted_stream(stream_path,
1888 ret = do_win32_extract_stream(h, lte);
1891 goto fail_close_handle;
1895 DEBUG("Closing \"%ls\"", stream_path);
1896 if (!CloseHandle(h)) {
1897 err = GetLastError();
1898 ERROR("Failed to close \"%ls\"", stream_path);
1900 ret = WIMLIB_ERR_WRITE;
1908 ERROR("Error extracting %ls", stream_path);
1914 * Creates a file, directory, or reparse point and extracts all streams to it
1915 * (unnamed data stream and/or reparse point stream, plus any alternate data
1918 * @inode: WIM inode for this file or directory.
1919 * @path: UTF-16LE external path to extract the inode to.
1920 * @args: Additional extraction context.
1922 * Returns 0 on success; nonzero on failure.
1925 win32_extract_streams(const struct wim_inode *inode,
1926 const wchar_t *path, struct apply_args *args)
1928 struct wim_lookup_table_entry *unnamed_lte;
1931 /* Extract the unnamed stream. */
1933 unnamed_lte = inode_unnamed_lte_resolved(inode);
1934 ret = win32_extract_stream(inode, path, NULL, unnamed_lte, args);
1937 if (unnamed_lte && inode->i_extracted_file == NULL)
1939 args->progress.extract.completed_bytes +=
1940 wim_resource_size(unnamed_lte);
1943 /* Extract any named streams, if supported by the volume. */
1945 if (!(args->vol_flags & FILE_NAMED_STREAMS))
1947 for (u16 i = 0; i < inode->i_num_ads; i++) {
1948 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1950 /* Skip the unnamed stream if it's in the ADS entries (we
1951 * already extracted it...) */
1952 if (ads_entry->stream_name_nbytes == 0)
1955 /* Skip special UNIX data entries (see documentation for
1956 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1957 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1958 && !memcmp(ads_entry->stream_name,
1959 WIMLIB_UNIX_DATA_TAG_UTF16LE,
1960 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1963 /* Extract the named stream */
1964 ret = win32_extract_stream(inode,
1966 ads_entry->stream_name,
1972 /* Tally the bytes extracted, unless this was supposed to be a
1973 * hard link and we are extracting the data again only as a
1975 if (ads_entry->lte && inode->i_extracted_file == NULL)
1977 args->progress.extract.completed_bytes +=
1978 wim_resource_size(ads_entry->lte);
1986 win32_check_vol_flags(const wchar_t *output_path, struct apply_args *args)
1988 if (args->have_vol_flags)
1991 win32_get_vol_flags(output_path, &args->vol_flags);
1992 args->have_vol_flags = true;
1993 /* Warn the user about data that may not be extracted. */
1994 if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
1995 WARNING("Volume does not support sparse files!\n"
1996 " Sparse files will be extracted as non-sparse.");
1997 if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1998 WARNING("Volume does not support reparse points!\n"
1999 " Reparse point data will not be extracted.");
2000 if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
2001 WARNING("Volume does not support named data streams!\n"
2002 " Named data streams will not be extracted.");
2004 if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
2005 WARNING("Volume does not support encryption!\n"
2006 " Encrypted files will be extracted as raw data.");
2008 if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
2009 WARNING("Volume does not support transparent compression!\n"
2010 " Compressed files will be extracted as non-compressed.");
2012 if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
2013 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
2014 ERROR("Strict ACLs requested, but the volume does not "
2016 return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
2018 WARNING("Volume does not support persistent ACLS!\n"
2019 " File permissions will not be extracted.");
2026 win32_try_hard_link(const wchar_t *output_path, const struct wim_inode *inode,
2027 struct apply_args *args)
2031 /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
2032 * but it's only available on Windows 7 and later. So no use
2033 * even checking it, really. Instead, CreateHardLinkW() will
2034 * apparently return ERROR_INVALID_FUNCTION if the volume does
2035 * not support hard links. */
2036 DEBUG("Creating hard link \"%ls => %ls\"",
2037 output_path, inode->i_extracted_file);
2038 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
2041 err = GetLastError();
2042 if (err != ERROR_INVALID_FUNCTION) {
2043 ERROR("Can't create hard link \"%ls => %ls\"",
2044 output_path, inode->i_extracted_file);
2046 return WIMLIB_ERR_LINK;
2048 args->num_hard_links_failed++;
2049 if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
2050 WARNING("Can't create hard link \"%ls => %ls\":\n"
2051 " Volume does not support hard links!\n"
2052 " Falling back to extracting a copy of the file.",
2053 output_path, inode->i_extracted_file);
2054 } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
2055 WARNING("Suppressing further hard linking warnings...");
2061 /* Extract a file, directory, reparse point, or hard link to an
2062 * already-extracted file using the Win32 API */
2064 win32_do_apply_dentry(const wchar_t *output_path,
2065 size_t output_path_num_chars,
2066 struct wim_dentry *dentry,
2067 struct apply_args *args)
2070 struct wim_inode *inode = dentry->d_inode;
2072 ret = win32_check_vol_flags(output_path, args);
2075 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
2076 /* Linked file, with another name already extracted. Create a
2078 ret = win32_try_hard_link(output_path, inode, args);
2081 /* Falling back to extracting copy of file */
2084 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2085 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2087 WARNING("Skipping extraction of reparse point \"%ls\":\n"
2088 " Not supported by destination filesystem",
2090 struct wim_lookup_table_entry *lte;
2091 lte = inode_unnamed_lte_resolved(inode);
2093 args->progress.extract.completed_bytes += wim_resource_size(lte);
2097 /* Create the file, directory, or reparse point, and extract the
2099 ret = win32_extract_streams(inode, output_path, args);
2103 if (inode->i_nlink > 1) {
2104 /* Save extracted path for a later call to
2105 * CreateHardLinkW() if this inode has multiple links.
2107 inode->i_extracted_file = WSTRDUP(output_path);
2108 if (!inode->i_extracted_file)
2109 ret = WIMLIB_ERR_NOMEM;
2114 /* Set timestamps on an extracted file using the Win32 API */
2116 win32_do_apply_dentry_timestamps(const wchar_t *path,
2117 size_t path_num_chars,
2118 const struct wim_dentry *dentry,
2119 const struct apply_args *args)
2123 const struct wim_inode *inode = dentry->d_inode;
2125 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2126 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2128 /* Skip reparse points not extracted */
2132 /* Windows doesn't let you change the timestamps of the root directory
2133 * (at least on FAT, which is dumb but expected since FAT doesn't store
2134 * any metadata about the root directory...) */
2135 if (path_is_root_of_drive(path))
2138 DEBUG("Opening \"%ls\" to set timestamps", path);
2139 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
2140 if (h == INVALID_HANDLE_VALUE) {
2141 err = GetLastError();
2145 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
2146 .dwHighDateTime = inode->i_creation_time >> 32};
2147 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
2148 .dwHighDateTime = inode->i_last_access_time >> 32};
2149 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
2150 .dwHighDateTime = inode->i_last_write_time >> 32};
2152 DEBUG("Calling SetFileTime() on \"%ls\"", path);
2153 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
2154 err = GetLastError();
2158 DEBUG("Closing \"%ls\"", path);
2159 if (!CloseHandle(h)) {
2160 err = GetLastError();
2165 /* Only warn if setting timestamps failed; still return 0. */
2166 WARNING("Can't set timestamps on \"%ls\"", path);
2172 /* Replacement for POSIX fsync() */
2179 h = (HANDLE)_get_osfhandle(fd);
2180 if (h == INVALID_HANDLE_VALUE) {
2181 err = GetLastError();
2182 ERROR("Could not get Windows handle for file descriptor");
2187 if (!FlushFileBuffers(h)) {
2188 err = GetLastError();
2189 ERROR("Could not flush file buffers to disk");
2197 /* Use the Win32 API to get the number of processors */
2199 win32_get_number_of_processors()
2201 SYSTEM_INFO sysinfo;
2202 GetSystemInfo(&sysinfo);
2203 return sysinfo.dwNumberOfProcessors;
2206 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
2207 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
2208 * really does the right thing under all circumstances. */
2210 realpath(const wchar_t *path, wchar_t *resolved_path)
2213 wimlib_assert(resolved_path == NULL);
2216 ret = GetFullPathNameW(path, 0, NULL, NULL);
2218 err = GetLastError();
2222 resolved_path = TMALLOC(ret);
2225 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2227 err = GetLastError();
2228 free(resolved_path);
2229 resolved_path = NULL;
2237 return resolved_path;
2240 /* rename() on Windows fails if the destination file exists. And we need to
2241 * make it work on wide characters. Fix it. */
2243 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2245 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2248 /* As usual, the possible error values are not documented */
2249 DWORD err = GetLastError();
2250 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2258 /* Replacement for POSIX fnmatch() (partial functionality only) */
2260 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2262 if (PathMatchSpecW(string, pattern))
2268 /* truncate() replacement */
2270 win32_truncate_replacement(const wchar_t *path, off_t size)
2272 DWORD err = NO_ERROR;
2273 LARGE_INTEGER liOffset;
2275 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2276 if (h == INVALID_HANDLE_VALUE)
2279 liOffset.QuadPart = size;
2280 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2281 goto fail_close_handle;
2283 if (!SetEndOfFile(h))
2284 goto fail_close_handle;
2289 err = GetLastError();
2292 if (err == NO_ERROR)
2293 err = GetLastError();
2294 ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2301 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2302 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2303 * linked in by Visual Studio...?). */
2305 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2307 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2309 pthread_mutex_lock(&strerror_lock);
2310 mbstowcs(buf, strerror(errnum), buflen);
2311 buf[buflen - 1] = '\0';
2312 pthread_mutex_unlock(&strerror_lock);
2316 #endif /* __WIN32__ */