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> /* shlwapi.h for PathMatchSpecW() */
33 #ifdef ERROR /* windows.h defines this */
39 #include "lookup_table.h"
41 #include "endianness.h"
42 #include "buffer_io.h"
47 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
48 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
49 #define MAX_CREATE_HARD_LINK_WARNINGS 5
50 struct win32_capture_state {
51 unsigned long num_get_sd_access_denied;
52 unsigned long num_get_sacl_priv_notheld;
55 #define MAX_SET_SD_ACCESS_DENIED_WARNINGS 1
56 #define MAX_SET_SACL_PRIV_NOTHELD_WARNINGS 1
58 #ifdef ENABLE_ERROR_MESSAGES
60 win32_error(u32 err_code)
64 nchars = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
65 FORMAT_MESSAGE_ALLOCATE_BUFFER,
67 (wchar_t*)&buffer, 0, NULL);
69 ERROR("Error printing error message! "
70 "Computer will self-destruct in 3 seconds.");
72 ERROR("Win32 error: %ls", buffer);
76 #else /* ENABLE_ERROR_MESSAGES */
77 # define win32_error(err_code)
78 #endif /* !ENABLE_ERROR_MESSAGES */
80 /* Pointers to functions that are not available on all targetted versions of
81 * Windows (XP and later). NOTE: The WINAPI annotations seem to be important; I
82 * assume it specifies a certain calling convention. */
85 static HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
86 STREAM_INFO_LEVELS InfoLevel,
87 LPVOID lpFindStreamData,
88 DWORD dwFlags) = NULL;
91 static BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
92 LPVOID lpFindStreamData) = NULL;
94 static HMODULE hKernel32 = NULL;
96 /* Try to dynamically load some functions */
102 if (hKernel32 == NULL) {
103 DEBUG("Loading Kernel32.dll");
104 hKernel32 = LoadLibraryW(L"Kernel32.dll");
105 if (hKernel32 == NULL) {
106 err = GetLastError();
107 WARNING("Can't load Kernel32.dll");
113 DEBUG("Looking for FindFirstStreamW");
114 win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32, "FindFirstStreamW");
115 if (!win32func_FindFirstStreamW) {
116 WARNING("Could not find function FindFirstStreamW() in Kernel32.dll!");
117 WARNING("Capturing alternate data streams will not be supported.");
121 DEBUG("Looking for FindNextStreamW");
122 win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32, "FindNextStreamW");
123 if (!win32func_FindNextStreamW) {
124 WARNING("Could not find function FindNextStreamW() in Kernel32.dll!");
125 WARNING("Capturing alternate data streams will not be supported.");
126 win32func_FindFirstStreamW = NULL;
131 win32_global_cleanup()
133 if (hKernel32 != NULL) {
134 DEBUG("Closing Kernel32.dll");
135 FreeLibrary(hKernel32);
140 static const wchar_t *capture_access_denied_msg =
141 L" If you are not running this program as the administrator, you may\n"
142 " need to do so, so that all data and metadata can be backed up.\n"
143 " Otherwise, there may be no way to access the desired data or\n"
144 " metadata without taking ownership of the file or directory.\n"
147 static const wchar_t *apply_access_denied_msg =
148 L"If you are not running this program as the administrator, you may\n"
149 " need to do so, so that all data and metadata can be extracted\n"
150 " exactly as the origignal copy. However, if you do not care that\n"
151 " the security descriptors are extracted correctly, you could run\n"
152 " `wimlib-imagex apply' with the --no-acls flag instead.\n"
156 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
158 return CreateFileW(path,
161 NULL, /* lpSecurityAttributes */
163 FILE_FLAG_BACKUP_SEMANTICS |
164 FILE_FLAG_OPEN_REPARSE_POINT,
165 NULL /* hTemplateFile */);
169 win32_open_file_data_only(const wchar_t *path)
171 return win32_open_existing_file(path, FILE_READ_DATA);
175 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
177 consume_data_callback_t cb,
186 HANDLE hFile = win32_open_file_data_only(lte->file_on_disk);
187 if (hFile == INVALID_HANDLE_VALUE) {
188 err = GetLastError();
189 ERROR("Failed to open \"%ls\"", lte->file_on_disk);
191 return WIMLIB_ERR_OPEN;
195 out_buf = alloca(WIM_CHUNK_SIZE);
197 out_buf = ctx_or_buf;
199 bytes_remaining = size;
200 while (bytes_remaining) {
201 DWORD bytesToRead, bytesRead;
203 bytesToRead = min(WIM_CHUNK_SIZE, bytes_remaining);
204 if (!ReadFile(hFile, out_buf, bytesToRead, &bytesRead, NULL) ||
205 bytesRead != bytesToRead)
207 err = GetLastError();
208 ERROR("Failed to read data from \"%ls\"", lte->file_on_disk);
210 ret = WIMLIB_ERR_READ;
213 bytes_remaining -= bytesRead;
215 ret = (*cb)(out_buf, bytesRead, ctx_or_buf);
219 out_buf += bytesRead;
226 struct win32_encrypted_read_ctx {
227 consume_data_callback_t read_prefix_cb;
228 void *read_prefix_ctx_or_buf;
236 win32_encrypted_export_cb(unsigned char *_data, void *_ctx, unsigned long len)
238 const void *data = _data;
239 struct win32_encrypted_read_ctx *ctx = _ctx;
242 DEBUG("len = %lu", len);
243 if (ctx->read_prefix_cb) {
244 /* The length of the buffer passed to the ReadEncryptedFileRaw()
245 * export callback is undocumented, so we assume it may be of
247 size_t bytes_to_buffer = min(ctx->bytes_remaining - ctx->buf_filled,
249 while (bytes_to_buffer) {
250 size_t bytes_to_copy_to_buf =
251 min(bytes_to_buffer, WIM_CHUNK_SIZE - ctx->buf_filled);
253 memcpy(ctx->buf + ctx->buf_filled, data,
254 bytes_to_copy_to_buf);
255 ctx->buf_filled += bytes_to_copy_to_buf;
256 data += bytes_to_copy_to_buf;
257 bytes_to_buffer -= bytes_to_copy_to_buf;
259 if (ctx->buf_filled == WIM_CHUNK_SIZE ||
260 ctx->buf_filled == ctx->bytes_remaining)
262 ret = (*ctx->read_prefix_cb)(ctx->buf,
264 ctx->read_prefix_ctx_or_buf);
266 ctx->wimlib_err_code = ret;
267 /* Shouldn't matter what error code is returned
268 * here, as long as it isn't ERROR_SUCCESS. */
269 return ERROR_READ_FAULT;
271 ctx->bytes_remaining -= ctx->buf_filled;
276 size_t len_to_copy = min(len, ctx->bytes_remaining);
277 memcpy(ctx->read_prefix_ctx_or_buf, data, len_to_copy);
278 ctx->bytes_remaining -= len_to_copy;
279 ctx->read_prefix_ctx_or_buf += len_to_copy;
281 return ERROR_SUCCESS;
285 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
287 consume_data_callback_t cb,
291 struct win32_encrypted_read_ctx export_ctx;
296 DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
297 size, lte->file_on_disk);
299 export_ctx.read_prefix_cb = cb;
300 export_ctx.read_prefix_ctx_or_buf = ctx_or_buf;
301 export_ctx.wimlib_err_code = 0;
303 export_ctx.buf = MALLOC(WIM_CHUNK_SIZE);
305 return WIMLIB_ERR_NOMEM;
307 export_ctx.buf = NULL;
309 export_ctx.bytes_remaining = size;
311 err = OpenEncryptedFileRawW(lte->file_on_disk, 0, &file_ctx);
312 if (err != ERROR_SUCCESS) {
313 ERROR("Failed to open encrypted file \"%ls\" for raw read",
316 ret = WIMLIB_ERR_OPEN;
319 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
320 &export_ctx, file_ctx);
321 if (err != ERROR_SUCCESS) {
322 ERROR("Failed to read encrypted file \"%ls\"",
325 ret = export_ctx.wimlib_err_code;
327 ret = WIMLIB_ERR_READ;
328 } else if (export_ctx.bytes_remaining != 0) {
329 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
330 "encryted file \"%ls\"",
331 size - export_ctx.bytes_remaining, size,
333 ret = WIMLIB_ERR_READ;
337 CloseEncryptedFileRaw(file_ctx);
339 FREE(export_ctx.buf);
343 /* Given a path, which may not yet exist, get a set of flags that describe the
344 * features of the volume the path is on. */
346 win32_get_vol_flags(const wchar_t *path, unsigned *vol_flags_ret)
352 if (path[0] != L'\0' && path[0] != L'\\' &&
353 path[0] != L'/' && path[1] == L':')
355 /* Path starts with a drive letter; use it. */
356 volume = alloca(4 * sizeof(wchar_t));
362 /* Path does not start with a drive letter; use the volume of
363 * the current working directory. */
366 bret = GetVolumeInformationW(volume, /* lpRootPathName */
367 NULL, /* lpVolumeNameBuffer */
368 0, /* nVolumeNameSize */
369 NULL, /* lpVolumeSerialNumber */
370 NULL, /* lpMaximumComponentLength */
371 &vol_flags, /* lpFileSystemFlags */
372 NULL, /* lpFileSystemNameBuffer */
373 0); /* nFileSystemNameSize */
375 DWORD err = GetLastError();
376 WARNING("Failed to get volume information for path \"%ls\"", path);
378 vol_flags = 0xffffffff;
381 DEBUG("using vol_flags = %x", vol_flags);
382 *vol_flags_ret = vol_flags;
388 FILETIME_to_u64(const FILETIME *ft)
390 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
394 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
396 WIN32_FIND_DATAW dat;
400 /* If we can't read the short filename for some reason, we just ignore
401 * the error and assume the file has no short name. I don't think this
402 * should be an issue, since the short names are essentially obsolete
404 hFind = FindFirstFileW(path, &dat);
405 if (hFind != INVALID_HANDLE_VALUE) {
406 if (dat.cAlternateFileName[0] != L'\0') {
407 DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
408 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
410 size_t n = short_name_nbytes + sizeof(wchar_t);
411 dentry->short_name = MALLOC(n);
412 if (dentry->short_name) {
413 memcpy(dentry->short_name, dat.cAlternateFileName, n);
414 dentry->short_name_nbytes = short_name_nbytes;
416 ret = WIMLIB_ERR_NOMEM;
425 win32_get_security_descriptor(struct wim_dentry *dentry,
426 struct sd_set *sd_set,
428 struct win32_capture_state *state,
431 SECURITY_INFORMATION requestedInformation;
437 requestedInformation = DACL_SECURITY_INFORMATION |
438 SACL_SECURITY_INFORMATION |
439 OWNER_SECURITY_INFORMATION |
440 GROUP_SECURITY_INFORMATION;
442 /* Request length of security descriptor */
443 status = GetFileSecurityW(path, requestedInformation,
444 NULL, 0, &lenNeeded);
445 err = GetLastError();
446 if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
447 DWORD len = lenNeeded;
449 if (GetFileSecurityW(path, requestedInformation,
450 (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
452 int security_id = sd_set_add_sd(sd_set, buf, len);
454 return WIMLIB_ERR_NOMEM;
456 dentry->d_inode->i_security_id = security_id;
460 err = GetLastError();
464 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS)
468 case ERROR_PRIVILEGE_NOT_HELD:
469 if (requestedInformation & SACL_SECURITY_INFORMATION) {
470 n = state->num_get_sacl_priv_notheld++;
471 requestedInformation &= ~SACL_SECURITY_INFORMATION;
472 if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
474 "We don't have enough privileges to read the full security\n"
475 " descriptor of \"%ls\"!\n"
476 " Re-trying with SACL omitted.\n", path);
477 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
479 "Suppressing further privileges not held error messages when reading\n"
480 " security descriptors.");
485 case ERROR_ACCESS_DENIED:
486 n = state->num_get_sd_access_denied++;
487 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
488 WARNING("Failed to read security descriptor of \"%ls\": "
489 "Access denied!\n%ls", path, capture_access_denied_msg);
490 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
491 WARNING("Suppressing further access denied errors messages i"
492 "when reading security descriptors");
497 ERROR("Failed to read security descriptor of \"%ls\"", path);
499 return WIMLIB_ERR_READ;
504 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
506 size_t path_num_chars,
507 struct add_image_params *params,
508 struct win32_capture_state *state,
511 /* Reads the directory entries of directory using a Win32 API and recursively
512 * calls win32_build_dentry_tree() on them. */
514 win32_recurse_directory(struct wim_dentry *root,
516 size_t dir_path_num_chars,
517 struct add_image_params *params,
518 struct win32_capture_state *state,
521 WIN32_FIND_DATAW dat;
526 DEBUG("Recurse to directory \"%ls\"", dir_path);
528 /* Begin reading the directory by calling FindFirstFileW. Unlike UNIX
529 * opendir(), FindFirstFileW has file globbing built into it. But this
530 * isn't what we actually want, so just add a dummy glob to get all
532 dir_path[dir_path_num_chars] = L'/';
533 dir_path[dir_path_num_chars + 1] = L'*';
534 dir_path[dir_path_num_chars + 2] = L'\0';
535 hFind = FindFirstFileW(dir_path, &dat);
536 dir_path[dir_path_num_chars] = L'\0';
538 if (hFind == INVALID_HANDLE_VALUE) {
539 err = GetLastError();
540 if (err == ERROR_FILE_NOT_FOUND) {
543 ERROR("Failed to read directory \"%ls\"", dir_path);
545 return WIMLIB_ERR_READ;
550 /* Skip . and .. entries */
551 if (dat.cFileName[0] == L'.' &&
552 (dat.cFileName[1] == L'\0' ||
553 (dat.cFileName[1] == L'.' &&
554 dat.cFileName[2] == L'\0')))
556 size_t filename_len = wcslen(dat.cFileName);
558 dir_path[dir_path_num_chars] = L'/';
559 wmemcpy(dir_path + dir_path_num_chars + 1,
563 struct wim_dentry *child;
564 size_t path_len = dir_path_num_chars + 1 + filename_len;
565 ret = win32_build_dentry_tree_recursive(&child,
571 dir_path[dir_path_num_chars] = L'\0';
575 dentry_add_child(root, child);
576 } while (FindNextFileW(hFind, &dat));
577 err = GetLastError();
578 if (err != ERROR_NO_MORE_FILES) {
579 ERROR("Failed to read directory \"%ls\"", dir_path);
582 ret = WIMLIB_ERR_READ;
590 win32_get_file_and_vol_ids(const wchar_t *path, u64 *ino_ret, u64 *dev_ret)
594 BY_HANDLE_FILE_INFORMATION file_info;
597 hFile = win32_open_existing_file(path, FILE_READ_ATTRIBUTES);
598 if (hFile == INVALID_HANDLE_VALUE) {
599 err = GetLastError();
600 WARNING("Failed to open \"%ls\" to get file and volume IDs",
603 return WIMLIB_ERR_OPEN;
606 if (!GetFileInformationByHandle(hFile, &file_info)) {
607 err = GetLastError();
608 ERROR("Failed to get file information for \"%ls\"", path);
610 ret = WIMLIB_ERR_STAT;
612 *ino_ret = ((u64)file_info.nFileIndexHigh << 32) |
613 (u64)file_info.nFileIndexLow;
614 *dev_ret = file_info.dwVolumeSerialNumber;
621 /* Reparse point fixup status code */
623 /* Reparse point corresponded to an absolute symbolic link or junction
624 * point that pointed outside the directory tree being captured, and
625 * therefore was excluded. */
628 /* Reparse point was not fixed as it was either a relative symbolic
629 * link, a mount point, or something else we could not understand. */
632 /* Reparse point corresponded to an absolute symbolic link or junction
633 * point that pointed inside the directory tree being captured, where
634 * the target was specified by a "full" \??\ prefixed path, and
635 * therefore was fixed to be relative to the root of the directory tree
637 RP_FIXED_FULLPATH = 0x2,
639 /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
640 * have the \??\ prefix. It may have begun with a drive letter though.
642 RP_FIXED_ABSPATH = 0x4,
644 /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
645 RP_FIXED = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
648 /* Given the "substitute name" target of a Windows reparse point, try doing a
649 * fixup where we change it to be absolute relative to the root of the directory
650 * tree being captured.
652 * Note that this is only executed when WIMLIB_ADD_IMAGE_FLAG_RPFIX has been
655 * @capture_root_ino and @capture_root_dev indicate the inode number and device
656 * of the root of the directory tree being captured. They are meant to identify
657 * this directory (as an alternative to its actual path, which could potentially
658 * be reached via multiple destinations due to other symbolic links). This may
659 * not work properly on FAT, which doesn't seem to supply proper inode numbers
660 * or file IDs. However, FAT doesn't support reparse points so this function
661 * wouldn't even be called anyway. */
662 static enum rp_status
663 win32_maybe_rpfix_target(wchar_t *target, size_t *target_nchars_p,
664 u64 capture_root_ino, u64 capture_root_dev)
666 size_t target_nchars= *target_nchars_p;
667 size_t stripped_chars;
668 wchar_t *orig_target;
670 if (target_nchars == 0)
671 /* Invalid reparse point (empty target) */
674 if (target[0] == L'\\') {
675 if (target_nchars >= 2 && target[1] == L'\\') {
676 /* Probably a volume. Can't do anything with it. */
677 DEBUG("Not fixing target (probably a volume)");
679 } else if (target_nchars >= 7 &&
687 DEBUG("Full style path");
688 /* Full \??\x:\ style path (may be junction or symlink)
692 DEBUG("Absolute target without drive letter");
693 /* Absolute target, without drive letter */
696 } else if (target_nchars >= 3 &&
697 target[0] != L'\0' &&
701 DEBUG("Absolute target with drive letter");
702 /* Absolute target, with drive letter */
705 DEBUG("Relative symlink or other link");
706 /* Relative symlink or other unexpected format */
709 target[target_nchars] = L'\0';
710 orig_target = target;
711 target = fixup_symlink(target + stripped_chars, capture_root_ino, capture_root_dev);
715 target_nchars = wcslen(target);
716 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
717 *target_nchars_p = target_nchars + stripped_chars;
718 DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
719 if (stripped_chars == 6)
720 return RP_FIXED_FULLPATH;
722 return RP_FIXED_ABSPATH;
725 static enum rp_status
726 win32_do_capture_rpfix(char *rpbuf, DWORD *rpbuflen_p,
727 u64 capture_root_ino, u64 capture_root_dev)
731 u16 substitute_name_offset;
732 u16 substitute_name_len;
734 size_t target_nchars;
735 enum rp_status status;
737 DWORD rpbuflen = *rpbuflen_p;
739 if (rpbuflen < 16) /* Invalid reparse point (length too small) */
741 p_get = get_u32(rpbuf, &rptag);
743 p_get = get_u16(p_get, &substitute_name_offset);
744 p_get = get_u16(p_get, &substitute_name_len);
746 if (rptag == WIM_IO_REPARSE_TAG_SYMLINK) {
747 if (rpbuflen < 20) /* Invalid reparse point (length too small) */
751 if ((DWORD)substitute_name_offset +
752 substitute_name_len + (p_get - rpbuf) > rpbuflen)
753 /* Invalid reparse point (length too small) */
756 target = (wchar_t*)&p_get[substitute_name_offset];
757 target_nchars = substitute_name_len / 2;
758 /* Note: target is not necessarily null-terminated */
760 status = win32_maybe_rpfix_target(target, &target_nchars,
761 capture_root_ino, capture_root_dev);
762 if (status & RP_FIXED) {
763 size_t target_nbytes = target_nchars * 2;
764 size_t print_nbytes = target_nbytes;
765 wchar_t target_copy[target_nchars];
766 wchar_t *print_name = target_copy;
768 if (status == RP_FIXED_FULLPATH) {
769 /* "full path", meaning \??\ prefixed. We should not
770 * include this prefix in the print name, as it is
771 * apparently meant for the filesystem driver only. */
775 wmemcpy(target_copy, target, target_nchars);
777 p_put = put_u16(p_put, 0); /* Substitute name offset */
778 p_put = put_u16(p_put, target_nbytes); /* Substitute name length */
779 p_put = put_u16(p_put, target_nbytes + 2); /* Print name offset */
780 p_put = put_u16(p_put, print_nbytes); /* Print name length */
781 if (rptag == WIM_IO_REPARSE_TAG_SYMLINK)
782 p_put = put_u32(p_put, 1);
783 p_put = put_bytes(p_put, target_nbytes, target_copy);
784 p_put = put_u16(p_put, 0);
785 p_put = put_bytes(p_put, print_nbytes, print_name);
786 p_put = put_u16(p_put, 0);
788 /* Wrote the end of the reparse data. Recalculate the length,
789 * set the length field correctly, and return it. */
790 rpbuflen = p_put - rpbuf;
791 put_u16(rpbuf + 4, rpbuflen - 8);
792 *rpbuflen_p = rpbuflen;
797 /* Load a reparse point into a WIM inode. It is just stored in memory.
799 * @hFile is the open handle to a reparse point, with permission to read the
802 * @inode is the WIM inode for the reparse point.
805 win32_capture_reparse_point(struct wim_dentry **root_p,
807 struct wim_inode *inode,
809 struct add_image_params *params)
811 DEBUG("Capturing reparse point \"%ls\"", path);
813 /* "Reparse point data, including the tag and optional GUID,
814 * cannot exceed 16 kilobytes." - MSDN */
815 char reparse_point_buf[REPARSE_POINT_MAX_SIZE];
820 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
821 NULL, /* "Not used with this operation; set to NULL" */
822 0, /* "Not used with this operation; set to 0" */
823 reparse_point_buf, /* "A pointer to a buffer that
824 receives the reparse point data */
825 sizeof(reparse_point_buf), /* "The size of the output
830 DWORD err = GetLastError();
831 ERROR("Failed to get reparse data of \"%ls\"", path);
833 return WIMLIB_ERR_READ;
835 if (bytesReturned < 8) {
836 ERROR("Reparse data on \"%ls\" is invalid", path);
837 return WIMLIB_ERR_READ;
839 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
841 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX &&
842 (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
843 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
845 /* Try doing reparse point fixup */
846 enum rp_status status;
847 status = win32_do_capture_rpfix(reparse_point_buf,
849 params->capture_root_ino,
850 params->capture_root_dev);
851 if (status == RP_EXCLUDED) {
852 /* Absolute path points out of capture tree. Free the
853 * dentry; we're not including it at all. */
854 free_dentry(*root_p);
857 } else if (status & RP_FIXED) {
858 /* Absolute path fixup was done. */
859 inode->i_not_rpfixed = 0;
862 return inode_set_unnamed_stream(inode, reparse_point_buf + 8,
863 bytesReturned - 8, params->lookup_table);
866 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
867 * stream); calculates its SHA1 message digest and either creates a `struct
868 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
869 * wim_lookup_table_entry' for an identical stream.
871 * @path: Path to the file (UTF-16LE).
873 * @path_num_chars: Number of 2-byte characters in @path.
875 * @inode: WIM inode to save the stream into.
877 * @lookup_table: Stream lookup table for the WIM.
879 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
882 * Returns 0 on success; nonzero on failure.
885 win32_capture_stream(const wchar_t *path,
886 size_t path_num_chars,
887 struct wim_inode *inode,
888 struct wim_lookup_table *lookup_table,
889 WIN32_FIND_STREAM_DATA *dat)
891 struct wim_ads_entry *ads_entry;
892 struct wim_lookup_table_entry *lte;
894 wchar_t *stream_name, *colon;
895 size_t stream_name_nchars;
896 bool is_named_stream;
899 size_t spath_buf_nbytes;
900 const wchar_t *relpath_prefix;
901 const wchar_t *colonchar;
903 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
905 /* The stream name should be returned as :NAME:TYPE */
906 stream_name = dat->cStreamName;
907 if (*stream_name != L':')
908 goto out_invalid_stream_name;
910 colon = wcschr(stream_name, L':');
912 goto out_invalid_stream_name;
914 if (wcscmp(colon + 1, L"$DATA")) {
915 /* Not a DATA stream */
922 stream_name_nchars = colon - stream_name;
923 is_named_stream = (stream_name_nchars != 0);
925 if (is_named_stream) {
926 /* Allocate an ADS entry for the named stream. */
927 ads_entry = inode_add_ads_utf16le(inode, stream_name,
928 stream_name_nchars * sizeof(wchar_t));
930 ret = WIMLIB_ERR_NOMEM;
935 /* If zero length stream, no lookup table entry needed. */
936 if ((u64)dat->StreamSize.QuadPart == 0) {
941 /* Create a UTF-16LE string @spath that gives the filename, then a
942 * colon, then the stream name. Or, if it's an unnamed stream, just the
943 * filename. It is MALLOC()'ed so that it can be saved in the
944 * wim_lookup_table_entry if needed.
946 * As yet another special case, relative paths need to be changed to
947 * begin with an explicit "./" so that, for example, a file t:ads, where
948 * :ads is the part we added, is not interpreted as a file on the t:
950 spath_nchars = path_num_chars;
951 relpath_prefix = L"";
953 if (is_named_stream) {
954 spath_nchars += 1 + stream_name_nchars;
956 if (path_num_chars == 1 &&
961 relpath_prefix = L"./";
965 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
966 spath = MALLOC(spath_buf_nbytes);
968 swprintf(spath, L"%ls%ls%ls%ls",
969 relpath_prefix, path, colonchar, stream_name);
971 /* Make a new wim_lookup_table_entry */
972 lte = new_lookup_table_entry();
974 ret = WIMLIB_ERR_NOMEM;
977 lte->file_on_disk = spath;
979 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream)
980 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
982 lte->resource_location = RESOURCE_WIN32;
983 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
986 if (is_named_stream) {
987 stream_id = ads_entry->stream_id;
988 ads_entry->lte = lte;
993 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
999 out_invalid_stream_name:
1000 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
1001 ret = WIMLIB_ERR_READ;
1005 /* Scans a Win32 file for unnamed and named data streams (not reparse point
1008 * @path: Path to the file (UTF-16LE).
1010 * @path_num_chars: Number of 2-byte characters in @path.
1012 * @inode: WIM inode to save the stream into.
1014 * @lookup_table: Stream lookup table for the WIM.
1016 * @file_size: Size of unnamed data stream. (Used only if alternate
1017 * data streams API appears to be unavailable.)
1019 * @vol_flags: Flags that specify features of the volume being
1022 * Returns 0 on success; nonzero on failure.
1025 win32_capture_streams(const wchar_t *path,
1026 size_t path_num_chars,
1027 struct wim_inode *inode,
1028 struct wim_lookup_table *lookup_table,
1032 WIN32_FIND_STREAM_DATA dat;
1037 DEBUG("Capturing streams from \"%ls\"", path);
1039 if (win32func_FindFirstStreamW == NULL ||
1040 !(vol_flags & FILE_NAMED_STREAMS))
1043 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1044 if (hFind == INVALID_HANDLE_VALUE) {
1045 err = GetLastError();
1046 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1049 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1050 * points and directories */
1051 if ((inode->i_attributes &
1052 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1053 && err == ERROR_HANDLE_EOF)
1055 DEBUG("ERROR_HANDLE_EOF (ok)");
1058 if (err == ERROR_ACCESS_DENIED) {
1059 ERROR("Failed to look up data streams "
1060 "of \"%ls\": Access denied!\n%ls",
1061 path, capture_access_denied_msg);
1062 return WIMLIB_ERR_READ;
1064 ERROR("Failed to look up data streams "
1065 "of \"%ls\"", path);
1067 return WIMLIB_ERR_READ;
1072 ret = win32_capture_stream(path,
1074 inode, lookup_table,
1077 goto out_find_close;
1078 } while (win32func_FindNextStreamW(hFind, &dat));
1079 err = GetLastError();
1080 if (err != ERROR_HANDLE_EOF) {
1081 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
1083 ret = WIMLIB_ERR_READ;
1089 /* FindFirstStreamW() API is not available, or the volume does not
1090 * support named streams. Only capture the unnamed data stream. */
1091 DEBUG("Only capturing unnamed data stream");
1092 if (inode->i_attributes &
1093 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1097 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
1098 * stream to reduce the code to a call to the
1099 * already-implemented win32_capture_stream() */
1100 wcscpy(dat.cStreamName, L"::$DATA");
1101 dat.StreamSize.QuadPart = file_size;
1102 ret = win32_capture_stream(path,
1104 inode, lookup_table,
1111 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1113 size_t path_num_chars,
1114 struct add_image_params *params,
1115 struct win32_capture_state *state,
1118 struct wim_dentry *root = NULL;
1119 struct wim_inode *inode;
1123 const wchar_t *basename;
1125 if (exclude_path(path, path_num_chars, params->config, true)) {
1126 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
1127 ERROR("Cannot exclude the root directory from capture");
1128 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1131 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
1132 && params->progress_func)
1134 union wimlib_progress_info info;
1135 info.scan.cur_path = path;
1136 info.scan.excluded = true;
1137 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1142 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
1143 && params->progress_func)
1145 union wimlib_progress_info info;
1146 info.scan.cur_path = path;
1147 info.scan.excluded = false;
1148 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1151 HANDLE hFile = win32_open_existing_file(path,
1152 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1153 if (hFile == INVALID_HANDLE_VALUE) {
1154 err = GetLastError();
1155 ERROR("Win32 API: Failed to open \"%ls\"", path);
1157 ret = WIMLIB_ERR_OPEN;
1161 BY_HANDLE_FILE_INFORMATION file_info;
1162 if (!GetFileInformationByHandle(hFile, &file_info)) {
1163 err = GetLastError();
1164 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1167 ret = WIMLIB_ERR_STAT;
1168 goto out_close_handle;
1171 /* Create a WIM dentry with an associated inode, which may be shared.
1173 * However, we need to explicitly check for directories and files with
1174 * only 1 link and refuse to hard link them. This is because Windows
1175 * has a bug where it can return duplicate File IDs for files and
1176 * directories on the FAT filesystem. */
1177 basename = path_basename_with_len(path, path_num_chars);
1178 if (!(file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1179 && file_info.nNumberOfLinks > 1)
1181 ret = inode_table_new_dentry(params->inode_table,
1183 ((u64)file_info.nFileIndexHigh << 32) |
1184 (u64)file_info.nFileIndexLow,
1185 file_info.dwVolumeSerialNumber,
1188 goto out_close_handle;
1190 ret = new_dentry_with_inode(basename, &root);
1192 goto out_close_handle;
1193 list_add_tail(&root->d_inode->i_list, ¶ms->inode_table->extra_inodes);
1197 ret = win32_get_short_name(root, path);
1199 goto out_close_handle;
1201 inode = root->d_inode;
1203 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1204 goto out_close_handle;
1206 inode->i_attributes = file_info.dwFileAttributes;
1207 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1208 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1209 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1210 inode->i_resolved = 1;
1212 params->add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
1214 if (!(params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)
1215 && (vol_flags & FILE_PERSISTENT_ACLS))
1217 ret = win32_get_security_descriptor(root, params->sd_set,
1219 params->add_image_flags);
1221 goto out_close_handle;
1224 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1225 (u64)file_info.nFileSizeLow;
1227 if (inode_is_directory(inode)) {
1228 /* Directory (not a reparse point) --- recurse to children */
1230 /* But first... directories may have alternate data streams that
1231 * need to be captured. */
1232 ret = win32_capture_streams(path,
1235 params->lookup_table,
1239 goto out_close_handle;
1240 ret = win32_recurse_directory(root,
1246 } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1247 /* Reparse point: save the reparse tag and data. Alternate data
1248 * streams are not captured, if it's even possible for a reparse
1249 * point to have alternate data streams... */
1250 ret = win32_capture_reparse_point(&root, hFile, inode, path, params);
1252 /* Not a directory, not a reparse point; capture the default
1253 * file contents and any alternate data streams. */
1254 ret = win32_capture_streams(path,
1257 params->lookup_table,
1267 free_dentry_tree(root, params->lookup_table);
1272 win32_do_capture_warnings(const struct win32_capture_state *state,
1273 int add_image_flags)
1275 if (state->num_get_sacl_priv_notheld == 0 &&
1276 state->num_get_sd_access_denied == 0)
1280 WARNING("Built dentry tree successfully, but with the following problem(s):");
1281 if (state->num_get_sacl_priv_notheld != 0) {
1282 WARNING("Could not capture SACL (System Access Control List)\n"
1283 " on %lu files or directories.",
1284 state->num_get_sacl_priv_notheld);
1286 if (state->num_get_sd_access_denied != 0) {
1287 WARNING("Could not capture security descriptor at all\n"
1288 " on %lu files or directories.",
1289 state->num_get_sd_access_denied);
1292 "Try running the program as the Administrator to make sure all the\n"
1293 " desired metadata has been captured exactly. However, if you\n"
1294 " do not care about capturing security descriptors correctly, then\n"
1295 " nothing more needs to be done%ls\n",
1296 (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
1297 L", although you might consider\n"
1298 " passing the --no-acls flag to `wimlib-imagex capture' or\n"
1299 " `wimlib-imagex append' to explicitly capture no security\n"
1303 /* Win32 version of capturing a directory tree */
1305 win32_build_dentry_tree(struct wim_dentry **root_ret,
1306 const wchar_t *root_disk_path,
1307 struct add_image_params *params)
1312 struct win32_capture_state state;
1316 path_nchars = wcslen(root_disk_path);
1317 if (path_nchars > 32767)
1318 return WIMLIB_ERR_INVALID_PARAM;
1320 ret = win32_get_file_and_vol_ids(root_disk_path,
1321 ¶ms->capture_root_ino,
1322 ¶ms->capture_root_dev);
1326 win32_get_vol_flags(root_disk_path, &vol_flags);
1328 /* There is no check for overflow later when this buffer is being used!
1329 * But the max path length on NTFS is 32767 characters, and paths need
1330 * to be written specially to even go past 260 characters, so we should
1331 * be okay with 32770 characters. */
1332 path = MALLOC(32770 * sizeof(wchar_t));
1334 return WIMLIB_ERR_NOMEM;
1336 wmemcpy(path, root_disk_path, path_nchars + 1);
1338 memset(&state, 0, sizeof(state));
1339 ret = win32_build_dentry_tree_recursive(root_ret, path,
1340 path_nchars, params,
1344 win32_do_capture_warnings(&state, params->add_image_flags);
1349 win32_set_reparse_data(HANDLE h,
1351 const struct wim_lookup_table_entry *lte,
1352 const wchar_t *path)
1359 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
1363 len = wim_resource_size(lte);
1364 if (len > 16 * 1024 - 8) {
1365 WARNING("\"%ls\": reparse data too long!", path);
1369 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
1370 * leave 8 bytes of space for them at the beginning of the buffer, then
1371 * set them manually. */
1372 buf = alloca(len + 8);
1373 ret = read_full_resource_into_buf(lte, buf + 8, false);
1376 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
1377 *(u16*)(buf + 4) = cpu_to_le16(len);
1378 *(u16*)(buf + 6) = 0;
1380 /* Set the reparse data on the open file using the
1381 * FSCTL_SET_REPARSE_POINT ioctl.
1383 * There are contradictions in Microsoft's documentation for this:
1385 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1386 * lpOverlapped is ignored."
1388 * --- So setting lpOverlapped to NULL is okay since it's ignored.
1390 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1391 * operation returns no output data and lpOutBuffer is NULL,
1392 * DeviceIoControl makes use of lpBytesReturned. After such an
1393 * operation, the value of lpBytesReturned is meaningless."
1395 * --- So lpOverlapped not really ignored, as it affects another
1396 * parameter. This is the actual behavior: lpBytesReturned must be
1397 * specified, even though lpBytesReturned is documented as:
1399 * "Not used with this operation; set to NULL."
1401 DWORD bytesReturned;
1402 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
1404 &bytesReturned /* lpBytesReturned */,
1405 NULL /* lpOverlapped */))
1407 DWORD err = GetLastError();
1408 ERROR("Failed to set reparse data on \"%ls\"", path);
1410 return WIMLIB_ERR_WRITE;
1416 win32_set_compressed(HANDLE hFile, const wchar_t *path)
1418 USHORT format = COMPRESSION_FORMAT_DEFAULT;
1419 DWORD bytesReturned = 0;
1420 if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1421 &format, sizeof(USHORT),
1423 &bytesReturned, NULL))
1425 /* Could be a warning only, but we only call this if the volume
1426 * supports compression. So I'm calling this an error. */
1427 DWORD err = GetLastError();
1428 ERROR("Failed to set compression flag on \"%ls\"", path);
1430 return WIMLIB_ERR_WRITE;
1436 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1438 DWORD bytesReturned = 0;
1439 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1442 &bytesReturned, NULL))
1444 /* Could be a warning only, but we only call this if the volume
1445 * supports sparse files. So I'm calling this an error. */
1446 DWORD err = GetLastError();
1447 WARNING("Failed to set sparse flag on \"%ls\"", path);
1449 return WIMLIB_ERR_WRITE;
1455 * Sets the security descriptor on an extracted file.
1458 win32_set_security_data(const struct wim_inode *inode,
1459 const wchar_t *path,
1460 struct apply_args *args)
1462 PSECURITY_DESCRIPTOR descriptor;
1466 descriptor = wim_const_security_data(args->w)->descriptors[inode->i_security_id];
1468 SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
1469 SACL_SECURITY_INFORMATION |
1470 OWNER_SECURITY_INFORMATION |
1471 GROUP_SECURITY_INFORMATION;
1473 if (SetFileSecurityW(path, securityInformation, descriptor))
1475 err = GetLastError();
1476 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1479 case ERROR_PRIVILEGE_NOT_HELD:
1480 if (securityInformation & SACL_SECURITY_INFORMATION) {
1481 n = args->num_set_sacl_priv_notheld++;
1482 securityInformation &= ~SACL_SECURITY_INFORMATION;
1483 if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1485 "We don't have enough privileges to set the full security\n"
1486 " descriptor on \"%ls\"!\n", path);
1487 if (args->num_set_sd_access_denied +
1488 args->num_set_sacl_priv_notheld == 1)
1490 WARNING("%ls", apply_access_denied_msg);
1492 WARNING("Re-trying with SACL omitted.\n", path);
1493 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1495 "Suppressing further 'privileges not held' error messages when setting\n"
1496 " security descriptors.");
1501 case ERROR_INVALID_OWNER:
1502 case ERROR_ACCESS_DENIED:
1503 n = args->num_set_sd_access_denied++;
1504 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1505 WARNING("Failed to set security descriptor on \"%ls\": "
1506 "Access denied!\n", path);
1507 if (args->num_set_sd_access_denied +
1508 args->num_set_sacl_priv_notheld == 1)
1510 WARNING("%ls", apply_access_denied_msg);
1512 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1514 "Suppressing further access denied error messages when setting\n"
1515 " security descriptors");
1520 ERROR("Failed to set security descriptor on \"%ls\"", path);
1522 return WIMLIB_ERR_WRITE;
1528 win32_extract_chunk(const void *buf, size_t len, void *arg)
1530 HANDLE hStream = arg;
1532 DWORD nbytes_written;
1533 wimlib_assert(len <= 0xffffffff);
1535 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1536 nbytes_written != len)
1538 DWORD err = GetLastError();
1539 ERROR("WriteFile(): write error");
1541 return WIMLIB_ERR_WRITE;
1547 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1549 return extract_wim_resource(lte, wim_resource_size(lte),
1550 win32_extract_chunk, hStream);
1554 do_win32_extract_encrypted_stream(const wchar_t *path,
1555 const struct wim_lookup_table_entry *lte)
1557 ERROR("Extracting encryted streams not implemented");
1558 return WIMLIB_ERR_INVALID_PARAM;
1562 path_is_root_of_drive(const wchar_t *path)
1567 if (*path != L'/' && *path != L'\\') {
1568 if (*(path + 1) == L':')
1573 while (*path == L'/' || *path == L'\\')
1575 return (*path == L'\0');
1579 win32_get_create_flags_and_attributes(DWORD i_attributes)
1584 * Some attributes cannot be set by passing them to CreateFile(). In
1587 * FILE_ATTRIBUTE_DIRECTORY:
1588 * CreateDirectory() must be called instead of CreateFile().
1590 * FILE_ATTRIBUTE_SPARSE_FILE:
1592 * See: win32_set_sparse().
1594 * FILE_ATTRIBUTE_COMPRESSED:
1595 * Not clear from the documentation, but apparently this needs an
1597 * See: win32_set_compressed().
1599 * FILE_ATTRIBUTE_REPARSE_POINT:
1600 * Needs an ioctl, with the reparse data specified.
1601 * See: win32_set_reparse_data().
1603 * In addition, clear any file flags in the attributes that we don't
1604 * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1605 * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1607 attributes = i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1608 FILE_ATTRIBUTE_COMPRESSED |
1609 FILE_ATTRIBUTE_REPARSE_POINT |
1610 FILE_ATTRIBUTE_DIRECTORY |
1611 FILE_FLAG_DELETE_ON_CLOSE |
1612 FILE_FLAG_NO_BUFFERING |
1613 FILE_FLAG_OPEN_NO_RECALL |
1614 FILE_FLAG_OVERLAPPED |
1615 FILE_FLAG_RANDOM_ACCESS |
1616 /*FILE_FLAG_SESSION_AWARE |*/
1617 FILE_FLAG_SEQUENTIAL_SCAN |
1618 FILE_FLAG_WRITE_THROUGH);
1620 FILE_FLAG_OPEN_REPARSE_POINT |
1621 FILE_FLAG_BACKUP_SEMANTICS;
1625 inode_has_special_attributes(const struct wim_inode *inode)
1627 return (inode->i_attributes & (FILE_ATTRIBUTE_COMPRESSED |
1628 FILE_ATTRIBUTE_REPARSE_POINT |
1629 FILE_ATTRIBUTE_SPARSE_FILE)) != 0;
1632 /* Set compression or sparse attributes, and reparse data, if supported by the
1635 win32_set_special_attributes(HANDLE hFile, const struct wim_inode *inode,
1636 struct wim_lookup_table_entry *unnamed_stream_lte,
1637 const wchar_t *path, unsigned vol_flags)
1641 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1642 if (vol_flags & FILE_FILE_COMPRESSION) {
1643 DEBUG("Setting compression flag on \"%ls\"", path);
1644 ret = win32_set_compressed(hFile, path);
1648 DEBUG("Cannot set compression attribute on \"%ls\": "
1649 "volume does not support transparent compression",
1654 if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1655 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1656 DEBUG("Setting sparse flag on \"%ls\"", path);
1657 ret = win32_set_sparse(hFile, path);
1661 DEBUG("Cannot set sparse attribute on \"%ls\": "
1662 "volume does not support sparse files",
1667 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1668 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
1669 DEBUG("Setting reparse data on \"%ls\"", path);
1670 ret = win32_set_reparse_data(hFile, inode->i_reparse_tag,
1671 unnamed_stream_lte, path);
1675 DEBUG("Cannot set reparse data on \"%ls\": volume "
1676 "does not support reparse points", path);
1684 win32_extract_stream(const struct wim_inode *inode,
1685 const wchar_t *path,
1686 const wchar_t *stream_name_utf16,
1687 struct wim_lookup_table_entry *lte,
1690 wchar_t *stream_path;
1694 DWORD creationDisposition = CREATE_ALWAYS;
1696 if (stream_name_utf16) {
1697 /* Named stream. Create a buffer that contains the UTF-16LE
1698 * string [.\]@path:@stream_name_utf16. This is needed to
1699 * create and open the stream using CreateFileW(). I'm not
1700 * aware of any other APIs to do this. Note: the '$DATA' suffix
1701 * seems to be unneeded. Additional note: a "./" prefix needs
1702 * to be added when the path is not absolute to avoid ambiguity
1703 * with drive letters. */
1704 size_t stream_path_nchars;
1706 size_t stream_name_nchars;
1707 const wchar_t *prefix;
1709 path_nchars = wcslen(path);
1710 stream_name_nchars = wcslen(stream_name_utf16);
1711 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1712 if (path[0] != cpu_to_le16(L'\0') &&
1713 path[0] != cpu_to_le16(L'/') &&
1714 path[0] != cpu_to_le16(L'\\') &&
1715 path[1] != cpu_to_le16(L':'))
1718 stream_path_nchars += 2;
1722 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1723 swprintf(stream_path, L"%ls%ls:%ls",
1724 prefix, path, stream_name_utf16);
1726 /* Unnamed stream; its path is just the path to the file itself.
1728 stream_path = (wchar_t*)path;
1730 /* Directories must be created with CreateDirectoryW(). Then
1731 * the call to CreateFileW() will merely open the directory that
1732 * was already created rather than creating a new file. */
1733 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1734 if (!CreateDirectoryW(stream_path, NULL)) {
1735 err = GetLastError();
1737 case ERROR_ALREADY_EXISTS:
1739 case ERROR_ACCESS_DENIED:
1740 if (path_is_root_of_drive(path))
1744 ERROR("Failed to create directory \"%ls\"",
1747 ret = WIMLIB_ERR_MKDIR;
1751 DEBUG("Created directory \"%ls\"", stream_path);
1752 if (!inode_has_special_attributes(inode)) {
1756 DEBUG("Directory \"%ls\" has special attributes!",
1758 creationDisposition = OPEN_EXISTING;
1762 DEBUG("Opening \"%ls\"", stream_path);
1763 h = CreateFileW(stream_path,
1764 GENERIC_READ | GENERIC_WRITE,
1767 creationDisposition,
1768 win32_get_create_flags_and_attributes(inode->i_attributes),
1770 if (h == INVALID_HANDLE_VALUE) {
1771 err = GetLastError();
1772 ERROR("Failed to create \"%ls\"", stream_path);
1774 ret = WIMLIB_ERR_OPEN;
1778 if (stream_name_utf16 == NULL && inode_has_special_attributes(inode)) {
1779 ret = win32_set_special_attributes(h, inode, lte, path,
1782 goto fail_close_handle;
1785 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1787 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1788 stream_path, wim_resource_size(lte));
1789 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED
1790 && stream_name_utf16 == NULL
1791 && (vol_flags & FILE_SUPPORTS_ENCRYPTION))
1793 ret = do_win32_extract_encrypted_stream(stream_path,
1796 ret = do_win32_extract_stream(h, lte);
1799 goto fail_close_handle;
1803 DEBUG("Closing \"%ls\"", stream_path);
1804 if (!CloseHandle(h)) {
1805 err = GetLastError();
1806 ERROR("Failed to close \"%ls\"", stream_path);
1808 ret = WIMLIB_ERR_WRITE;
1816 ERROR("Error extracting %ls", stream_path);
1822 * Creates a file, directory, or reparse point and extracts all streams to it
1823 * (unnamed data stream and/or reparse point stream, plus any alternate data
1824 * streams). This in Win32-specific code.
1826 * @inode: WIM inode for this file or directory.
1827 * @path: UTF-16LE external path to extract the inode to.
1829 * Returns 0 on success; nonzero on failure.
1832 win32_extract_streams(const struct wim_inode *inode,
1833 const wchar_t *path, u64 *completed_bytes_p,
1836 struct wim_lookup_table_entry *unnamed_lte;
1839 unnamed_lte = inode_unnamed_lte_resolved(inode);
1840 ret = win32_extract_stream(inode, path, NULL, unnamed_lte,
1844 if (unnamed_lte && inode->i_extracted_file == NULL)
1845 *completed_bytes_p += wim_resource_size(unnamed_lte);
1847 if (!(vol_flags & FILE_NAMED_STREAMS))
1849 for (u16 i = 0; i < inode->i_num_ads; i++) {
1850 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1851 if (ads_entry->stream_name_nbytes != 0) {
1852 /* Skip special UNIX data entries (see documentation for
1853 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1854 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1855 && !memcmp(ads_entry->stream_name,
1856 WIMLIB_UNIX_DATA_TAG_UTF16LE,
1857 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1859 ret = win32_extract_stream(inode,
1861 ads_entry->stream_name,
1866 if (ads_entry->lte && inode->i_extracted_file == NULL)
1867 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1874 /* Extract a file, directory, reparse point, or hard link to an
1875 * already-extracted file using the Win32 API */
1877 win32_do_apply_dentry(const wchar_t *output_path,
1878 size_t output_path_num_chars,
1879 struct wim_dentry *dentry,
1880 struct apply_args *args)
1883 struct wim_inode *inode = dentry->d_inode;
1886 if (!args->have_vol_flags) {
1887 win32_get_vol_flags(output_path, &args->vol_flags);
1888 args->have_vol_flags = true;
1889 /* Warn the user about data that may not be extracted. */
1890 if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
1891 WARNING("Volume does not support sparse files!\n"
1892 " Sparse files will be extracted as non-sparse.");
1893 if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1894 WARNING("Volume does not support reparse points!\n"
1895 " Reparse point data will not be extracted.");
1896 if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
1897 WARNING("Volume does not support named data streams!\n"
1898 " Named data streams will not be extracted.");
1900 if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
1901 WARNING("Volume does not support encryption!\n"
1902 " Encrypted files will be extracted as raw data.");
1904 if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
1905 WARNING("Volume does not support transparent compression!\n"
1906 " Compressed files will be extracted as non-compressed.");
1908 if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
1909 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
1910 ERROR("Strict ACLs requested, but the volume does not "
1912 return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
1914 WARNING("Volume does not support persistent ACLS!\n"
1915 " File permissions will not be extracted.");
1920 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1921 /* Linked file, with another name already extracted. Create a
1924 /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
1925 * but it's only available on Windows 7 and later. So no use
1926 * even checking it, really. Instead, CreateHardLinkW() will
1927 * apparently return ERROR_INVALID_FUNCTION if the volume does
1928 * not support hard links. */
1929 DEBUG("Creating hard link \"%ls => %ls\"",
1930 output_path, inode->i_extracted_file);
1931 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
1934 err = GetLastError();
1935 if (err != ERROR_INVALID_FUNCTION) {
1936 ERROR("Can't create hard link \"%ls => %ls\"",
1937 output_path, inode->i_extracted_file);
1939 return WIMLIB_ERR_LINK;
1941 args->num_hard_links_failed++;
1942 if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
1943 WARNING("Can't create hard link \"%ls => %ls\":\n"
1944 " Volume does not support hard links!\n"
1945 " Falling back to extracting a copy of the file.",
1946 output_path, inode->i_extracted_file);
1947 } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
1948 WARNING("Suppressing further hard linking warnings...");
1953 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1954 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1956 WARNING("Skipping extraction of reparse point \"%ls\":\n"
1957 " Not supported by destination filesystem",
1959 struct wim_lookup_table_entry *lte;
1960 lte = inode_unnamed_lte_resolved(inode);
1962 args->progress.extract.completed_bytes += wim_resource_size(lte);
1966 /* Create the file, directory, or reparse point, and extract the
1968 ret = win32_extract_streams(inode, output_path,
1969 &args->progress.extract.completed_bytes,
1974 if (inode->i_security_id >= 0 &&
1975 !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
1976 && (args->vol_flags & FILE_PERSISTENT_ACLS))
1978 ret = win32_set_security_data(inode, output_path, args);
1982 if (inode->i_nlink > 1) {
1983 /* Save extracted path for a later call to
1984 * CreateHardLinkW() if this inode has multiple links.
1986 inode->i_extracted_file = WSTRDUP(output_path);
1987 if (!inode->i_extracted_file)
1988 ret = WIMLIB_ERR_NOMEM;
1993 /* Set timestamps on an extracted file using the Win32 API */
1995 win32_do_apply_dentry_timestamps(const wchar_t *path,
1996 size_t path_num_chars,
1997 const struct wim_dentry *dentry,
1998 const struct apply_args *args)
2002 const struct wim_inode *inode = dentry->d_inode;
2004 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2005 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2007 /* Skip reparse points not extracted */
2011 /* Windows doesn't let you change the timestamps of the root directory
2012 * (at least on FAT, which is dumb but expected since FAT doesn't store
2013 * any metadata about the root directory...) */
2014 if (path_is_root_of_drive(path))
2017 DEBUG("Opening \"%ls\" to set timestamps", path);
2018 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
2019 if (h == INVALID_HANDLE_VALUE) {
2020 err = GetLastError();
2024 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
2025 .dwHighDateTime = inode->i_creation_time >> 32};
2026 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
2027 .dwHighDateTime = inode->i_last_access_time >> 32};
2028 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
2029 .dwHighDateTime = inode->i_last_write_time >> 32};
2031 DEBUG("Calling SetFileTime() on \"%ls\"", path);
2032 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
2033 err = GetLastError();
2037 DEBUG("Closing \"%ls\"", path);
2038 if (!CloseHandle(h)) {
2039 err = GetLastError();
2044 /* Only warn if setting timestamps failed; still return 0. */
2045 WARNING("Can't set timestamps on \"%ls\"", path);
2051 /* Replacement for POSIX fsync() */
2058 h = (HANDLE)_get_osfhandle(fd);
2059 if (h == INVALID_HANDLE_VALUE) {
2060 err = GetLastError();
2061 ERROR("Could not get Windows handle for file descriptor");
2066 if (!FlushFileBuffers(h)) {
2067 err = GetLastError();
2068 ERROR("Could not flush file buffers to disk");
2076 /* Use the Win32 API to get the number of processors */
2078 win32_get_number_of_processors()
2080 SYSTEM_INFO sysinfo;
2081 GetSystemInfo(&sysinfo);
2082 return sysinfo.dwNumberOfProcessors;
2085 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
2086 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
2087 * really does the right thing under all circumstances. */
2089 realpath(const wchar_t *path, wchar_t *resolved_path)
2092 wimlib_assert(resolved_path == NULL);
2095 ret = GetFullPathNameW(path, 0, NULL, NULL);
2097 err = GetLastError();
2101 resolved_path = TMALLOC(ret);
2104 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2106 err = GetLastError();
2107 free(resolved_path);
2108 resolved_path = NULL;
2116 return resolved_path;
2119 /* rename() on Windows fails if the destination file exists. And we need to
2120 * make it work on wide characters. Fix it. */
2122 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2124 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2127 /* As usual, the possible error values are not documented */
2128 DWORD err = GetLastError();
2129 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2137 /* Replacement for POSIX fnmatch() (partial functionality only) */
2139 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2141 if (PathMatchSpecW(string, pattern))
2147 /* truncate() replacement */
2149 win32_truncate_replacement(const wchar_t *path, off_t size)
2151 DWORD err = NO_ERROR;
2152 LARGE_INTEGER liOffset;
2154 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2155 if (h == INVALID_HANDLE_VALUE)
2158 liOffset.QuadPart = size;
2159 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2160 goto fail_close_handle;
2162 if (!SetEndOfFile(h))
2163 goto fail_close_handle;
2168 err = GetLastError();
2171 if (err == NO_ERROR)
2172 err = GetLastError();
2173 ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2180 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2181 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2182 * linked in by Visual Studio...?). */
2184 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2186 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2188 pthread_mutex_lock(&strerror_lock);
2189 mbstowcs(buf, strerror(errnum), buflen);
2190 buf[buflen - 1] = '\0';
2191 pthread_mutex_unlock(&strerror_lock);
2195 #endif /* __WIN32__ */