4 * All the library code specific to native Windows builds is in here.
8 * Copyright (C) 2013 Eric Biggers
10 * This file is part of wimlib, a library for working with WIM files.
12 * wimlib is free software; you can redistribute it and/or modify it under the
13 * terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 3 of the License, or (at your option)
17 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 * A PARTICULAR PURPOSE. See the GNU General Public License for more
22 * You should have received a copy of the GNU General Public License
23 * along with wimlib; if not, see http://www.gnu.org/licenses/.
32 #include <shlwapi.h> /* for PathMatchSpecW() */
33 #include <aclapi.h> /* for SetSecurityInfo() */
34 #ifdef ERROR /* windows.h defines this */
40 #include "lookup_table.h"
42 #include "endianness.h"
43 #include "buffer_io.h"
48 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
49 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
50 #define MAX_CREATE_HARD_LINK_WARNINGS 5
51 struct win32_capture_state {
52 unsigned long num_get_sd_access_denied;
53 unsigned long num_get_sacl_priv_notheld;
56 #define MAX_SET_SD_ACCESS_DENIED_WARNINGS 1
57 #define MAX_SET_SACL_PRIV_NOTHELD_WARNINGS 1
59 #ifdef ENABLE_ERROR_MESSAGES
61 win32_error(u32 err_code)
65 nchars = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
66 FORMAT_MESSAGE_ALLOCATE_BUFFER,
68 (wchar_t*)&buffer, 0, NULL);
70 ERROR("Error printing error message! "
71 "Computer will self-destruct in 3 seconds.");
73 ERROR("Win32 error: %ls", buffer);
77 #else /* ENABLE_ERROR_MESSAGES */
78 # define win32_error(err_code)
79 #endif /* !ENABLE_ERROR_MESSAGES */
81 /* Pointers to functions that are not available on all targetted versions of
82 * Windows (XP and later). NOTE: The WINAPI annotations seem to be important; I
83 * assume it specifies a certain calling convention. */
86 static HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
87 STREAM_INFO_LEVELS InfoLevel,
88 LPVOID lpFindStreamData,
89 DWORD dwFlags) = NULL;
92 static BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
93 LPVOID lpFindStreamData) = NULL;
95 static HMODULE hKernel32 = NULL;
97 /* Try to dynamically load some functions */
103 if (hKernel32 == NULL) {
104 DEBUG("Loading Kernel32.dll");
105 hKernel32 = LoadLibraryW(L"Kernel32.dll");
106 if (hKernel32 == NULL) {
107 err = GetLastError();
108 WARNING("Can't load Kernel32.dll");
114 DEBUG("Looking for FindFirstStreamW");
115 win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32, "FindFirstStreamW");
116 if (!win32func_FindFirstStreamW) {
117 WARNING("Could not find function FindFirstStreamW() in Kernel32.dll!");
118 WARNING("Capturing alternate data streams will not be supported.");
122 DEBUG("Looking for FindNextStreamW");
123 win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32, "FindNextStreamW");
124 if (!win32func_FindNextStreamW) {
125 WARNING("Could not find function FindNextStreamW() in Kernel32.dll!");
126 WARNING("Capturing alternate data streams will not be supported.");
127 win32func_FindFirstStreamW = NULL;
132 win32_global_cleanup()
134 if (hKernel32 != NULL) {
135 DEBUG("Closing Kernel32.dll");
136 FreeLibrary(hKernel32);
141 static const wchar_t *capture_access_denied_msg =
142 L" If you are not running this program as the administrator, you may\n"
143 " need to do so, so that all data and metadata can be backed up.\n"
144 " Otherwise, there may be no way to access the desired data or\n"
145 " metadata without taking ownership of the file or directory.\n"
148 static const wchar_t *apply_access_denied_msg =
149 L"If you are not running this program as the administrator, you may\n"
150 " need to do so, so that all data and metadata can be extracted\n"
151 " exactly as the origignal copy. However, if you do not care that\n"
152 " the security descriptors are extracted correctly, you could run\n"
153 " `wimlib-imagex apply' with the --no-acls flag instead.\n"
157 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
159 return CreateFileW(path,
162 NULL, /* lpSecurityAttributes */
164 FILE_FLAG_BACKUP_SEMANTICS |
165 FILE_FLAG_OPEN_REPARSE_POINT,
166 NULL /* hTemplateFile */);
170 win32_open_file_data_only(const wchar_t *path)
172 return win32_open_existing_file(path, FILE_READ_DATA);
176 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
178 consume_data_callback_t cb,
187 HANDLE hFile = win32_open_file_data_only(lte->file_on_disk);
188 if (hFile == INVALID_HANDLE_VALUE) {
189 err = GetLastError();
190 ERROR("Failed to open \"%ls\"", lte->file_on_disk);
192 return WIMLIB_ERR_OPEN;
196 out_buf = alloca(WIM_CHUNK_SIZE);
198 out_buf = ctx_or_buf;
200 bytes_remaining = size;
201 while (bytes_remaining) {
202 DWORD bytesToRead, bytesRead;
204 bytesToRead = min(WIM_CHUNK_SIZE, bytes_remaining);
205 if (!ReadFile(hFile, out_buf, bytesToRead, &bytesRead, NULL) ||
206 bytesRead != bytesToRead)
208 err = GetLastError();
209 ERROR("Failed to read data from \"%ls\"", lte->file_on_disk);
211 ret = WIMLIB_ERR_READ;
214 bytes_remaining -= bytesRead;
216 ret = (*cb)(out_buf, bytesRead, ctx_or_buf);
220 out_buf += bytesRead;
227 struct win32_encrypted_read_ctx {
228 consume_data_callback_t read_prefix_cb;
229 void *read_prefix_ctx_or_buf;
237 win32_encrypted_export_cb(unsigned char *_data, void *_ctx, unsigned long len)
239 const void *data = _data;
240 struct win32_encrypted_read_ctx *ctx = _ctx;
243 DEBUG("len = %lu", len);
244 if (ctx->read_prefix_cb) {
245 /* The length of the buffer passed to the ReadEncryptedFileRaw()
246 * export callback is undocumented, so we assume it may be of
248 size_t bytes_to_buffer = min(ctx->bytes_remaining - ctx->buf_filled,
250 while (bytes_to_buffer) {
251 size_t bytes_to_copy_to_buf =
252 min(bytes_to_buffer, WIM_CHUNK_SIZE - ctx->buf_filled);
254 memcpy(ctx->buf + ctx->buf_filled, data,
255 bytes_to_copy_to_buf);
256 ctx->buf_filled += bytes_to_copy_to_buf;
257 data += bytes_to_copy_to_buf;
258 bytes_to_buffer -= bytes_to_copy_to_buf;
260 if (ctx->buf_filled == WIM_CHUNK_SIZE ||
261 ctx->buf_filled == ctx->bytes_remaining)
263 ret = (*ctx->read_prefix_cb)(ctx->buf,
265 ctx->read_prefix_ctx_or_buf);
267 ctx->wimlib_err_code = ret;
268 /* Shouldn't matter what error code is returned
269 * here, as long as it isn't ERROR_SUCCESS. */
270 return ERROR_READ_FAULT;
272 ctx->bytes_remaining -= ctx->buf_filled;
277 size_t len_to_copy = min(len, ctx->bytes_remaining);
278 memcpy(ctx->read_prefix_ctx_or_buf, data, len_to_copy);
279 ctx->bytes_remaining -= len_to_copy;
280 ctx->read_prefix_ctx_or_buf += len_to_copy;
282 return ERROR_SUCCESS;
286 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
288 consume_data_callback_t cb,
292 struct win32_encrypted_read_ctx export_ctx;
297 DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
298 size, lte->file_on_disk);
300 export_ctx.read_prefix_cb = cb;
301 export_ctx.read_prefix_ctx_or_buf = ctx_or_buf;
302 export_ctx.wimlib_err_code = 0;
304 export_ctx.buf = MALLOC(WIM_CHUNK_SIZE);
306 return WIMLIB_ERR_NOMEM;
308 export_ctx.buf = NULL;
310 export_ctx.bytes_remaining = size;
312 err = OpenEncryptedFileRawW(lte->file_on_disk, 0, &file_ctx);
313 if (err != ERROR_SUCCESS) {
314 ERROR("Failed to open encrypted file \"%ls\" for raw read",
317 ret = WIMLIB_ERR_OPEN;
320 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
321 &export_ctx, file_ctx);
322 if (err != ERROR_SUCCESS) {
323 ERROR("Failed to read encrypted file \"%ls\"",
326 ret = export_ctx.wimlib_err_code;
328 ret = WIMLIB_ERR_READ;
329 } else if (export_ctx.bytes_remaining != 0) {
330 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
331 "encryted file \"%ls\"",
332 size - export_ctx.bytes_remaining, size,
334 ret = WIMLIB_ERR_READ;
338 CloseEncryptedFileRaw(file_ctx);
340 FREE(export_ctx.buf);
344 /* Given a path, which may not yet exist, get a set of flags that describe the
345 * features of the volume the path is on. */
347 win32_get_vol_flags(const wchar_t *path, unsigned *vol_flags_ret)
353 if (path[0] != L'\0' && path[0] != L'\\' &&
354 path[0] != L'/' && path[1] == L':')
356 /* Path starts with a drive letter; use it. */
357 volume = alloca(4 * sizeof(wchar_t));
363 /* Path does not start with a drive letter; use the volume of
364 * the current working directory. */
367 bret = GetVolumeInformationW(volume, /* lpRootPathName */
368 NULL, /* lpVolumeNameBuffer */
369 0, /* nVolumeNameSize */
370 NULL, /* lpVolumeSerialNumber */
371 NULL, /* lpMaximumComponentLength */
372 &vol_flags, /* lpFileSystemFlags */
373 NULL, /* lpFileSystemNameBuffer */
374 0); /* nFileSystemNameSize */
376 DWORD err = GetLastError();
377 WARNING("Failed to get volume information for path \"%ls\"", path);
379 vol_flags = 0xffffffff;
382 DEBUG("using vol_flags = %x", vol_flags);
383 *vol_flags_ret = vol_flags;
389 FILETIME_to_u64(const FILETIME *ft)
391 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
395 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
397 WIN32_FIND_DATAW dat;
401 /* If we can't read the short filename for some reason, we just ignore
402 * the error and assume the file has no short name. I don't think this
403 * should be an issue, since the short names are essentially obsolete
405 hFind = FindFirstFileW(path, &dat);
406 if (hFind != INVALID_HANDLE_VALUE) {
407 if (dat.cAlternateFileName[0] != L'\0') {
408 DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
409 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
411 size_t n = short_name_nbytes + sizeof(wchar_t);
412 dentry->short_name = MALLOC(n);
413 if (dentry->short_name) {
414 memcpy(dentry->short_name, dat.cAlternateFileName, n);
415 dentry->short_name_nbytes = short_name_nbytes;
417 ret = WIMLIB_ERR_NOMEM;
426 win32_get_security_descriptor(struct wim_dentry *dentry,
427 struct sd_set *sd_set,
429 struct win32_capture_state *state,
432 SECURITY_INFORMATION requestedInformation;
438 requestedInformation = DACL_SECURITY_INFORMATION |
439 SACL_SECURITY_INFORMATION |
440 OWNER_SECURITY_INFORMATION |
441 GROUP_SECURITY_INFORMATION;
443 /* Request length of security descriptor */
444 status = GetFileSecurityW(path, requestedInformation,
445 NULL, 0, &lenNeeded);
446 err = GetLastError();
447 if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
448 DWORD len = lenNeeded;
450 if (GetFileSecurityW(path, requestedInformation,
451 (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
453 int security_id = sd_set_add_sd(sd_set, buf, len);
455 return WIMLIB_ERR_NOMEM;
457 dentry->d_inode->i_security_id = security_id;
461 err = GetLastError();
465 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS)
469 case ERROR_PRIVILEGE_NOT_HELD:
470 if (requestedInformation & SACL_SECURITY_INFORMATION) {
471 n = state->num_get_sacl_priv_notheld++;
472 requestedInformation &= ~SACL_SECURITY_INFORMATION;
473 if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
475 "We don't have enough privileges to read the full security\n"
476 " descriptor of \"%ls\"!\n"
477 " Re-trying with SACL omitted.\n", path);
478 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
480 "Suppressing further privileges not held error messages when reading\n"
481 " security descriptors.");
486 case ERROR_ACCESS_DENIED:
487 n = state->num_get_sd_access_denied++;
488 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
489 WARNING("Failed to read security descriptor of \"%ls\": "
490 "Access denied!\n%ls", path, capture_access_denied_msg);
491 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
492 WARNING("Suppressing further access denied errors messages i"
493 "when reading security descriptors");
498 ERROR("Failed to read security descriptor of \"%ls\"", path);
500 return WIMLIB_ERR_READ;
505 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
507 size_t path_num_chars,
508 struct add_image_params *params,
509 struct win32_capture_state *state,
512 /* Reads the directory entries of directory using a Win32 API and recursively
513 * calls win32_build_dentry_tree() on them. */
515 win32_recurse_directory(struct wim_dentry *root,
517 size_t dir_path_num_chars,
518 struct add_image_params *params,
519 struct win32_capture_state *state,
522 WIN32_FIND_DATAW dat;
527 DEBUG("Recurse to directory \"%ls\"", dir_path);
529 /* Begin reading the directory by calling FindFirstFileW. Unlike UNIX
530 * opendir(), FindFirstFileW has file globbing built into it. But this
531 * isn't what we actually want, so just add a dummy glob to get all
533 dir_path[dir_path_num_chars] = L'/';
534 dir_path[dir_path_num_chars + 1] = L'*';
535 dir_path[dir_path_num_chars + 2] = L'\0';
536 hFind = FindFirstFileW(dir_path, &dat);
537 dir_path[dir_path_num_chars] = L'\0';
539 if (hFind == INVALID_HANDLE_VALUE) {
540 err = GetLastError();
541 if (err == ERROR_FILE_NOT_FOUND) {
544 ERROR("Failed to read directory \"%ls\"", dir_path);
546 return WIMLIB_ERR_READ;
551 /* Skip . and .. entries */
552 if (dat.cFileName[0] == L'.' &&
553 (dat.cFileName[1] == L'\0' ||
554 (dat.cFileName[1] == L'.' &&
555 dat.cFileName[2] == L'\0')))
557 size_t filename_len = wcslen(dat.cFileName);
559 dir_path[dir_path_num_chars] = L'/';
560 wmemcpy(dir_path + dir_path_num_chars + 1,
564 struct wim_dentry *child;
565 size_t path_len = dir_path_num_chars + 1 + filename_len;
566 ret = win32_build_dentry_tree_recursive(&child,
572 dir_path[dir_path_num_chars] = L'\0';
576 dentry_add_child(root, child);
577 } while (FindNextFileW(hFind, &dat));
578 err = GetLastError();
579 if (err != ERROR_NO_MORE_FILES) {
580 ERROR("Failed to read directory \"%ls\"", dir_path);
583 ret = WIMLIB_ERR_READ;
591 win32_get_file_and_vol_ids(const wchar_t *path, u64 *ino_ret, u64 *dev_ret)
595 BY_HANDLE_FILE_INFORMATION file_info;
598 hFile = win32_open_existing_file(path, FILE_READ_ATTRIBUTES);
599 if (hFile == INVALID_HANDLE_VALUE) {
600 err = GetLastError();
601 WARNING("Failed to open \"%ls\" to get file and volume IDs",
604 return WIMLIB_ERR_OPEN;
607 if (!GetFileInformationByHandle(hFile, &file_info)) {
608 err = GetLastError();
609 ERROR("Failed to get file information for \"%ls\"", path);
611 ret = WIMLIB_ERR_STAT;
613 *ino_ret = ((u64)file_info.nFileIndexHigh << 32) |
614 (u64)file_info.nFileIndexLow;
615 *dev_ret = file_info.dwVolumeSerialNumber;
622 /* Reparse point fixup status code */
624 /* Reparse point corresponded to an absolute symbolic link or junction
625 * point that pointed outside the directory tree being captured, and
626 * therefore was excluded. */
629 /* Reparse point was not fixed as it was either a relative symbolic
630 * link, a mount point, or something else we could not understand. */
633 /* Reparse point corresponded to an absolute symbolic link or junction
634 * point that pointed inside the directory tree being captured, where
635 * the target was specified by a "full" \??\ prefixed path, and
636 * therefore was fixed to be relative to the root of the directory tree
638 RP_FIXED_FULLPATH = 0x2,
640 /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
641 * have the \??\ prefix. It may have begun with a drive letter though.
643 RP_FIXED_ABSPATH = 0x4,
645 /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
646 RP_FIXED = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
649 /* Given the "substitute name" target of a Windows reparse point, try doing a
650 * fixup where we change it to be absolute relative to the root of the directory
651 * tree being captured.
653 * Note that this is only executed when WIMLIB_ADD_IMAGE_FLAG_RPFIX has been
656 * @capture_root_ino and @capture_root_dev indicate the inode number and device
657 * of the root of the directory tree being captured. They are meant to identify
658 * this directory (as an alternative to its actual path, which could potentially
659 * be reached via multiple destinations due to other symbolic links). This may
660 * not work properly on FAT, which doesn't seem to supply proper inode numbers
661 * or file IDs. However, FAT doesn't support reparse points so this function
662 * wouldn't even be called anyway. */
663 static enum rp_status
664 win32_maybe_rpfix_target(wchar_t *target, size_t *target_nchars_p,
665 u64 capture_root_ino, u64 capture_root_dev)
667 size_t target_nchars= *target_nchars_p;
668 size_t stripped_chars;
669 wchar_t *orig_target;
671 if (target_nchars == 0)
672 /* Invalid reparse point (empty target) */
675 if (target[0] == L'\\') {
676 if (target_nchars >= 2 && target[1] == L'\\') {
677 /* Probably a volume. Can't do anything with it. */
678 DEBUG("Not fixing target (probably a volume)");
680 } else if (target_nchars >= 7 &&
688 DEBUG("Full style path");
689 /* Full \??\x:\ style path (may be junction or symlink)
693 DEBUG("Absolute target without drive letter");
694 /* Absolute target, without drive letter */
697 } else if (target_nchars >= 3 &&
698 target[0] != L'\0' &&
702 DEBUG("Absolute target with drive letter");
703 /* Absolute target, with drive letter */
706 DEBUG("Relative symlink or other link");
707 /* Relative symlink or other unexpected format */
710 target[target_nchars] = L'\0';
711 orig_target = target;
712 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_try_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;
798 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
799 struct add_image_params *params,
800 void *reparse_data, size_t *reparse_data_len_ret)
804 enum rp_status status;
806 DEBUG("Loading reparse data from \"%ls\"", path);
807 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
808 NULL, /* "Not used with this operation; set to NULL" */
809 0, /* "Not used with this operation; set to 0" */
810 reparse_data, /* "A pointer to a buffer that
811 receives the reparse point data */
812 REPARSE_POINT_MAX_SIZE, /* "The size of the output
817 DWORD err = GetLastError();
818 ERROR("Failed to get reparse data of \"%ls\"", path);
820 return -WIMLIB_ERR_READ;
822 if (bytesReturned < 8) {
823 ERROR("Reparse data on \"%ls\" is invalid", path);
824 return -WIMLIB_ERR_READ;
827 reparse_tag = le32_to_cpu(*(u32*)reparse_data);
828 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX &&
829 (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
830 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
832 /* Try doing reparse point fixup */
833 status = win32_try_capture_rpfix(reparse_data,
835 params->capture_root_ino,
836 params->capture_root_dev);
838 status = RP_NOT_FIXED;
840 *reparse_data_len_ret = bytesReturned;
844 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
845 * stream); calculates its SHA1 message digest and either creates a `struct
846 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
847 * wim_lookup_table_entry' for an identical stream.
849 * @path: Path to the file (UTF-16LE).
851 * @path_num_chars: Number of 2-byte characters in @path.
853 * @inode: WIM inode to save the stream into.
855 * @lookup_table: Stream lookup table for the WIM.
857 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
860 * Returns 0 on success; nonzero on failure.
863 win32_capture_stream(const wchar_t *path,
864 size_t path_num_chars,
865 struct wim_inode *inode,
866 struct wim_lookup_table *lookup_table,
867 WIN32_FIND_STREAM_DATA *dat)
869 struct wim_ads_entry *ads_entry;
870 struct wim_lookup_table_entry *lte;
872 wchar_t *stream_name, *colon;
873 size_t stream_name_nchars;
874 bool is_named_stream;
877 size_t spath_buf_nbytes;
878 const wchar_t *relpath_prefix;
879 const wchar_t *colonchar;
881 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
883 /* The stream name should be returned as :NAME:TYPE */
884 stream_name = dat->cStreamName;
885 if (*stream_name != L':')
886 goto out_invalid_stream_name;
888 colon = wcschr(stream_name, L':');
890 goto out_invalid_stream_name;
892 if (wcscmp(colon + 1, L"$DATA")) {
893 /* Not a DATA stream */
900 stream_name_nchars = colon - stream_name;
901 is_named_stream = (stream_name_nchars != 0);
903 if (is_named_stream) {
904 /* Allocate an ADS entry for the named stream. */
905 ads_entry = inode_add_ads_utf16le(inode, stream_name,
906 stream_name_nchars * sizeof(wchar_t));
908 ret = WIMLIB_ERR_NOMEM;
913 /* If zero length stream, no lookup table entry needed. */
914 if ((u64)dat->StreamSize.QuadPart == 0) {
919 /* Create a UTF-16LE string @spath that gives the filename, then a
920 * colon, then the stream name. Or, if it's an unnamed stream, just the
921 * filename. It is MALLOC()'ed so that it can be saved in the
922 * wim_lookup_table_entry if needed.
924 * As yet another special case, relative paths need to be changed to
925 * begin with an explicit "./" so that, for example, a file t:ads, where
926 * :ads is the part we added, is not interpreted as a file on the t:
928 spath_nchars = path_num_chars;
929 relpath_prefix = L"";
931 if (is_named_stream) {
932 spath_nchars += 1 + stream_name_nchars;
934 if (path_num_chars == 1 &&
939 relpath_prefix = L"./";
943 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
944 spath = MALLOC(spath_buf_nbytes);
946 swprintf(spath, L"%ls%ls%ls%ls",
947 relpath_prefix, path, colonchar, stream_name);
949 /* Make a new wim_lookup_table_entry */
950 lte = new_lookup_table_entry();
952 ret = WIMLIB_ERR_NOMEM;
955 lte->file_on_disk = spath;
957 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream)
958 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
960 lte->resource_location = RESOURCE_WIN32;
961 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
964 if (is_named_stream) {
965 stream_id = ads_entry->stream_id;
966 ads_entry->lte = lte;
971 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
977 out_invalid_stream_name:
978 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
979 ret = WIMLIB_ERR_READ;
983 /* Scans a Win32 file for unnamed and named data streams (not reparse point
986 * @path: Path to the file (UTF-16LE).
988 * @path_num_chars: Number of 2-byte characters in @path.
990 * @inode: WIM inode to save the stream into.
992 * @lookup_table: Stream lookup table for the WIM.
994 * @file_size: Size of unnamed data stream. (Used only if alternate
995 * data streams API appears to be unavailable.)
997 * @vol_flags: Flags that specify features of the volume being
1000 * Returns 0 on success; nonzero on failure.
1003 win32_capture_streams(const wchar_t *path,
1004 size_t path_num_chars,
1005 struct wim_inode *inode,
1006 struct wim_lookup_table *lookup_table,
1010 WIN32_FIND_STREAM_DATA dat;
1015 DEBUG("Capturing streams from \"%ls\"", path);
1017 if (win32func_FindFirstStreamW == NULL ||
1018 !(vol_flags & FILE_NAMED_STREAMS))
1021 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1022 if (hFind == INVALID_HANDLE_VALUE) {
1023 err = GetLastError();
1024 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1027 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1028 * points and directories */
1029 if ((inode->i_attributes &
1030 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1031 && err == ERROR_HANDLE_EOF)
1033 DEBUG("ERROR_HANDLE_EOF (ok)");
1036 if (err == ERROR_ACCESS_DENIED) {
1037 ERROR("Failed to look up data streams "
1038 "of \"%ls\": Access denied!\n%ls",
1039 path, capture_access_denied_msg);
1040 return WIMLIB_ERR_READ;
1042 ERROR("Failed to look up data streams "
1043 "of \"%ls\"", path);
1045 return WIMLIB_ERR_READ;
1050 ret = win32_capture_stream(path,
1052 inode, lookup_table,
1055 goto out_find_close;
1056 } while (win32func_FindNextStreamW(hFind, &dat));
1057 err = GetLastError();
1058 if (err != ERROR_HANDLE_EOF) {
1059 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
1061 ret = WIMLIB_ERR_READ;
1067 /* FindFirstStreamW() API is not available, or the volume does not
1068 * support named streams. Only capture the unnamed data stream. */
1069 DEBUG("Only capturing unnamed data stream");
1070 if (inode->i_attributes &
1071 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1075 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
1076 * stream to reduce the code to a call to the
1077 * already-implemented win32_capture_stream() */
1078 wcscpy(dat.cStreamName, L"::$DATA");
1079 dat.StreamSize.QuadPart = file_size;
1080 ret = win32_capture_stream(path,
1082 inode, lookup_table,
1089 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1091 size_t path_num_chars,
1092 struct add_image_params *params,
1093 struct win32_capture_state *state,
1096 struct wim_dentry *root = NULL;
1097 struct wim_inode *inode;
1102 size_t reparse_data_len;
1105 if (exclude_path(path, path_num_chars, params->config, true)) {
1106 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
1107 ERROR("Cannot exclude the root directory from capture");
1108 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1111 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
1112 && params->progress_func)
1114 union wimlib_progress_info info;
1115 info.scan.cur_path = path;
1116 info.scan.excluded = true;
1117 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1123 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
1124 && params->progress_func)
1126 union wimlib_progress_info info;
1127 info.scan.cur_path = path;
1128 info.scan.excluded = false;
1129 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1132 HANDLE hFile = win32_open_existing_file(path,
1133 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1134 if (hFile == INVALID_HANDLE_VALUE) {
1135 err = GetLastError();
1136 ERROR("Win32 API: Failed to open \"%ls\"", path);
1138 ret = WIMLIB_ERR_OPEN;
1142 BY_HANDLE_FILE_INFORMATION file_info;
1143 if (!GetFileInformationByHandle(hFile, &file_info)) {
1144 err = GetLastError();
1145 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1148 ret = WIMLIB_ERR_STAT;
1149 goto out_close_handle;
1152 if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1153 reparse_data = alloca(REPARSE_POINT_MAX_SIZE);
1154 ret = win32_get_reparse_data(hFile, path, params,
1155 reparse_data, &reparse_data_len);
1157 /* WIMLIB_ERR_* (inverted) */
1159 goto out_close_handle;
1160 } else if (ret & RP_FIXED) {
1162 } else if (ret == RP_EXCLUDED) {
1164 goto out_close_handle;
1170 /* Create a WIM dentry with an associated inode, which may be shared.
1172 * However, we need to explicitly check for directories and files with
1173 * only 1 link and refuse to hard link them. This is because Windows
1174 * has a bug where it can return duplicate File IDs for files and
1175 * directories on the FAT filesystem. */
1176 ret = inode_table_new_dentry(params->inode_table,
1177 path_basename_with_len(path, path_num_chars),
1178 ((u64)file_info.nFileIndexHigh << 32) |
1179 (u64)file_info.nFileIndexLow,
1180 file_info.dwVolumeSerialNumber,
1181 (file_info.nNumberOfLinks <= 1 ||
1182 (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1185 goto out_close_handle;
1187 ret = win32_get_short_name(root, path);
1189 goto out_close_handle;
1191 inode = root->d_inode;
1193 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1194 goto out_close_handle;
1196 inode->i_attributes = file_info.dwFileAttributes;
1197 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1198 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1199 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1200 inode->i_resolved = 1;
1202 params->add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
1204 if (!(params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)
1205 && (vol_flags & FILE_PERSISTENT_ACLS))
1207 ret = win32_get_security_descriptor(root, params->sd_set,
1209 params->add_image_flags);
1211 goto out_close_handle;
1214 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1215 (u64)file_info.nFileSizeLow;
1217 /* Capture the unnamed data stream (only should be present for regular
1218 * files) and any alternate data streams. */
1219 ret = win32_capture_streams(path,
1222 params->lookup_table,
1226 goto out_close_handle;
1228 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1229 /* Reparse point: set the reparse data (which we read already)
1231 inode->i_not_rpfixed = not_rpfixed;
1232 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_data);
1233 ret = inode_set_unnamed_stream(inode, reparse_data + 8,
1234 reparse_data_len - 8,
1235 params->lookup_table);
1236 } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1237 /* Directory (not a reparse point) --- recurse to children */
1238 ret = win32_recurse_directory(root,
1251 free_dentry_tree(root, params->lookup_table);
1256 win32_do_capture_warnings(const struct win32_capture_state *state,
1257 int add_image_flags)
1259 if (state->num_get_sacl_priv_notheld == 0 &&
1260 state->num_get_sd_access_denied == 0)
1264 WARNING("Built dentry tree successfully, but with the following problem(s):");
1265 if (state->num_get_sacl_priv_notheld != 0) {
1266 WARNING("Could not capture SACL (System Access Control List)\n"
1267 " on %lu files or directories.",
1268 state->num_get_sacl_priv_notheld);
1270 if (state->num_get_sd_access_denied != 0) {
1271 WARNING("Could not capture security descriptor at all\n"
1272 " on %lu files or directories.",
1273 state->num_get_sd_access_denied);
1276 "Try running the program as the Administrator to make sure all the\n"
1277 " desired metadata has been captured exactly. However, if you\n"
1278 " do not care about capturing security descriptors correctly, then\n"
1279 " nothing more needs to be done%ls\n",
1280 (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
1281 L", although you might consider\n"
1282 " passing the --no-acls flag to `wimlib-imagex capture' or\n"
1283 " `wimlib-imagex append' to explicitly capture no security\n"
1287 /* Win32 version of capturing a directory tree */
1289 win32_build_dentry_tree(struct wim_dentry **root_ret,
1290 const wchar_t *root_disk_path,
1291 struct add_image_params *params)
1296 struct win32_capture_state state;
1300 path_nchars = wcslen(root_disk_path);
1301 if (path_nchars > 32767)
1302 return WIMLIB_ERR_INVALID_PARAM;
1304 ret = win32_get_file_and_vol_ids(root_disk_path,
1305 ¶ms->capture_root_ino,
1306 ¶ms->capture_root_dev);
1310 win32_get_vol_flags(root_disk_path, &vol_flags);
1312 /* There is no check for overflow later when this buffer is being used!
1313 * But the max path length on NTFS is 32767 characters, and paths need
1314 * to be written specially to even go past 260 characters, so we should
1315 * be okay with 32770 characters. */
1316 path = MALLOC(32770 * sizeof(wchar_t));
1318 return WIMLIB_ERR_NOMEM;
1320 wmemcpy(path, root_disk_path, path_nchars + 1);
1322 memset(&state, 0, sizeof(state));
1323 ret = win32_build_dentry_tree_recursive(root_ret, path,
1324 path_nchars, params,
1328 win32_do_capture_warnings(&state, params->add_image_flags);
1333 win32_set_reparse_data(HANDLE h,
1335 const struct wim_lookup_table_entry *lte,
1336 const wchar_t *path)
1343 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
1347 len = wim_resource_size(lte);
1348 if (len > 16 * 1024 - 8) {
1349 WARNING("\"%ls\": reparse data too long!", path);
1353 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
1354 * leave 8 bytes of space for them at the beginning of the buffer, then
1355 * set them manually. */
1356 buf = alloca(len + 8);
1357 ret = read_full_resource_into_buf(lte, buf + 8, false);
1360 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
1361 *(u16*)(buf + 4) = cpu_to_le16(len);
1362 *(u16*)(buf + 6) = 0;
1364 /* Set the reparse data on the open file using the
1365 * FSCTL_SET_REPARSE_POINT ioctl.
1367 * There are contradictions in Microsoft's documentation for this:
1369 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1370 * lpOverlapped is ignored."
1372 * --- So setting lpOverlapped to NULL is okay since it's ignored.
1374 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1375 * operation returns no output data and lpOutBuffer is NULL,
1376 * DeviceIoControl makes use of lpBytesReturned. After such an
1377 * operation, the value of lpBytesReturned is meaningless."
1379 * --- So lpOverlapped not really ignored, as it affects another
1380 * parameter. This is the actual behavior: lpBytesReturned must be
1381 * specified, even though lpBytesReturned is documented as:
1383 * "Not used with this operation; set to NULL."
1385 DWORD bytesReturned;
1386 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
1388 &bytesReturned /* lpBytesReturned */,
1389 NULL /* lpOverlapped */))
1391 DWORD err = GetLastError();
1392 ERROR("Failed to set reparse data on \"%ls\"", path);
1394 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1395 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1396 else if (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1397 reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT)
1398 return WIMLIB_ERR_LINK;
1400 return WIMLIB_ERR_WRITE;
1406 win32_set_compression_state(HANDLE hFile, USHORT format, const wchar_t *path)
1408 DWORD bytesReturned = 0;
1409 if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1410 &format, sizeof(USHORT),
1412 &bytesReturned, NULL))
1414 /* Could be a warning only, but we only call this if the volume
1415 * supports compression. So I'm calling this an error. */
1416 DWORD err = GetLastError();
1417 ERROR("Failed to set compression flag on \"%ls\"", path);
1419 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1420 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1422 return WIMLIB_ERR_WRITE;
1428 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1430 DWORD bytesReturned = 0;
1431 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1434 &bytesReturned, NULL))
1436 /* Could be a warning only, but we only call this if the volume
1437 * supports sparse files. So I'm calling this an error. */
1438 DWORD err = GetLastError();
1439 WARNING("Failed to set sparse flag on \"%ls\"", path);
1441 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1442 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1444 return WIMLIB_ERR_WRITE;
1450 * Sets the security descriptor on an extracted file.
1453 win32_set_security_data(const struct wim_inode *inode,
1455 const wchar_t *path,
1456 struct apply_args *args)
1458 PSECURITY_DESCRIPTOR descriptor;
1461 const struct wim_security_data *sd;
1463 SECURITY_INFORMATION securityInformation = 0;
1470 BOOL owner_defaulted;
1471 BOOL group_defaulted;
1473 BOOL dacl_defaulted;
1475 BOOL sacl_defaulted;
1477 sd = wim_const_security_data(args->w);
1478 descriptor = sd->descriptors[inode->i_security_id];
1480 GetSecurityDescriptorOwner(descriptor, &owner, &owner_defaulted);
1482 securityInformation |= OWNER_SECURITY_INFORMATION;
1484 GetSecurityDescriptorGroup(descriptor, &group, &group_defaulted);
1486 securityInformation |= GROUP_SECURITY_INFORMATION;
1488 GetSecurityDescriptorDacl(descriptor, &dacl_present,
1489 &dacl, &dacl_defaulted);
1491 securityInformation |= DACL_SECURITY_INFORMATION;
1493 GetSecurityDescriptorSacl(descriptor, &sacl_present,
1494 &sacl, &sacl_defaulted);
1496 securityInformation |= SACL_SECURITY_INFORMATION;
1499 if (securityInformation == 0)
1501 if (SetSecurityInfo(hFile, SE_FILE_OBJECT,
1502 securityInformation, owner, group, dacl, sacl))
1504 err = GetLastError();
1505 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1508 case ERROR_PRIVILEGE_NOT_HELD:
1509 if (securityInformation & SACL_SECURITY_INFORMATION) {
1510 n = args->num_set_sacl_priv_notheld++;
1511 securityInformation &= ~SACL_SECURITY_INFORMATION;
1513 if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1515 "We don't have enough privileges to set the full security\n"
1516 " descriptor on \"%ls\"!\n", path);
1517 if (args->num_set_sd_access_denied +
1518 args->num_set_sacl_priv_notheld == 1)
1520 WARNING("%ls", apply_access_denied_msg);
1522 WARNING("Re-trying with SACL omitted.\n", path);
1523 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1525 "Suppressing further 'privileges not held' error messages when setting\n"
1526 " security descriptors.");
1531 case ERROR_INVALID_OWNER:
1532 case ERROR_ACCESS_DENIED:
1533 n = args->num_set_sd_access_denied++;
1534 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1535 WARNING("Failed to set security descriptor on \"%ls\": "
1536 "Access denied!\n", path);
1537 if (args->num_set_sd_access_denied +
1538 args->num_set_sacl_priv_notheld == 1)
1540 WARNING("%ls", apply_access_denied_msg);
1542 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1544 "Suppressing further access denied error messages when setting\n"
1545 " security descriptors");
1550 ERROR("Failed to set security descriptor on \"%ls\"", path);
1552 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1553 return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1555 return WIMLIB_ERR_WRITE;
1561 win32_extract_chunk(const void *buf, size_t len, void *arg)
1563 HANDLE hStream = arg;
1565 DWORD nbytes_written;
1566 wimlib_assert(len <= 0xffffffff);
1568 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1569 nbytes_written != len)
1571 DWORD err = GetLastError();
1572 ERROR("WriteFile(): write error");
1574 return WIMLIB_ERR_WRITE;
1580 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1582 return extract_wim_resource(lte, wim_resource_size(lte),
1583 win32_extract_chunk, hStream);
1587 do_win32_extract_encrypted_stream(const wchar_t *path,
1588 const struct wim_lookup_table_entry *lte)
1590 ERROR("Extracting encryted streams not implemented");
1591 return WIMLIB_ERR_INVALID_PARAM;
1595 path_is_root_of_drive(const wchar_t *path)
1600 if (*path != L'/' && *path != L'\\') {
1601 if (*(path + 1) == L':')
1606 while (*path == L'/' || *path == L'\\')
1608 return (*path == L'\0');
1612 win32_get_create_flags_and_attributes(DWORD i_attributes)
1617 * Some attributes cannot be set by passing them to CreateFile(). In
1620 * FILE_ATTRIBUTE_DIRECTORY:
1621 * CreateDirectory() must be called instead of CreateFile().
1623 * FILE_ATTRIBUTE_SPARSE_FILE:
1625 * See: win32_set_sparse().
1627 * FILE_ATTRIBUTE_COMPRESSED:
1628 * Not clear from the documentation, but apparently this needs an
1630 * See: win32_set_compressed().
1632 * FILE_ATTRIBUTE_REPARSE_POINT:
1633 * Needs an ioctl, with the reparse data specified.
1634 * See: win32_set_reparse_data().
1636 * In addition, clear any file flags in the attributes that we don't
1637 * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1638 * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1640 attributes = i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1641 FILE_ATTRIBUTE_COMPRESSED |
1642 FILE_ATTRIBUTE_REPARSE_POINT |
1643 FILE_ATTRIBUTE_DIRECTORY |
1644 FILE_FLAG_DELETE_ON_CLOSE |
1645 FILE_FLAG_NO_BUFFERING |
1646 FILE_FLAG_OPEN_NO_RECALL |
1647 FILE_FLAG_OVERLAPPED |
1648 FILE_FLAG_RANDOM_ACCESS |
1649 /*FILE_FLAG_SESSION_AWARE |*/
1650 FILE_FLAG_SEQUENTIAL_SCAN |
1651 FILE_FLAG_WRITE_THROUGH);
1653 FILE_FLAG_OPEN_REPARSE_POINT |
1654 FILE_FLAG_BACKUP_SEMANTICS;
1657 /* Set compression or sparse attributes, and reparse data, if supported by the
1660 win32_set_special_attributes(HANDLE hFile, const struct wim_inode *inode,
1661 struct wim_lookup_table_entry *unnamed_stream_lte,
1662 const wchar_t *path, unsigned vol_flags)
1666 /* Encrypted files cannot be [de]compressed. */
1667 if (!(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1668 if (vol_flags & FILE_FILE_COMPRESSION) {
1670 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1671 format = COMPRESSION_FORMAT_DEFAULT;
1672 DEBUG("Setting compression flag on \"%ls\"", path);
1674 format = COMPRESSION_FORMAT_NONE;
1675 DEBUG("Clearing compression flag on \"%ls\"", path);
1677 ret = win32_set_compression_state(hFile, format, path);
1681 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1682 DEBUG("Cannot set compression attribute on \"%ls\": "
1683 "volume does not support transparent compression",
1689 if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1690 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1691 DEBUG("Setting sparse flag on \"%ls\"", path);
1692 ret = win32_set_sparse(hFile, path);
1696 DEBUG("Cannot set sparse attribute on \"%ls\": "
1697 "volume does not support sparse files",
1702 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1703 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
1704 DEBUG("Setting reparse data on \"%ls\"", path);
1705 ret = win32_set_reparse_data(hFile, inode->i_reparse_tag,
1706 unnamed_stream_lte, path);
1710 DEBUG("Cannot set reparse data on \"%ls\": volume "
1711 "does not support reparse points", path);
1718 win32_extract_stream(const struct wim_inode *inode,
1719 const wchar_t *path,
1720 const wchar_t *stream_name_utf16,
1721 struct wim_lookup_table_entry *lte,
1722 struct apply_args *args)
1724 wchar_t *stream_path;
1728 DWORD creationDisposition = CREATE_ALWAYS;
1729 DWORD requestedAccess;
1731 if (stream_name_utf16) {
1732 /* Named stream. Create a buffer that contains the UTF-16LE
1733 * string [./]path:stream_name_utf16. This is needed to
1734 * create and open the stream using CreateFileW(). I'm not
1735 * aware of any other APIs to do this. Note: the '$DATA' suffix
1736 * seems to be unneeded. Additional note: a "./" prefix needs
1737 * to be added when the path is not absolute to avoid ambiguity
1738 * with drive letters. */
1739 size_t stream_path_nchars;
1741 size_t stream_name_nchars;
1742 const wchar_t *prefix;
1744 path_nchars = wcslen(path);
1745 stream_name_nchars = wcslen(stream_name_utf16);
1746 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1747 if (path[0] != cpu_to_le16(L'\0') &&
1748 path[0] != cpu_to_le16(L'/') &&
1749 path[0] != cpu_to_le16(L'\\') &&
1750 path[1] != cpu_to_le16(L':'))
1753 stream_path_nchars += 2;
1757 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1758 swprintf(stream_path, L"%ls%ls:%ls",
1759 prefix, path, stream_name_utf16);
1761 /* Unnamed stream; its path is just the path to the file itself.
1763 stream_path = (wchar_t*)path;
1765 /* Directories must be created with CreateDirectoryW(). Then
1766 * the call to CreateFileW() will merely open the directory that
1767 * was already created rather than creating a new file. */
1768 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1769 if (!CreateDirectoryW(stream_path, NULL)) {
1770 err = GetLastError();
1772 case ERROR_ALREADY_EXISTS:
1774 case ERROR_ACCESS_DENIED:
1775 if (path_is_root_of_drive(path))
1779 ERROR("Failed to create directory \"%ls\"",
1782 ret = WIMLIB_ERR_MKDIR;
1786 DEBUG("Created directory \"%ls\"", stream_path);
1787 creationDisposition = OPEN_EXISTING;
1791 DEBUG("Opening \"%ls\"", stream_path);
1792 requestedAccess = GENERIC_READ | GENERIC_WRITE |
1793 ACCESS_SYSTEM_SECURITY;
1795 h = CreateFileW(stream_path,
1799 creationDisposition,
1800 win32_get_create_flags_and_attributes(inode->i_attributes),
1802 if (h == INVALID_HANDLE_VALUE) {
1803 err = GetLastError();
1804 if (err == ERROR_PRIVILEGE_NOT_HELD &&
1805 (requestedAccess & ACCESS_SYSTEM_SECURITY))
1807 requestedAccess &= ~ACCESS_SYSTEM_SECURITY;
1808 goto try_open_again;
1810 ERROR("Failed to create \"%ls\"", stream_path);
1812 ret = WIMLIB_ERR_OPEN;
1816 if (stream_name_utf16 == NULL) {
1817 if (inode->i_security_id >= 0 &&
1818 !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
1819 && (args->vol_flags & FILE_PERSISTENT_ACLS))
1821 ret = win32_set_security_data(inode, h, path, args);
1823 goto fail_close_handle;
1826 ret = win32_set_special_attributes(h, inode, lte, path,
1829 goto fail_close_handle;
1832 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1834 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1835 stream_path, wim_resource_size(lte));
1836 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED
1837 && stream_name_utf16 == NULL
1838 && (args->vol_flags & FILE_SUPPORTS_ENCRYPTION))
1840 ret = do_win32_extract_encrypted_stream(stream_path,
1843 ret = do_win32_extract_stream(h, lte);
1846 goto fail_close_handle;
1850 DEBUG("Closing \"%ls\"", stream_path);
1851 if (!CloseHandle(h)) {
1852 err = GetLastError();
1853 ERROR("Failed to close \"%ls\"", stream_path);
1855 ret = WIMLIB_ERR_WRITE;
1863 ERROR("Error extracting %ls", stream_path);
1869 * Creates a file, directory, or reparse point and extracts all streams to it
1870 * (unnamed data stream and/or reparse point stream, plus any alternate data
1873 * @inode: WIM inode for this file or directory.
1874 * @path: UTF-16LE external path to extract the inode to.
1875 * @args: Additional extraction context.
1877 * Returns 0 on success; nonzero on failure.
1880 win32_extract_streams(const struct wim_inode *inode,
1881 const wchar_t *path, struct apply_args *args)
1883 struct wim_lookup_table_entry *unnamed_lte;
1886 /* Extract the unnamed stream. */
1888 unnamed_lte = inode_unnamed_lte_resolved(inode);
1889 ret = win32_extract_stream(inode, path, NULL, unnamed_lte, args);
1892 if (unnamed_lte && inode->i_extracted_file == NULL)
1894 args->progress.extract.completed_bytes +=
1895 wim_resource_size(unnamed_lte);
1898 /* Extract any named streams, if supported by the volume. */
1900 if (!(args->vol_flags & FILE_NAMED_STREAMS))
1902 for (u16 i = 0; i < inode->i_num_ads; i++) {
1903 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1905 /* Skip the unnamed stream if it's in the ADS entries (we
1906 * already extracted it...) */
1907 if (ads_entry->stream_name_nbytes == 0)
1910 /* Skip special UNIX data entries (see documentation for
1911 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1912 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1913 && !memcmp(ads_entry->stream_name,
1914 WIMLIB_UNIX_DATA_TAG_UTF16LE,
1915 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1918 /* Extract the named stream */
1919 ret = win32_extract_stream(inode,
1921 ads_entry->stream_name,
1927 /* Tally the bytes extracted, unless this was supposed to be a
1928 * hard link and we are extracting the data again only as a
1930 if (ads_entry->lte && inode->i_extracted_file == NULL)
1932 args->progress.extract.completed_bytes +=
1933 wim_resource_size(ads_entry->lte);
1941 win32_check_vol_flags(const wchar_t *output_path, struct apply_args *args)
1943 if (args->have_vol_flags)
1946 win32_get_vol_flags(output_path, &args->vol_flags);
1947 args->have_vol_flags = true;
1948 /* Warn the user about data that may not be extracted. */
1949 if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
1950 WARNING("Volume does not support sparse files!\n"
1951 " Sparse files will be extracted as non-sparse.");
1952 if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1953 WARNING("Volume does not support reparse points!\n"
1954 " Reparse point data will not be extracted.");
1955 if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
1956 WARNING("Volume does not support named data streams!\n"
1957 " Named data streams will not be extracted.");
1959 if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
1960 WARNING("Volume does not support encryption!\n"
1961 " Encrypted files will be extracted as raw data.");
1963 if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
1964 WARNING("Volume does not support transparent compression!\n"
1965 " Compressed files will be extracted as non-compressed.");
1967 if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
1968 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
1969 ERROR("Strict ACLs requested, but the volume does not "
1971 return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
1973 WARNING("Volume does not support persistent ACLS!\n"
1974 " File permissions will not be extracted.");
1981 win32_try_hard_link(const wchar_t *output_path, const struct wim_inode *inode,
1982 struct apply_args *args)
1986 /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
1987 * but it's only available on Windows 7 and later. So no use
1988 * even checking it, really. Instead, CreateHardLinkW() will
1989 * apparently return ERROR_INVALID_FUNCTION if the volume does
1990 * not support hard links. */
1991 DEBUG("Creating hard link \"%ls => %ls\"",
1992 output_path, inode->i_extracted_file);
1993 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
1996 err = GetLastError();
1997 if (err != ERROR_INVALID_FUNCTION) {
1998 ERROR("Can't create hard link \"%ls => %ls\"",
1999 output_path, inode->i_extracted_file);
2001 return WIMLIB_ERR_LINK;
2003 args->num_hard_links_failed++;
2004 if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
2005 WARNING("Can't create hard link \"%ls => %ls\":\n"
2006 " Volume does not support hard links!\n"
2007 " Falling back to extracting a copy of the file.",
2008 output_path, inode->i_extracted_file);
2009 } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
2010 WARNING("Suppressing further hard linking warnings...");
2016 /* Extract a file, directory, reparse point, or hard link to an
2017 * already-extracted file using the Win32 API */
2019 win32_do_apply_dentry(const wchar_t *output_path,
2020 size_t output_path_num_chars,
2021 struct wim_dentry *dentry,
2022 struct apply_args *args)
2025 struct wim_inode *inode = dentry->d_inode;
2027 ret = win32_check_vol_flags(output_path, args);
2030 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
2031 /* Linked file, with another name already extracted. Create a
2033 ret = win32_try_hard_link(output_path, inode, args);
2036 /* Falling back to extracting copy of file */
2039 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2040 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2042 WARNING("Skipping extraction of reparse point \"%ls\":\n"
2043 " Not supported by destination filesystem",
2045 struct wim_lookup_table_entry *lte;
2046 lte = inode_unnamed_lte_resolved(inode);
2048 args->progress.extract.completed_bytes += wim_resource_size(lte);
2052 /* Create the file, directory, or reparse point, and extract the
2054 ret = win32_extract_streams(inode, output_path, args);
2058 if (inode->i_nlink > 1) {
2059 /* Save extracted path for a later call to
2060 * CreateHardLinkW() if this inode has multiple links.
2062 inode->i_extracted_file = WSTRDUP(output_path);
2063 if (!inode->i_extracted_file)
2064 ret = WIMLIB_ERR_NOMEM;
2069 /* Set timestamps on an extracted file using the Win32 API */
2071 win32_do_apply_dentry_timestamps(const wchar_t *path,
2072 size_t path_num_chars,
2073 const struct wim_dentry *dentry,
2074 const struct apply_args *args)
2078 const struct wim_inode *inode = dentry->d_inode;
2080 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2081 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2083 /* Skip reparse points not extracted */
2087 /* Windows doesn't let you change the timestamps of the root directory
2088 * (at least on FAT, which is dumb but expected since FAT doesn't store
2089 * any metadata about the root directory...) */
2090 if (path_is_root_of_drive(path))
2093 DEBUG("Opening \"%ls\" to set timestamps", path);
2094 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
2095 if (h == INVALID_HANDLE_VALUE) {
2096 err = GetLastError();
2100 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
2101 .dwHighDateTime = inode->i_creation_time >> 32};
2102 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
2103 .dwHighDateTime = inode->i_last_access_time >> 32};
2104 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
2105 .dwHighDateTime = inode->i_last_write_time >> 32};
2107 DEBUG("Calling SetFileTime() on \"%ls\"", path);
2108 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
2109 err = GetLastError();
2113 DEBUG("Closing \"%ls\"", path);
2114 if (!CloseHandle(h)) {
2115 err = GetLastError();
2120 /* Only warn if setting timestamps failed; still return 0. */
2121 WARNING("Can't set timestamps on \"%ls\"", path);
2127 /* Replacement for POSIX fsync() */
2134 h = (HANDLE)_get_osfhandle(fd);
2135 if (h == INVALID_HANDLE_VALUE) {
2136 err = GetLastError();
2137 ERROR("Could not get Windows handle for file descriptor");
2142 if (!FlushFileBuffers(h)) {
2143 err = GetLastError();
2144 ERROR("Could not flush file buffers to disk");
2152 /* Use the Win32 API to get the number of processors */
2154 win32_get_number_of_processors()
2156 SYSTEM_INFO sysinfo;
2157 GetSystemInfo(&sysinfo);
2158 return sysinfo.dwNumberOfProcessors;
2161 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
2162 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
2163 * really does the right thing under all circumstances. */
2165 realpath(const wchar_t *path, wchar_t *resolved_path)
2168 wimlib_assert(resolved_path == NULL);
2171 ret = GetFullPathNameW(path, 0, NULL, NULL);
2173 err = GetLastError();
2177 resolved_path = TMALLOC(ret);
2180 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2182 err = GetLastError();
2183 free(resolved_path);
2184 resolved_path = NULL;
2192 return resolved_path;
2195 /* rename() on Windows fails if the destination file exists. And we need to
2196 * make it work on wide characters. Fix it. */
2198 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2200 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2203 /* As usual, the possible error values are not documented */
2204 DWORD err = GetLastError();
2205 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2213 /* Replacement for POSIX fnmatch() (partial functionality only) */
2215 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2217 if (PathMatchSpecW(string, pattern))
2223 /* truncate() replacement */
2225 win32_truncate_replacement(const wchar_t *path, off_t size)
2227 DWORD err = NO_ERROR;
2228 LARGE_INTEGER liOffset;
2230 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2231 if (h == INVALID_HANDLE_VALUE)
2234 liOffset.QuadPart = size;
2235 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2236 goto fail_close_handle;
2238 if (!SetEndOfFile(h))
2239 goto fail_close_handle;
2244 err = GetLastError();
2247 if (err == NO_ERROR)
2248 err = GetLastError();
2249 ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2256 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2257 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2258 * linked in by Visual Studio...?). */
2260 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2262 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2264 pthread_mutex_lock(&strerror_lock);
2265 mbstowcs(buf, strerror(errnum), buflen);
2266 buf[buflen - 1] = '\0';
2267 pthread_mutex_unlock(&strerror_lock);
2271 #endif /* __WIN32__ */