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);
714 target_nchars = wcslen(target);
715 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
716 *target_nchars_p = target_nchars + stripped_chars;
717 DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
718 if (stripped_chars == 6)
719 return RP_FIXED_FULLPATH;
721 return RP_FIXED_ABSPATH;
724 static enum rp_status
725 win32_try_capture_rpfix(char *rpbuf, DWORD *rpbuflen_p,
726 u64 capture_root_ino, u64 capture_root_dev)
730 u16 substitute_name_offset;
731 u16 substitute_name_len;
733 size_t target_nchars;
734 enum rp_status status;
736 DWORD rpbuflen = *rpbuflen_p;
738 if (rpbuflen < 16) /* Invalid reparse point (length too small) */
740 p_get = get_u32(rpbuf, &rptag);
742 p_get = get_u16(p_get, &substitute_name_offset);
743 p_get = get_u16(p_get, &substitute_name_len);
745 if (rptag == WIM_IO_REPARSE_TAG_SYMLINK) {
746 if (rpbuflen < 20) /* Invalid reparse point (length too small) */
750 if ((DWORD)substitute_name_offset +
751 substitute_name_len + (p_get - rpbuf) > rpbuflen)
752 /* Invalid reparse point (length too small) */
755 target = (wchar_t*)&p_get[substitute_name_offset];
756 target_nchars = substitute_name_len / 2;
757 /* Note: target is not necessarily null-terminated */
759 status = win32_maybe_rpfix_target(target, &target_nchars,
760 capture_root_ino, capture_root_dev);
761 if (status & RP_FIXED) {
762 size_t target_nbytes = target_nchars * 2;
763 size_t print_nbytes = target_nbytes;
764 wchar_t target_copy[target_nchars];
765 wchar_t *print_name = target_copy;
767 if (status == RP_FIXED_FULLPATH) {
768 /* "full path", meaning \??\ prefixed. We should not
769 * include this prefix in the print name, as it is
770 * apparently meant for the filesystem driver only. */
774 wmemcpy(target_copy, target, target_nchars);
776 p_put = put_u16(p_put, 0); /* Substitute name offset */
777 p_put = put_u16(p_put, target_nbytes); /* Substitute name length */
778 p_put = put_u16(p_put, target_nbytes + 2); /* Print name offset */
779 p_put = put_u16(p_put, print_nbytes); /* Print name length */
780 if (rptag == WIM_IO_REPARSE_TAG_SYMLINK)
781 p_put = put_u32(p_put, 1);
782 p_put = put_bytes(p_put, target_nbytes, target_copy);
783 p_put = put_u16(p_put, 0);
784 p_put = put_bytes(p_put, print_nbytes, print_name);
785 p_put = put_u16(p_put, 0);
787 /* Wrote the end of the reparse data. Recalculate the length,
788 * set the length field correctly, and return it. */
789 rpbuflen = p_put - rpbuf;
790 put_u16(rpbuf + 4, rpbuflen - 8);
791 *rpbuflen_p = rpbuflen;
797 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
798 struct add_image_params *params,
799 void *reparse_data, size_t *reparse_data_len_ret)
803 enum rp_status status;
805 DEBUG("Loading reparse data from \"%ls\"", path);
806 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
807 NULL, /* "Not used with this operation; set to NULL" */
808 0, /* "Not used with this operation; set to 0" */
809 reparse_data, /* "A pointer to a buffer that
810 receives the reparse point data */
811 REPARSE_POINT_MAX_SIZE, /* "The size of the output
816 DWORD err = GetLastError();
817 ERROR("Failed to get reparse data of \"%ls\"", path);
819 return -WIMLIB_ERR_READ;
821 if (bytesReturned < 8) {
822 ERROR("Reparse data on \"%ls\" is invalid", path);
823 return -WIMLIB_ERR_READ;
826 reparse_tag = le32_to_cpu(*(u32*)reparse_data);
827 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX &&
828 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
829 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
831 /* Try doing reparse point fixup */
832 status = win32_try_capture_rpfix(reparse_data,
834 params->capture_root_ino,
835 params->capture_root_dev);
837 status = RP_NOT_FIXED;
839 *reparse_data_len_ret = bytesReturned;
843 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
844 * stream); calculates its SHA1 message digest and either creates a `struct
845 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
846 * wim_lookup_table_entry' for an identical stream.
848 * @path: Path to the file (UTF-16LE).
850 * @path_num_chars: Number of 2-byte characters in @path.
852 * @inode: WIM inode to save the stream into.
854 * @lookup_table: Stream lookup table for the WIM.
856 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
859 * Returns 0 on success; nonzero on failure.
862 win32_capture_stream(const wchar_t *path,
863 size_t path_num_chars,
864 struct wim_inode *inode,
865 struct wim_lookup_table *lookup_table,
866 WIN32_FIND_STREAM_DATA *dat)
868 struct wim_ads_entry *ads_entry;
869 struct wim_lookup_table_entry *lte;
871 wchar_t *stream_name, *colon;
872 size_t stream_name_nchars;
873 bool is_named_stream;
876 size_t spath_buf_nbytes;
877 const wchar_t *relpath_prefix;
878 const wchar_t *colonchar;
880 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
882 /* The stream name should be returned as :NAME:TYPE */
883 stream_name = dat->cStreamName;
884 if (*stream_name != L':')
885 goto out_invalid_stream_name;
887 colon = wcschr(stream_name, L':');
889 goto out_invalid_stream_name;
891 if (wcscmp(colon + 1, L"$DATA")) {
892 /* Not a DATA stream */
899 stream_name_nchars = colon - stream_name;
900 is_named_stream = (stream_name_nchars != 0);
902 if (is_named_stream) {
903 /* Allocate an ADS entry for the named stream. */
904 ads_entry = inode_add_ads_utf16le(inode, stream_name,
905 stream_name_nchars * sizeof(wchar_t));
907 ret = WIMLIB_ERR_NOMEM;
912 /* If zero length stream, no lookup table entry needed. */
913 if ((u64)dat->StreamSize.QuadPart == 0) {
918 /* Create a UTF-16LE string @spath that gives the filename, then a
919 * colon, then the stream name. Or, if it's an unnamed stream, just the
920 * filename. It is MALLOC()'ed so that it can be saved in the
921 * wim_lookup_table_entry if needed.
923 * As yet another special case, relative paths need to be changed to
924 * begin with an explicit "./" so that, for example, a file t:ads, where
925 * :ads is the part we added, is not interpreted as a file on the t:
927 spath_nchars = path_num_chars;
928 relpath_prefix = L"";
930 if (is_named_stream) {
931 spath_nchars += 1 + stream_name_nchars;
933 if (path_num_chars == 1 &&
938 relpath_prefix = L"./";
942 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
943 spath = MALLOC(spath_buf_nbytes);
945 swprintf(spath, L"%ls%ls%ls%ls",
946 relpath_prefix, path, colonchar, stream_name);
948 /* Make a new wim_lookup_table_entry */
949 lte = new_lookup_table_entry();
951 ret = WIMLIB_ERR_NOMEM;
954 lte->file_on_disk = spath;
956 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream)
957 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
959 lte->resource_location = RESOURCE_WIN32;
960 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
963 if (is_named_stream) {
964 stream_id = ads_entry->stream_id;
965 ads_entry->lte = lte;
970 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
976 out_invalid_stream_name:
977 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
978 ret = WIMLIB_ERR_READ;
982 /* Scans a Win32 file for unnamed and named data streams (not reparse point
985 * @path: Path to the file (UTF-16LE).
987 * @path_num_chars: Number of 2-byte characters in @path.
989 * @inode: WIM inode to save the stream into.
991 * @lookup_table: Stream lookup table for the WIM.
993 * @file_size: Size of unnamed data stream. (Used only if alternate
994 * data streams API appears to be unavailable.)
996 * @vol_flags: Flags that specify features of the volume being
999 * Returns 0 on success; nonzero on failure.
1002 win32_capture_streams(const wchar_t *path,
1003 size_t path_num_chars,
1004 struct wim_inode *inode,
1005 struct wim_lookup_table *lookup_table,
1009 WIN32_FIND_STREAM_DATA dat;
1014 DEBUG("Capturing streams from \"%ls\"", path);
1016 if (win32func_FindFirstStreamW == NULL ||
1017 !(vol_flags & FILE_NAMED_STREAMS))
1020 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1021 if (hFind == INVALID_HANDLE_VALUE) {
1022 err = GetLastError();
1023 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1026 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1027 * points and directories */
1028 if ((inode->i_attributes &
1029 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1030 && err == ERROR_HANDLE_EOF)
1032 DEBUG("ERROR_HANDLE_EOF (ok)");
1035 if (err == ERROR_ACCESS_DENIED) {
1036 ERROR("Failed to look up data streams "
1037 "of \"%ls\": Access denied!\n%ls",
1038 path, capture_access_denied_msg);
1039 return WIMLIB_ERR_READ;
1041 ERROR("Failed to look up data streams "
1042 "of \"%ls\"", path);
1044 return WIMLIB_ERR_READ;
1049 ret = win32_capture_stream(path,
1051 inode, lookup_table,
1054 goto out_find_close;
1055 } while (win32func_FindNextStreamW(hFind, &dat));
1056 err = GetLastError();
1057 if (err != ERROR_HANDLE_EOF) {
1058 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
1060 ret = WIMLIB_ERR_READ;
1066 /* FindFirstStreamW() API is not available, or the volume does not
1067 * support named streams. Only capture the unnamed data stream. */
1068 DEBUG("Only capturing unnamed data stream");
1069 if (inode->i_attributes &
1070 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1074 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
1075 * stream to reduce the code to a call to the
1076 * already-implemented win32_capture_stream() */
1077 wcscpy(dat.cStreamName, L"::$DATA");
1078 dat.StreamSize.QuadPart = file_size;
1079 ret = win32_capture_stream(path,
1081 inode, lookup_table,
1088 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1090 size_t path_num_chars,
1091 struct add_image_params *params,
1092 struct win32_capture_state *state,
1095 struct wim_dentry *root = NULL;
1096 struct wim_inode *inode;
1101 size_t reparse_data_len;
1104 if (exclude_path(path, path_num_chars, params->config, true)) {
1105 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
1106 ERROR("Cannot exclude the root directory from capture");
1107 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1110 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
1111 && params->progress_func)
1113 union wimlib_progress_info info;
1114 info.scan.cur_path = path;
1115 info.scan.excluded = true;
1116 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1122 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
1123 && params->progress_func)
1125 union wimlib_progress_info info;
1126 info.scan.cur_path = path;
1127 info.scan.excluded = false;
1128 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1131 HANDLE hFile = win32_open_existing_file(path,
1132 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1133 if (hFile == INVALID_HANDLE_VALUE) {
1134 err = GetLastError();
1135 ERROR("Win32 API: Failed to open \"%ls\"", path);
1137 ret = WIMLIB_ERR_OPEN;
1141 BY_HANDLE_FILE_INFORMATION file_info;
1142 if (!GetFileInformationByHandle(hFile, &file_info)) {
1143 err = GetLastError();
1144 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1147 ret = WIMLIB_ERR_STAT;
1148 goto out_close_handle;
1151 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1152 reparse_data = alloca(REPARSE_POINT_MAX_SIZE);
1153 ret = win32_get_reparse_data(hFile, path, params,
1154 reparse_data, &reparse_data_len);
1156 /* WIMLIB_ERR_* (inverted) */
1158 goto out_close_handle;
1159 } else if (ret & RP_FIXED) {
1161 } else if (ret == RP_EXCLUDED) {
1163 goto out_close_handle;
1169 /* Create a WIM dentry with an associated inode, which may be shared.
1171 * However, we need to explicitly check for directories and files with
1172 * only 1 link and refuse to hard link them. This is because Windows
1173 * has a bug where it can return duplicate File IDs for files and
1174 * directories on the FAT filesystem. */
1175 ret = inode_table_new_dentry(params->inode_table,
1176 path_basename_with_len(path, path_num_chars),
1177 ((u64)file_info.nFileIndexHigh << 32) |
1178 (u64)file_info.nFileIndexLow,
1179 file_info.dwVolumeSerialNumber,
1180 (file_info.nNumberOfLinks <= 1 ||
1181 (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1184 goto out_close_handle;
1186 ret = win32_get_short_name(root, path);
1188 goto out_close_handle;
1190 inode = root->d_inode;
1192 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1193 goto out_close_handle;
1195 inode->i_attributes = file_info.dwFileAttributes;
1196 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1197 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1198 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1199 inode->i_resolved = 1;
1201 params->add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
1203 if (!(params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)
1204 && (vol_flags & FILE_PERSISTENT_ACLS))
1206 ret = win32_get_security_descriptor(root, params->sd_set,
1208 params->add_image_flags);
1210 goto out_close_handle;
1213 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1214 (u64)file_info.nFileSizeLow;
1216 /* Capture the unnamed data stream (only should be present for regular
1217 * files) and any alternate data streams. */
1218 ret = win32_capture_streams(path,
1221 params->lookup_table,
1225 goto out_close_handle;
1227 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1228 /* Reparse point: set the reparse data (which we read already)
1230 inode->i_not_rpfixed = not_rpfixed;
1231 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_data);
1232 ret = inode_set_unnamed_stream(inode, reparse_data + 8,
1233 reparse_data_len - 8,
1234 params->lookup_table);
1235 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1236 /* Directory (not a reparse point) --- recurse to children */
1237 ret = win32_recurse_directory(root,
1250 free_dentry_tree(root, params->lookup_table);
1255 win32_do_capture_warnings(const struct win32_capture_state *state,
1256 int add_image_flags)
1258 if (state->num_get_sacl_priv_notheld == 0 &&
1259 state->num_get_sd_access_denied == 0)
1263 WARNING("Built dentry tree successfully, but with the following problem(s):");
1264 if (state->num_get_sacl_priv_notheld != 0) {
1265 WARNING("Could not capture SACL (System Access Control List)\n"
1266 " on %lu files or directories.",
1267 state->num_get_sacl_priv_notheld);
1269 if (state->num_get_sd_access_denied != 0) {
1270 WARNING("Could not capture security descriptor at all\n"
1271 " on %lu files or directories.",
1272 state->num_get_sd_access_denied);
1275 "Try running the program as the Administrator to make sure all the\n"
1276 " desired metadata has been captured exactly. However, if you\n"
1277 " do not care about capturing security descriptors correctly, then\n"
1278 " nothing more needs to be done%ls\n",
1279 (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
1280 L", although you might consider\n"
1281 " passing the --no-acls flag to `wimlib-imagex capture' or\n"
1282 " `wimlib-imagex append' to explicitly capture no security\n"
1286 /* Win32 version of capturing a directory tree */
1288 win32_build_dentry_tree(struct wim_dentry **root_ret,
1289 const wchar_t *root_disk_path,
1290 struct add_image_params *params)
1295 struct win32_capture_state state;
1299 path_nchars = wcslen(root_disk_path);
1300 if (path_nchars > 32767)
1301 return WIMLIB_ERR_INVALID_PARAM;
1303 ret = win32_get_file_and_vol_ids(root_disk_path,
1304 ¶ms->capture_root_ino,
1305 ¶ms->capture_root_dev);
1309 win32_get_vol_flags(root_disk_path, &vol_flags);
1311 /* There is no check for overflow later when this buffer is being used!
1312 * But the max path length on NTFS is 32767 characters, and paths need
1313 * to be written specially to even go past 260 characters, so we should
1314 * be okay with 32770 characters. */
1315 path = MALLOC(32770 * sizeof(wchar_t));
1317 return WIMLIB_ERR_NOMEM;
1319 wmemcpy(path, root_disk_path, path_nchars + 1);
1321 memset(&state, 0, sizeof(state));
1322 ret = win32_build_dentry_tree_recursive(root_ret, path,
1323 path_nchars, params,
1327 win32_do_capture_warnings(&state, params->add_image_flags);
1332 win32_set_reparse_data(HANDLE h,
1334 const struct wim_lookup_table_entry *lte,
1335 const wchar_t *path)
1342 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
1346 len = wim_resource_size(lte);
1347 if (len > 16 * 1024 - 8) {
1348 WARNING("\"%ls\": reparse data too long!", path);
1352 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
1353 * leave 8 bytes of space for them at the beginning of the buffer, then
1354 * set them manually. */
1355 buf = alloca(len + 8);
1356 ret = read_full_resource_into_buf(lte, buf + 8, false);
1359 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
1360 *(u16*)(buf + 4) = cpu_to_le16(len);
1361 *(u16*)(buf + 6) = 0;
1363 /* Set the reparse data on the open file using the
1364 * FSCTL_SET_REPARSE_POINT ioctl.
1366 * There are contradictions in Microsoft's documentation for this:
1368 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1369 * lpOverlapped is ignored."
1371 * --- So setting lpOverlapped to NULL is okay since it's ignored.
1373 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1374 * operation returns no output data and lpOutBuffer is NULL,
1375 * DeviceIoControl makes use of lpBytesReturned. After such an
1376 * operation, the value of lpBytesReturned is meaningless."
1378 * --- So lpOverlapped not really ignored, as it affects another
1379 * parameter. This is the actual behavior: lpBytesReturned must be
1380 * specified, even though lpBytesReturned is documented as:
1382 * "Not used with this operation; set to NULL."
1384 DWORD bytesReturned;
1385 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
1387 &bytesReturned /* lpBytesReturned */,
1388 NULL /* lpOverlapped */))
1390 DWORD err = GetLastError();
1391 ERROR("Failed to set reparse data on \"%ls\"", path);
1393 return WIMLIB_ERR_WRITE;
1399 win32_set_compressed(HANDLE hFile, const wchar_t *path)
1401 USHORT format = COMPRESSION_FORMAT_DEFAULT;
1402 DWORD bytesReturned = 0;
1403 if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1404 &format, sizeof(USHORT),
1406 &bytesReturned, NULL))
1408 /* Could be a warning only, but we only call this if the volume
1409 * supports compression. So I'm calling this an error. */
1410 DWORD err = GetLastError();
1411 ERROR("Failed to set compression flag on \"%ls\"", path);
1413 return WIMLIB_ERR_WRITE;
1419 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1421 DWORD bytesReturned = 0;
1422 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1425 &bytesReturned, NULL))
1427 /* Could be a warning only, but we only call this if the volume
1428 * supports sparse files. So I'm calling this an error. */
1429 DWORD err = GetLastError();
1430 WARNING("Failed to set sparse flag on \"%ls\"", path);
1432 return WIMLIB_ERR_WRITE;
1438 * Sets the security descriptor on an extracted file.
1441 win32_set_security_data(const struct wim_inode *inode,
1442 const wchar_t *path,
1443 struct apply_args *args)
1445 PSECURITY_DESCRIPTOR descriptor;
1449 descriptor = wim_const_security_data(args->w)->descriptors[inode->i_security_id];
1451 SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
1452 SACL_SECURITY_INFORMATION |
1453 OWNER_SECURITY_INFORMATION |
1454 GROUP_SECURITY_INFORMATION;
1456 if (SetFileSecurityW(path, securityInformation, descriptor))
1458 err = GetLastError();
1459 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1462 case ERROR_PRIVILEGE_NOT_HELD:
1463 if (securityInformation & SACL_SECURITY_INFORMATION) {
1464 n = args->num_set_sacl_priv_notheld++;
1465 securityInformation &= ~SACL_SECURITY_INFORMATION;
1466 if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1468 "We don't have enough privileges to set the full security\n"
1469 " descriptor on \"%ls\"!\n", path);
1470 if (args->num_set_sd_access_denied +
1471 args->num_set_sacl_priv_notheld == 1)
1473 WARNING("%ls", apply_access_denied_msg);
1475 WARNING("Re-trying with SACL omitted.\n", path);
1476 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1478 "Suppressing further 'privileges not held' error messages when setting\n"
1479 " security descriptors.");
1484 case ERROR_INVALID_OWNER:
1485 case ERROR_ACCESS_DENIED:
1486 n = args->num_set_sd_access_denied++;
1487 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1488 WARNING("Failed to set security descriptor on \"%ls\": "
1489 "Access denied!\n", path);
1490 if (args->num_set_sd_access_denied +
1491 args->num_set_sacl_priv_notheld == 1)
1493 WARNING("%ls", apply_access_denied_msg);
1495 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1497 "Suppressing further access denied error messages when setting\n"
1498 " security descriptors");
1503 ERROR("Failed to set security descriptor on \"%ls\"", path);
1505 return WIMLIB_ERR_WRITE;
1511 win32_extract_chunk(const void *buf, size_t len, void *arg)
1513 HANDLE hStream = arg;
1515 DWORD nbytes_written;
1516 wimlib_assert(len <= 0xffffffff);
1518 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1519 nbytes_written != len)
1521 DWORD err = GetLastError();
1522 ERROR("WriteFile(): write error");
1524 return WIMLIB_ERR_WRITE;
1530 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1532 return extract_wim_resource(lte, wim_resource_size(lte),
1533 win32_extract_chunk, hStream);
1537 do_win32_extract_encrypted_stream(const wchar_t *path,
1538 const struct wim_lookup_table_entry *lte)
1540 ERROR("Extracting encryted streams not implemented");
1541 return WIMLIB_ERR_INVALID_PARAM;
1545 path_is_root_of_drive(const wchar_t *path)
1550 if (*path != L'/' && *path != L'\\') {
1551 if (*(path + 1) == L':')
1556 while (*path == L'/' || *path == L'\\')
1558 return (*path == L'\0');
1562 win32_get_create_flags_and_attributes(DWORD i_attributes)
1567 * Some attributes cannot be set by passing them to CreateFile(). In
1570 * FILE_ATTRIBUTE_DIRECTORY:
1571 * CreateDirectory() must be called instead of CreateFile().
1573 * FILE_ATTRIBUTE_SPARSE_FILE:
1575 * See: win32_set_sparse().
1577 * FILE_ATTRIBUTE_COMPRESSED:
1578 * Not clear from the documentation, but apparently this needs an
1580 * See: win32_set_compressed().
1582 * FILE_ATTRIBUTE_REPARSE_POINT:
1583 * Needs an ioctl, with the reparse data specified.
1584 * See: win32_set_reparse_data().
1586 * In addition, clear any file flags in the attributes that we don't
1587 * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1588 * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1590 attributes = i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1591 FILE_ATTRIBUTE_COMPRESSED |
1592 FILE_ATTRIBUTE_REPARSE_POINT |
1593 FILE_ATTRIBUTE_DIRECTORY |
1594 FILE_FLAG_DELETE_ON_CLOSE |
1595 FILE_FLAG_NO_BUFFERING |
1596 FILE_FLAG_OPEN_NO_RECALL |
1597 FILE_FLAG_OVERLAPPED |
1598 FILE_FLAG_RANDOM_ACCESS |
1599 /*FILE_FLAG_SESSION_AWARE |*/
1600 FILE_FLAG_SEQUENTIAL_SCAN |
1601 FILE_FLAG_WRITE_THROUGH);
1603 FILE_FLAG_OPEN_REPARSE_POINT |
1604 FILE_FLAG_BACKUP_SEMANTICS;
1608 inode_has_special_attributes(const struct wim_inode *inode)
1610 return (inode->i_attributes & (FILE_ATTRIBUTE_COMPRESSED |
1611 FILE_ATTRIBUTE_REPARSE_POINT |
1612 FILE_ATTRIBUTE_SPARSE_FILE)) != 0;
1615 /* Set compression or sparse attributes, and reparse data, if supported by the
1618 win32_set_special_attributes(HANDLE hFile, const struct wim_inode *inode,
1619 struct wim_lookup_table_entry *unnamed_stream_lte,
1620 const wchar_t *path, unsigned vol_flags)
1624 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1625 if (vol_flags & FILE_FILE_COMPRESSION) {
1626 DEBUG("Setting compression flag on \"%ls\"", path);
1627 ret = win32_set_compressed(hFile, path);
1631 DEBUG("Cannot set compression attribute on \"%ls\": "
1632 "volume does not support transparent compression",
1637 if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1638 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1639 DEBUG("Setting sparse flag on \"%ls\"", path);
1640 ret = win32_set_sparse(hFile, path);
1644 DEBUG("Cannot set sparse attribute on \"%ls\": "
1645 "volume does not support sparse files",
1650 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1651 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
1652 DEBUG("Setting reparse data on \"%ls\"", path);
1653 ret = win32_set_reparse_data(hFile, inode->i_reparse_tag,
1654 unnamed_stream_lte, path);
1658 DEBUG("Cannot set reparse data on \"%ls\": volume "
1659 "does not support reparse points", path);
1667 win32_extract_stream(const struct wim_inode *inode,
1668 const wchar_t *path,
1669 const wchar_t *stream_name_utf16,
1670 struct wim_lookup_table_entry *lte,
1673 wchar_t *stream_path;
1677 DWORD creationDisposition = CREATE_ALWAYS;
1679 if (stream_name_utf16) {
1680 /* Named stream. Create a buffer that contains the UTF-16LE
1681 * string [.\]@path:@stream_name_utf16. This is needed to
1682 * create and open the stream using CreateFileW(). I'm not
1683 * aware of any other APIs to do this. Note: the '$DATA' suffix
1684 * seems to be unneeded. Additional note: a "./" prefix needs
1685 * to be added when the path is not absolute to avoid ambiguity
1686 * with drive letters. */
1687 size_t stream_path_nchars;
1689 size_t stream_name_nchars;
1690 const wchar_t *prefix;
1692 path_nchars = wcslen(path);
1693 stream_name_nchars = wcslen(stream_name_utf16);
1694 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1695 if (path[0] != cpu_to_le16(L'\0') &&
1696 path[0] != cpu_to_le16(L'/') &&
1697 path[0] != cpu_to_le16(L'\\') &&
1698 path[1] != cpu_to_le16(L':'))
1701 stream_path_nchars += 2;
1705 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1706 swprintf(stream_path, L"%ls%ls:%ls",
1707 prefix, path, stream_name_utf16);
1709 /* Unnamed stream; its path is just the path to the file itself.
1711 stream_path = (wchar_t*)path;
1713 /* Directories must be created with CreateDirectoryW(). Then
1714 * the call to CreateFileW() will merely open the directory that
1715 * was already created rather than creating a new file. */
1716 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1717 if (!CreateDirectoryW(stream_path, NULL)) {
1718 err = GetLastError();
1720 case ERROR_ALREADY_EXISTS:
1722 case ERROR_ACCESS_DENIED:
1723 if (path_is_root_of_drive(path))
1727 ERROR("Failed to create directory \"%ls\"",
1730 ret = WIMLIB_ERR_MKDIR;
1734 DEBUG("Created directory \"%ls\"", stream_path);
1735 if (!inode_has_special_attributes(inode)) {
1739 DEBUG("Directory \"%ls\" has special attributes!",
1741 creationDisposition = OPEN_EXISTING;
1745 DEBUG("Opening \"%ls\"", stream_path);
1746 h = CreateFileW(stream_path,
1747 GENERIC_READ | GENERIC_WRITE,
1750 creationDisposition,
1751 win32_get_create_flags_and_attributes(inode->i_attributes),
1753 if (h == INVALID_HANDLE_VALUE) {
1754 err = GetLastError();
1755 ERROR("Failed to create \"%ls\"", stream_path);
1757 ret = WIMLIB_ERR_OPEN;
1761 if (stream_name_utf16 == NULL && inode_has_special_attributes(inode)) {
1762 ret = win32_set_special_attributes(h, inode, lte, path,
1765 goto fail_close_handle;
1768 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1770 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1771 stream_path, wim_resource_size(lte));
1772 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED
1773 && stream_name_utf16 == NULL
1774 && (vol_flags & FILE_SUPPORTS_ENCRYPTION))
1776 ret = do_win32_extract_encrypted_stream(stream_path,
1779 ret = do_win32_extract_stream(h, lte);
1782 goto fail_close_handle;
1786 DEBUG("Closing \"%ls\"", stream_path);
1787 if (!CloseHandle(h)) {
1788 err = GetLastError();
1789 ERROR("Failed to close \"%ls\"", stream_path);
1791 ret = WIMLIB_ERR_WRITE;
1799 ERROR("Error extracting %ls", stream_path);
1805 * Creates a file, directory, or reparse point and extracts all streams to it
1806 * (unnamed data stream and/or reparse point stream, plus any alternate data
1807 * streams). This in Win32-specific code.
1809 * @inode: WIM inode for this file or directory.
1810 * @path: UTF-16LE external path to extract the inode to.
1812 * Returns 0 on success; nonzero on failure.
1815 win32_extract_streams(const struct wim_inode *inode,
1816 const wchar_t *path, u64 *completed_bytes_p,
1819 struct wim_lookup_table_entry *unnamed_lte;
1822 unnamed_lte = inode_unnamed_lte_resolved(inode);
1823 ret = win32_extract_stream(inode, path, NULL, unnamed_lte,
1827 if (unnamed_lte && inode->i_extracted_file == NULL)
1828 *completed_bytes_p += wim_resource_size(unnamed_lte);
1830 if (!(vol_flags & FILE_NAMED_STREAMS))
1832 for (u16 i = 0; i < inode->i_num_ads; i++) {
1833 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1834 if (ads_entry->stream_name_nbytes != 0) {
1835 /* Skip special UNIX data entries (see documentation for
1836 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1837 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1838 && !memcmp(ads_entry->stream_name,
1839 WIMLIB_UNIX_DATA_TAG_UTF16LE,
1840 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1842 ret = win32_extract_stream(inode,
1844 ads_entry->stream_name,
1849 if (ads_entry->lte && inode->i_extracted_file == NULL)
1850 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1857 /* Extract a file, directory, reparse point, or hard link to an
1858 * already-extracted file using the Win32 API */
1860 win32_do_apply_dentry(const wchar_t *output_path,
1861 size_t output_path_num_chars,
1862 struct wim_dentry *dentry,
1863 struct apply_args *args)
1866 struct wim_inode *inode = dentry->d_inode;
1869 if (!args->have_vol_flags) {
1870 win32_get_vol_flags(output_path, &args->vol_flags);
1871 args->have_vol_flags = true;
1872 /* Warn the user about data that may not be extracted. */
1873 if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
1874 WARNING("Volume does not support sparse files!\n"
1875 " Sparse files will be extracted as non-sparse.");
1876 if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1877 WARNING("Volume does not support reparse points!\n"
1878 " Reparse point data will not be extracted.");
1879 if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
1880 WARNING("Volume does not support named data streams!\n"
1881 " Named data streams will not be extracted.");
1883 if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
1884 WARNING("Volume does not support encryption!\n"
1885 " Encrypted files will be extracted as raw data.");
1887 if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
1888 WARNING("Volume does not support transparent compression!\n"
1889 " Compressed files will be extracted as non-compressed.");
1891 if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
1892 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
1893 ERROR("Strict ACLs requested, but the volume does not "
1895 return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
1897 WARNING("Volume does not support persistent ACLS!\n"
1898 " File permissions will not be extracted.");
1903 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1904 /* Linked file, with another name already extracted. Create a
1907 /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
1908 * but it's only available on Windows 7 and later. So no use
1909 * even checking it, really. Instead, CreateHardLinkW() will
1910 * apparently return ERROR_INVALID_FUNCTION if the volume does
1911 * not support hard links. */
1912 DEBUG("Creating hard link \"%ls => %ls\"",
1913 output_path, inode->i_extracted_file);
1914 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
1917 err = GetLastError();
1918 if (err != ERROR_INVALID_FUNCTION) {
1919 ERROR("Can't create hard link \"%ls => %ls\"",
1920 output_path, inode->i_extracted_file);
1922 return WIMLIB_ERR_LINK;
1924 args->num_hard_links_failed++;
1925 if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
1926 WARNING("Can't create hard link \"%ls => %ls\":\n"
1927 " Volume does not support hard links!\n"
1928 " Falling back to extracting a copy of the file.",
1929 output_path, inode->i_extracted_file);
1930 } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
1931 WARNING("Suppressing further hard linking warnings...");
1936 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1937 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1939 WARNING("Skipping extraction of reparse point \"%ls\":\n"
1940 " Not supported by destination filesystem",
1942 struct wim_lookup_table_entry *lte;
1943 lte = inode_unnamed_lte_resolved(inode);
1945 args->progress.extract.completed_bytes += wim_resource_size(lte);
1949 /* Create the file, directory, or reparse point, and extract the
1951 ret = win32_extract_streams(inode, output_path,
1952 &args->progress.extract.completed_bytes,
1957 if (inode->i_security_id >= 0 &&
1958 !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
1959 && (args->vol_flags & FILE_PERSISTENT_ACLS))
1961 ret = win32_set_security_data(inode, output_path, args);
1965 if (inode->i_nlink > 1) {
1966 /* Save extracted path for a later call to
1967 * CreateHardLinkW() if this inode has multiple links.
1969 inode->i_extracted_file = WSTRDUP(output_path);
1970 if (!inode->i_extracted_file)
1971 ret = WIMLIB_ERR_NOMEM;
1976 /* Set timestamps on an extracted file using the Win32 API */
1978 win32_do_apply_dentry_timestamps(const wchar_t *path,
1979 size_t path_num_chars,
1980 const struct wim_dentry *dentry,
1981 const struct apply_args *args)
1985 const struct wim_inode *inode = dentry->d_inode;
1987 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1988 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1990 /* Skip reparse points not extracted */
1994 /* Windows doesn't let you change the timestamps of the root directory
1995 * (at least on FAT, which is dumb but expected since FAT doesn't store
1996 * any metadata about the root directory...) */
1997 if (path_is_root_of_drive(path))
2000 DEBUG("Opening \"%ls\" to set timestamps", path);
2001 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
2002 if (h == INVALID_HANDLE_VALUE) {
2003 err = GetLastError();
2007 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
2008 .dwHighDateTime = inode->i_creation_time >> 32};
2009 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
2010 .dwHighDateTime = inode->i_last_access_time >> 32};
2011 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
2012 .dwHighDateTime = inode->i_last_write_time >> 32};
2014 DEBUG("Calling SetFileTime() on \"%ls\"", path);
2015 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
2016 err = GetLastError();
2020 DEBUG("Closing \"%ls\"", path);
2021 if (!CloseHandle(h)) {
2022 err = GetLastError();
2027 /* Only warn if setting timestamps failed; still return 0. */
2028 WARNING("Can't set timestamps on \"%ls\"", path);
2034 /* Replacement for POSIX fsync() */
2041 h = (HANDLE)_get_osfhandle(fd);
2042 if (h == INVALID_HANDLE_VALUE) {
2043 err = GetLastError();
2044 ERROR("Could not get Windows handle for file descriptor");
2049 if (!FlushFileBuffers(h)) {
2050 err = GetLastError();
2051 ERROR("Could not flush file buffers to disk");
2059 /* Use the Win32 API to get the number of processors */
2061 win32_get_number_of_processors()
2063 SYSTEM_INFO sysinfo;
2064 GetSystemInfo(&sysinfo);
2065 return sysinfo.dwNumberOfProcessors;
2068 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
2069 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
2070 * really does the right thing under all circumstances. */
2072 realpath(const wchar_t *path, wchar_t *resolved_path)
2075 wimlib_assert(resolved_path == NULL);
2078 ret = GetFullPathNameW(path, 0, NULL, NULL);
2080 err = GetLastError();
2084 resolved_path = TMALLOC(ret);
2087 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2089 err = GetLastError();
2090 free(resolved_path);
2091 resolved_path = NULL;
2099 return resolved_path;
2102 /* rename() on Windows fails if the destination file exists. And we need to
2103 * make it work on wide characters. Fix it. */
2105 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2107 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2110 /* As usual, the possible error values are not documented */
2111 DWORD err = GetLastError();
2112 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2120 /* Replacement for POSIX fnmatch() (partial functionality only) */
2122 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2124 if (PathMatchSpecW(string, pattern))
2130 /* truncate() replacement */
2132 win32_truncate_replacement(const wchar_t *path, off_t size)
2134 DWORD err = NO_ERROR;
2135 LARGE_INTEGER liOffset;
2137 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2138 if (h == INVALID_HANDLE_VALUE)
2141 liOffset.QuadPart = size;
2142 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2143 goto fail_close_handle;
2145 if (!SetEndOfFile(h))
2146 goto fail_close_handle;
2151 err = GetLastError();
2154 if (err == NO_ERROR)
2155 err = GetLastError();
2156 ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2163 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2164 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2165 * linked in by Visual Studio...?). */
2167 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2169 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2171 pthread_mutex_lock(&strerror_lock);
2172 mbstowcs(buf, strerror(errnum), buflen);
2173 buf[buflen - 1] = '\0';
2174 pthread_mutex_unlock(&strerror_lock);
2178 #endif /* __WIN32__ */