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;
624 RP_FIXED_FULLPATH = 0x2,
625 RP_FIXED_ABSPATH = 0x4,
626 RP_FIXED = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
629 static enum rp_status
630 win32_maybe_rpfix_target(wchar_t *target, size_t *target_nchars_p,
631 u64 capture_root_ino, u64 capture_root_dev)
633 size_t target_nchars= *target_nchars_p;
634 size_t stripped_chars;
635 wchar_t *orig_target;
637 if (target_nchars == 0)
640 if (target[0] == L'\\') {
641 if (target_nchars >= 2 && target[1] == L'\\') {
642 /* Probaby a volume. Can't do anything with it. */
643 DEBUG("Not fixing target (probably a volume)");
645 } else if (target_nchars >= 7 &&
653 DEBUG("Full style path");
654 /* Full \??\x:\ style path (may be junction or symlink)
658 DEBUG("Absolute target without drive letter");
659 /* Absolute target, without drive letter */
662 } else if (target_nchars >= 3 &&
663 target[0] != L'\0' &&
667 DEBUG("Absolute target with drive letter");
668 /* Absolute target, with drive letter */
671 DEBUG("Relative symlink or other link");
672 /* Relative symlink or other unexpected format */
675 target[target_nchars] = L'\0';
676 orig_target = target;
677 target = fixup_symlink(target + stripped_chars, capture_root_ino, capture_root_dev);
679 target_nchars = wcslen(target);
680 wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
681 *target_nchars_p = target_nchars + stripped_chars;
682 DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
683 return stripped_chars ? RP_FIXED_FULLPATH : RP_FIXED_ABSPATH;
689 static enum rp_status
690 win32_do_capture_rpfix(char *rpbuf, DWORD *rpbuflen_p,
691 u64 capture_root_ino, u64 capture_root_dev)
695 u16 substitute_name_offset;
696 u16 substitute_name_len;
698 size_t target_nchars;
699 enum rp_status status;
701 DWORD rpbuflen = *rpbuflen_p;
705 p_get = get_u32(rpbuf, &rptag);
707 p_get = get_u16(p_get, &substitute_name_offset);
708 p_get = get_u16(p_get, &substitute_name_len);
710 if ((size_t)substitute_name_offset + substitute_name_len > rpbuflen)
712 if (rptag == WIM_IO_REPARSE_TAG_SYMLINK) {
719 target = (wchar_t*)&p_get[substitute_name_offset];
720 target_nchars = substitute_name_len / 2;
721 /* Note: target is not necessarily null-terminated */
723 status = win32_maybe_rpfix_target(target, &target_nchars,
724 capture_root_ino, capture_root_dev);
725 if (status & RP_FIXED) {
726 size_t target_nbytes = target_nchars * 2;
727 size_t print_nbytes = target_nbytes;
728 wchar_t target_copy[target_nchars];
729 wchar_t *print_name = target_copy;
731 if (status == RP_FIXED_FULLPATH) {
735 wmemcpy(target_copy, target, target_nchars);
737 p_put = put_u16(p_put, 0); /* Substitute name offset */
738 p_put = put_u16(p_put, target_nbytes); /* Substitute name length */
739 p_put = put_u16(p_put, target_nbytes + 2); /* Print name offset */
740 p_put = put_u16(p_put, print_nbytes); /* Print name length */
741 if (rptag == WIM_IO_REPARSE_TAG_SYMLINK)
742 p_put = put_u32(p_put, 1);
743 p_put = put_bytes(p_put, target_nbytes, target_copy);
744 p_put = put_u16(p_put, 0);
745 p_put = put_bytes(p_put, print_nbytes, print_name);
746 p_put = put_u16(p_put, 0);
747 rpbuflen = p_put - rpbuf;
748 put_u16(rpbuf + 4, rpbuflen - 8);
749 *rpbuflen_p = rpbuflen;
754 /* Load a reparse point into a WIM inode. It is just stored in memory.
756 * @hFile is the open handle to a reparse point, with permission to read the
759 * @inode is the WIM inode for the reparse point.
762 win32_capture_reparse_point(struct wim_dentry **root_p,
764 struct wim_inode *inode,
766 struct add_image_params *params)
768 DEBUG("Capturing reparse point \"%ls\"", path);
770 /* "Reparse point data, including the tag and optional GUID,
771 * cannot exceed 16 kilobytes." - MSDN */
772 char reparse_point_buf[REPARSE_POINT_MAX_SIZE];
777 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
778 NULL, /* "Not used with this operation; set to NULL" */
779 0, /* "Not used with this operation; set to 0" */
780 reparse_point_buf, /* "A pointer to a buffer that
781 receives the reparse point data */
782 sizeof(reparse_point_buf), /* "The size of the output
787 DWORD err = GetLastError();
788 ERROR("Failed to get reparse data of \"%ls\"", path);
790 return WIMLIB_ERR_READ;
792 if (bytesReturned < 8) {
793 ERROR("Reparse data on \"%ls\" is invalid", path);
794 return WIMLIB_ERR_READ;
796 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
798 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX &&
799 (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
800 inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
802 enum rp_status status;
803 status = win32_do_capture_rpfix(reparse_point_buf,
805 params->capture_root_ino,
806 params->capture_root_dev);
807 if (status == RP_EXCLUDED) {
808 free_dentry(*root_p);
811 } else if (status & RP_FIXED) {
812 inode->i_not_rpfixed = 0;
815 return inode_set_unnamed_stream(inode, reparse_point_buf + 8,
816 bytesReturned - 8, params->lookup_table);
819 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
820 * stream); calculates its SHA1 message digest and either creates a `struct
821 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
822 * wim_lookup_table_entry' for an identical stream.
824 * @path: Path to the file (UTF-16LE).
826 * @path_num_chars: Number of 2-byte characters in @path.
828 * @inode: WIM inode to save the stream into.
830 * @lookup_table: Stream lookup table for the WIM.
832 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
835 * Returns 0 on success; nonzero on failure.
838 win32_capture_stream(const wchar_t *path,
839 size_t path_num_chars,
840 struct wim_inode *inode,
841 struct wim_lookup_table *lookup_table,
842 WIN32_FIND_STREAM_DATA *dat)
844 struct wim_ads_entry *ads_entry;
845 struct wim_lookup_table_entry *lte;
847 wchar_t *stream_name, *colon;
848 size_t stream_name_nchars;
849 bool is_named_stream;
852 size_t spath_buf_nbytes;
853 const wchar_t *relpath_prefix;
854 const wchar_t *colonchar;
856 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
858 /* The stream name should be returned as :NAME:TYPE */
859 stream_name = dat->cStreamName;
860 if (*stream_name != L':')
861 goto out_invalid_stream_name;
863 colon = wcschr(stream_name, L':');
865 goto out_invalid_stream_name;
867 if (wcscmp(colon + 1, L"$DATA")) {
868 /* Not a DATA stream */
875 stream_name_nchars = colon - stream_name;
876 is_named_stream = (stream_name_nchars != 0);
878 if (is_named_stream) {
879 /* Allocate an ADS entry for the named stream. */
880 ads_entry = inode_add_ads_utf16le(inode, stream_name,
881 stream_name_nchars * sizeof(wchar_t));
883 ret = WIMLIB_ERR_NOMEM;
888 /* If zero length stream, no lookup table entry needed. */
889 if ((u64)dat->StreamSize.QuadPart == 0) {
894 /* Create a UTF-16LE string @spath that gives the filename, then a
895 * colon, then the stream name. Or, if it's an unnamed stream, just the
896 * filename. It is MALLOC()'ed so that it can be saved in the
897 * wim_lookup_table_entry if needed.
899 * As yet another special case, relative paths need to be changed to
900 * begin with an explicit "./" so that, for example, a file t:ads, where
901 * :ads is the part we added, is not interpreted as a file on the t:
903 spath_nchars = path_num_chars;
904 relpath_prefix = L"";
906 if (is_named_stream) {
907 spath_nchars += 1 + stream_name_nchars;
909 if (path_num_chars == 1 &&
914 relpath_prefix = L"./";
918 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
919 spath = MALLOC(spath_buf_nbytes);
921 swprintf(spath, L"%ls%ls%ls%ls",
922 relpath_prefix, path, colonchar, stream_name);
924 /* Make a new wim_lookup_table_entry */
925 lte = new_lookup_table_entry();
927 ret = WIMLIB_ERR_NOMEM;
930 lte->file_on_disk = spath;
932 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream)
933 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
935 lte->resource_location = RESOURCE_WIN32;
936 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
939 if (is_named_stream) {
940 stream_id = ads_entry->stream_id;
941 ads_entry->lte = lte;
946 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
952 out_invalid_stream_name:
953 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
954 ret = WIMLIB_ERR_READ;
958 /* Scans a Win32 file for unnamed and named data streams (not reparse point
961 * @path: Path to the file (UTF-16LE).
963 * @path_num_chars: Number of 2-byte characters in @path.
965 * @inode: WIM inode to save the stream into.
967 * @lookup_table: Stream lookup table for the WIM.
969 * @file_size: Size of unnamed data stream. (Used only if alternate
970 * data streams API appears to be unavailable.)
972 * @vol_flags: Flags that specify features of the volume being
975 * Returns 0 on success; nonzero on failure.
978 win32_capture_streams(const wchar_t *path,
979 size_t path_num_chars,
980 struct wim_inode *inode,
981 struct wim_lookup_table *lookup_table,
985 WIN32_FIND_STREAM_DATA dat;
990 DEBUG("Capturing streams from \"%ls\"", path);
992 if (win32func_FindFirstStreamW == NULL ||
993 !(vol_flags & FILE_NAMED_STREAMS))
996 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
997 if (hFind == INVALID_HANDLE_VALUE) {
998 err = GetLastError();
999 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1002 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1003 * points and directories */
1004 if ((inode->i_attributes &
1005 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1006 && err == ERROR_HANDLE_EOF)
1008 DEBUG("ERROR_HANDLE_EOF (ok)");
1011 if (err == ERROR_ACCESS_DENIED) {
1012 ERROR("Failed to look up data streams "
1013 "of \"%ls\": Access denied!\n%ls",
1014 path, capture_access_denied_msg);
1015 return WIMLIB_ERR_READ;
1017 ERROR("Failed to look up data streams "
1018 "of \"%ls\"", path);
1020 return WIMLIB_ERR_READ;
1025 ret = win32_capture_stream(path,
1027 inode, lookup_table,
1030 goto out_find_close;
1031 } while (win32func_FindNextStreamW(hFind, &dat));
1032 err = GetLastError();
1033 if (err != ERROR_HANDLE_EOF) {
1034 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
1036 ret = WIMLIB_ERR_READ;
1042 /* FindFirstStreamW() API is not available, or the volume does not
1043 * support named streams. Only capture the unnamed data stream. */
1044 DEBUG("Only capturing unnamed data stream");
1045 if (inode->i_attributes &
1046 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1050 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
1051 * stream to reduce the code to a call to the
1052 * already-implemented win32_capture_stream() */
1053 wcscpy(dat.cStreamName, L"::$DATA");
1054 dat.StreamSize.QuadPart = file_size;
1055 ret = win32_capture_stream(path,
1057 inode, lookup_table,
1064 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1066 size_t path_num_chars,
1067 struct add_image_params *params,
1068 struct win32_capture_state *state,
1071 struct wim_dentry *root = NULL;
1072 struct wim_inode *inode;
1077 if (exclude_path(path, path_num_chars, params->config, true)) {
1078 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
1079 ERROR("Cannot exclude the root directory from capture");
1080 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1083 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
1084 && params->progress_func)
1086 union wimlib_progress_info info;
1087 info.scan.cur_path = path;
1088 info.scan.excluded = true;
1089 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1094 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
1095 && params->progress_func)
1097 union wimlib_progress_info info;
1098 info.scan.cur_path = path;
1099 info.scan.excluded = false;
1100 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1103 HANDLE hFile = win32_open_existing_file(path,
1104 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1105 if (hFile == INVALID_HANDLE_VALUE) {
1106 err = GetLastError();
1107 ERROR("Win32 API: Failed to open \"%ls\"", path);
1109 ret = WIMLIB_ERR_OPEN;
1113 BY_HANDLE_FILE_INFORMATION file_info;
1114 if (!GetFileInformationByHandle(hFile, &file_info)) {
1115 err = GetLastError();
1116 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1119 ret = WIMLIB_ERR_STAT;
1120 goto out_close_handle;
1123 /* Create a WIM dentry with an associated inode, which may be shared */
1124 ret = inode_table_new_dentry(params->inode_table,
1125 path_basename_with_len(path, path_num_chars),
1126 ((u64)file_info.nFileIndexHigh << 32) |
1127 (u64)file_info.nFileIndexLow,
1128 file_info.dwVolumeSerialNumber,
1131 goto out_close_handle;
1133 ret = win32_get_short_name(root, path);
1135 goto out_close_handle;
1137 inode = root->d_inode;
1139 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1140 goto out_close_handle;
1142 inode->i_attributes = file_info.dwFileAttributes;
1143 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1144 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1145 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1146 inode->i_resolved = 1;
1148 params->add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
1150 if (!(params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)
1151 && (vol_flags & FILE_PERSISTENT_ACLS))
1153 ret = win32_get_security_descriptor(root, params->sd_set,
1155 params->add_image_flags);
1157 goto out_close_handle;
1160 file_size = ((u64)file_info.nFileSizeHigh << 32) |
1161 (u64)file_info.nFileSizeLow;
1163 if (inode_is_directory(inode)) {
1164 /* Directory (not a reparse point) --- recurse to children */
1166 /* But first... directories may have alternate data streams that
1167 * need to be captured. */
1168 ret = win32_capture_streams(path,
1171 params->lookup_table,
1175 goto out_close_handle;
1176 ret = win32_recurse_directory(root,
1182 } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1183 /* Reparse point: save the reparse tag and data. Alternate data
1184 * streams are not captured, if it's even possible for a reparse
1185 * point to have alternate data streams... */
1186 ret = win32_capture_reparse_point(&root, hFile, inode, path, params);
1188 /* Not a directory, not a reparse point; capture the default
1189 * file contents and any alternate data streams. */
1190 ret = win32_capture_streams(path,
1193 params->lookup_table,
1203 free_dentry_tree(root, params->lookup_table);
1208 win32_do_capture_warnings(const struct win32_capture_state *state,
1209 int add_image_flags)
1211 if (state->num_get_sacl_priv_notheld == 0 &&
1212 state->num_get_sd_access_denied == 0)
1216 WARNING("Built dentry tree successfully, but with the following problem(s):");
1217 if (state->num_get_sacl_priv_notheld != 0) {
1218 WARNING("Could not capture SACL (System Access Control List)\n"
1219 " on %lu files or directories.",
1220 state->num_get_sacl_priv_notheld);
1222 if (state->num_get_sd_access_denied != 0) {
1223 WARNING("Could not capture security descriptor at all\n"
1224 " on %lu files or directories.",
1225 state->num_get_sd_access_denied);
1228 "Try running the program as the Administrator to make sure all the\n"
1229 " desired metadata has been captured exactly. However, if you\n"
1230 " do not care about capturing security descriptors correctly, then\n"
1231 " nothing more needs to be done%ls\n",
1232 (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
1233 L", although you might consider\n"
1234 " passing the --no-acls flag to `wimlib-imagex capture' or\n"
1235 " `wimlib-imagex append' to explicitly capture no security\n"
1239 /* Win32 version of capturing a directory tree */
1241 win32_build_dentry_tree(struct wim_dentry **root_ret,
1242 const wchar_t *root_disk_path,
1243 struct add_image_params *params)
1248 struct win32_capture_state state;
1252 path_nchars = wcslen(root_disk_path);
1253 if (path_nchars > 32767)
1254 return WIMLIB_ERR_INVALID_PARAM;
1256 ret = win32_get_file_and_vol_ids(root_disk_path,
1257 ¶ms->capture_root_ino,
1258 ¶ms->capture_root_dev);
1262 win32_get_vol_flags(root_disk_path, &vol_flags);
1264 /* There is no check for overflow later when this buffer is being used!
1265 * But the max path length on NTFS is 32767 characters, and paths need
1266 * to be written specially to even go past 260 characters, so we should
1267 * be okay with 32770 characters. */
1268 path = MALLOC(32770 * sizeof(wchar_t));
1270 return WIMLIB_ERR_NOMEM;
1272 wmemcpy(path, root_disk_path, path_nchars + 1);
1274 memset(&state, 0, sizeof(state));
1275 ret = win32_build_dentry_tree_recursive(root_ret, path,
1276 path_nchars, params,
1280 win32_do_capture_warnings(&state, params->add_image_flags);
1285 win32_set_reparse_data(HANDLE h,
1287 const struct wim_lookup_table_entry *lte,
1288 const wchar_t *path)
1295 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
1299 len = wim_resource_size(lte);
1300 if (len > 16 * 1024 - 8) {
1301 WARNING("\"%ls\": reparse data too long!", path);
1305 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
1306 * leave 8 bytes of space for them at the beginning of the buffer, then
1307 * set them manually. */
1308 buf = alloca(len + 8);
1309 ret = read_full_resource_into_buf(lte, buf + 8, false);
1312 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
1313 *(u16*)(buf + 4) = cpu_to_le16(len);
1314 *(u16*)(buf + 6) = 0;
1316 /* Set the reparse data on the open file using the
1317 * FSCTL_SET_REPARSE_POINT ioctl.
1319 * There are contradictions in Microsoft's documentation for this:
1321 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1322 * lpOverlapped is ignored."
1324 * --- So setting lpOverlapped to NULL is okay since it's ignored.
1326 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1327 * operation returns no output data and lpOutBuffer is NULL,
1328 * DeviceIoControl makes use of lpBytesReturned. After such an
1329 * operation, the value of lpBytesReturned is meaningless."
1331 * --- So lpOverlapped not really ignored, as it affects another
1332 * parameter. This is the actual behavior: lpBytesReturned must be
1333 * specified, even though lpBytesReturned is documented as:
1335 * "Not used with this operation; set to NULL."
1337 DWORD bytesReturned;
1338 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
1340 &bytesReturned /* lpBytesReturned */,
1341 NULL /* lpOverlapped */))
1343 DWORD err = GetLastError();
1344 ERROR("Failed to set reparse data on \"%ls\"", path);
1346 return WIMLIB_ERR_WRITE;
1352 win32_set_compressed(HANDLE hFile, const wchar_t *path)
1354 USHORT format = COMPRESSION_FORMAT_DEFAULT;
1355 DWORD bytesReturned = 0;
1356 if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1357 &format, sizeof(USHORT),
1359 &bytesReturned, NULL))
1361 /* Could be a warning only, but we only call this if the volume
1362 * supports compression. So I'm calling this an error. */
1363 DWORD err = GetLastError();
1364 ERROR("Failed to set compression flag on \"%ls\"", path);
1366 return WIMLIB_ERR_WRITE;
1372 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1374 DWORD bytesReturned = 0;
1375 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1378 &bytesReturned, NULL))
1380 /* Could be a warning only, but we only call this if the volume
1381 * supports sparse files. So I'm calling this an error. */
1382 DWORD err = GetLastError();
1383 WARNING("Failed to set sparse flag on \"%ls\"", path);
1385 return WIMLIB_ERR_WRITE;
1391 * Sets the security descriptor on an extracted file.
1394 win32_set_security_data(const struct wim_inode *inode,
1395 const wchar_t *path,
1396 struct apply_args *args)
1398 PSECURITY_DESCRIPTOR descriptor;
1402 descriptor = wim_const_security_data(args->w)->descriptors[inode->i_security_id];
1404 SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
1405 SACL_SECURITY_INFORMATION |
1406 OWNER_SECURITY_INFORMATION |
1407 GROUP_SECURITY_INFORMATION;
1409 if (SetFileSecurityW(path, securityInformation, descriptor))
1411 err = GetLastError();
1412 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1415 case ERROR_PRIVILEGE_NOT_HELD:
1416 if (securityInformation & SACL_SECURITY_INFORMATION) {
1417 n = args->num_set_sacl_priv_notheld++;
1418 securityInformation &= ~SACL_SECURITY_INFORMATION;
1419 if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1421 "We don't have enough privileges to set the full security\n"
1422 " descriptor on \"%ls\"!\n", path);
1423 if (args->num_set_sd_access_denied +
1424 args->num_set_sacl_priv_notheld == 1)
1426 WARNING("%ls", apply_access_denied_msg);
1428 WARNING("Re-trying with SACL omitted.\n", path);
1429 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1431 "Suppressing further 'privileges not held' error messages when setting\n"
1432 " security descriptors.");
1437 case ERROR_INVALID_OWNER:
1438 case ERROR_ACCESS_DENIED:
1439 n = args->num_set_sd_access_denied++;
1440 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1441 WARNING("Failed to set security descriptor on \"%ls\": "
1442 "Access denied!\n", path);
1443 if (args->num_set_sd_access_denied +
1444 args->num_set_sacl_priv_notheld == 1)
1446 WARNING("%ls", apply_access_denied_msg);
1448 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1450 "Suppressing further access denied error messages when setting\n"
1451 " security descriptors");
1456 ERROR("Failed to set security descriptor on \"%ls\"", path);
1458 return WIMLIB_ERR_WRITE;
1464 win32_extract_chunk(const void *buf, size_t len, void *arg)
1466 HANDLE hStream = arg;
1468 DWORD nbytes_written;
1469 wimlib_assert(len <= 0xffffffff);
1471 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1472 nbytes_written != len)
1474 DWORD err = GetLastError();
1475 ERROR("WriteFile(): write error");
1477 return WIMLIB_ERR_WRITE;
1483 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1485 return extract_wim_resource(lte, wim_resource_size(lte),
1486 win32_extract_chunk, hStream);
1490 do_win32_extract_encrypted_stream(const wchar_t *path,
1491 const struct wim_lookup_table_entry *lte)
1493 ERROR("Extracting encryted streams not implemented");
1494 return WIMLIB_ERR_INVALID_PARAM;
1498 path_is_root_of_drive(const wchar_t *path)
1503 if (*path != L'/' && *path != L'\\') {
1504 if (*(path + 1) == L':')
1509 while (*path == L'/' || *path == L'\\')
1511 return (*path == L'\0');
1515 win32_get_create_flags_and_attributes(DWORD i_attributes)
1520 * Some attributes cannot be set by passing them to CreateFile(). In
1523 * FILE_ATTRIBUTE_DIRECTORY:
1524 * CreateDirectory() must be called instead of CreateFile().
1526 * FILE_ATTRIBUTE_SPARSE_FILE:
1528 * See: win32_set_sparse().
1530 * FILE_ATTRIBUTE_COMPRESSED:
1531 * Not clear from the documentation, but apparently this needs an
1533 * See: win32_set_compressed().
1535 * FILE_ATTRIBUTE_REPARSE_POINT:
1536 * Needs an ioctl, with the reparse data specified.
1537 * See: win32_set_reparse_data().
1539 * In addition, clear any file flags in the attributes that we don't
1540 * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1541 * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1543 attributes = i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1544 FILE_ATTRIBUTE_COMPRESSED |
1545 FILE_ATTRIBUTE_REPARSE_POINT |
1546 FILE_ATTRIBUTE_DIRECTORY |
1547 FILE_FLAG_DELETE_ON_CLOSE |
1548 FILE_FLAG_NO_BUFFERING |
1549 FILE_FLAG_OPEN_NO_RECALL |
1550 FILE_FLAG_OVERLAPPED |
1551 FILE_FLAG_RANDOM_ACCESS |
1552 /*FILE_FLAG_SESSION_AWARE |*/
1553 FILE_FLAG_SEQUENTIAL_SCAN |
1554 FILE_FLAG_WRITE_THROUGH);
1556 FILE_FLAG_OPEN_REPARSE_POINT |
1557 FILE_FLAG_BACKUP_SEMANTICS;
1561 inode_has_special_attributes(const struct wim_inode *inode)
1563 return (inode->i_attributes & (FILE_ATTRIBUTE_COMPRESSED |
1564 FILE_ATTRIBUTE_REPARSE_POINT |
1565 FILE_ATTRIBUTE_SPARSE_FILE)) != 0;
1568 /* Set compression or sparse attributes, and reparse data, if supported by the
1571 win32_set_special_attributes(HANDLE hFile, const struct wim_inode *inode,
1572 struct wim_lookup_table_entry *unnamed_stream_lte,
1573 const wchar_t *path, unsigned vol_flags)
1577 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1578 if (vol_flags & FILE_FILE_COMPRESSION) {
1579 DEBUG("Setting compression flag on \"%ls\"", path);
1580 ret = win32_set_compressed(hFile, path);
1584 DEBUG("Cannot set compression attribute on \"%ls\": "
1585 "volume does not support transparent compression",
1590 if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1591 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1592 DEBUG("Setting sparse flag on \"%ls\"", path);
1593 ret = win32_set_sparse(hFile, path);
1597 DEBUG("Cannot set sparse attribute on \"%ls\": "
1598 "volume does not support sparse files",
1603 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1604 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
1605 DEBUG("Setting reparse data on \"%ls\"", path);
1606 ret = win32_set_reparse_data(hFile, inode->i_reparse_tag,
1607 unnamed_stream_lte, path);
1611 DEBUG("Cannot set reparse data on \"%ls\": volume "
1612 "does not support reparse points", path);
1620 win32_extract_stream(const struct wim_inode *inode,
1621 const wchar_t *path,
1622 const wchar_t *stream_name_utf16,
1623 struct wim_lookup_table_entry *lte,
1626 wchar_t *stream_path;
1630 DWORD creationDisposition = CREATE_ALWAYS;
1632 if (stream_name_utf16) {
1633 /* Named stream. Create a buffer that contains the UTF-16LE
1634 * string [.\]@path:@stream_name_utf16. This is needed to
1635 * create and open the stream using CreateFileW(). I'm not
1636 * aware of any other APIs to do this. Note: the '$DATA' suffix
1637 * seems to be unneeded. Additional note: a "./" prefix needs
1638 * to be added when the path is not absolute to avoid ambiguity
1639 * with drive letters. */
1640 size_t stream_path_nchars;
1642 size_t stream_name_nchars;
1643 const wchar_t *prefix;
1645 path_nchars = wcslen(path);
1646 stream_name_nchars = wcslen(stream_name_utf16);
1647 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1648 if (path[0] != cpu_to_le16(L'\0') &&
1649 path[0] != cpu_to_le16(L'/') &&
1650 path[0] != cpu_to_le16(L'\\') &&
1651 path[1] != cpu_to_le16(L':'))
1654 stream_path_nchars += 2;
1658 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1659 swprintf(stream_path, L"%ls%ls:%ls",
1660 prefix, path, stream_name_utf16);
1662 /* Unnamed stream; its path is just the path to the file itself.
1664 stream_path = (wchar_t*)path;
1666 /* Directories must be created with CreateDirectoryW(). Then
1667 * the call to CreateFileW() will merely open the directory that
1668 * was already created rather than creating a new file. */
1669 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1670 if (!CreateDirectoryW(stream_path, NULL)) {
1671 err = GetLastError();
1673 case ERROR_ALREADY_EXISTS:
1675 case ERROR_ACCESS_DENIED:
1676 if (path_is_root_of_drive(path))
1680 ERROR("Failed to create directory \"%ls\"",
1683 ret = WIMLIB_ERR_MKDIR;
1687 DEBUG("Created directory \"%ls\"", stream_path);
1688 if (!inode_has_special_attributes(inode)) {
1692 DEBUG("Directory \"%ls\" has special attributes!",
1694 creationDisposition = OPEN_EXISTING;
1698 DEBUG("Opening \"%ls\"", stream_path);
1699 h = CreateFileW(stream_path,
1700 GENERIC_READ | GENERIC_WRITE,
1703 creationDisposition,
1704 win32_get_create_flags_and_attributes(inode->i_attributes),
1706 if (h == INVALID_HANDLE_VALUE) {
1707 err = GetLastError();
1708 ERROR("Failed to create \"%ls\"", stream_path);
1710 ret = WIMLIB_ERR_OPEN;
1714 if (stream_name_utf16 == NULL && inode_has_special_attributes(inode)) {
1715 ret = win32_set_special_attributes(h, inode, lte, path,
1718 goto fail_close_handle;
1721 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1723 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1724 stream_path, wim_resource_size(lte));
1725 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED
1726 && stream_name_utf16 == NULL
1727 && (vol_flags & FILE_SUPPORTS_ENCRYPTION))
1729 ret = do_win32_extract_encrypted_stream(stream_path,
1732 ret = do_win32_extract_stream(h, lte);
1735 goto fail_close_handle;
1739 DEBUG("Closing \"%ls\"", stream_path);
1740 if (!CloseHandle(h)) {
1741 err = GetLastError();
1742 ERROR("Failed to close \"%ls\"", stream_path);
1744 ret = WIMLIB_ERR_WRITE;
1752 ERROR("Error extracting %ls", stream_path);
1758 * Creates a file, directory, or reparse point and extracts all streams to it
1759 * (unnamed data stream and/or reparse point stream, plus any alternate data
1760 * streams). This in Win32-specific code.
1762 * @inode: WIM inode for this file or directory.
1763 * @path: UTF-16LE external path to extract the inode to.
1765 * Returns 0 on success; nonzero on failure.
1768 win32_extract_streams(const struct wim_inode *inode,
1769 const wchar_t *path, u64 *completed_bytes_p,
1772 struct wim_lookup_table_entry *unnamed_lte;
1775 unnamed_lte = inode_unnamed_lte_resolved(inode);
1776 ret = win32_extract_stream(inode, path, NULL, unnamed_lte,
1780 if (unnamed_lte && inode->i_extracted_file == NULL)
1781 *completed_bytes_p += wim_resource_size(unnamed_lte);
1783 if (!(vol_flags & FILE_NAMED_STREAMS))
1785 for (u16 i = 0; i < inode->i_num_ads; i++) {
1786 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1787 if (ads_entry->stream_name_nbytes != 0) {
1788 /* Skip special UNIX data entries (see documentation for
1789 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1790 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1791 && !memcmp(ads_entry->stream_name,
1792 WIMLIB_UNIX_DATA_TAG_UTF16LE,
1793 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1795 ret = win32_extract_stream(inode,
1797 ads_entry->stream_name,
1802 if (ads_entry->lte && inode->i_extracted_file == NULL)
1803 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1810 /* Extract a file, directory, reparse point, or hard link to an
1811 * already-extracted file using the Win32 API */
1813 win32_do_apply_dentry(const wchar_t *output_path,
1814 size_t output_path_num_chars,
1815 struct wim_dentry *dentry,
1816 struct apply_args *args)
1819 struct wim_inode *inode = dentry->d_inode;
1822 if (!args->have_vol_flags) {
1823 win32_get_vol_flags(output_path, &args->vol_flags);
1824 args->have_vol_flags = true;
1825 /* Warn the user about data that may not be extracted. */
1826 if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
1827 WARNING("Volume does not support sparse files!\n"
1828 " Sparse files will be extracted as non-sparse.");
1829 if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1830 WARNING("Volume does not support reparse points!\n"
1831 " Reparse point data will not be extracted.");
1832 if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
1833 WARNING("Volume does not support named data streams!\n"
1834 " Named data streams will not be extracted.");
1836 if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
1837 WARNING("Volume does not support encryption!\n"
1838 " Encrypted files will be extracted as raw data.");
1840 if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
1841 WARNING("Volume does not support transparent compression!\n"
1842 " Compressed files will be extracted as non-compressed.");
1844 if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
1845 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
1846 ERROR("Strict ACLs requested, but the volume does not "
1848 return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
1850 WARNING("Volume does not support persistent ACLS!\n"
1851 " File permissions will not be extracted.");
1856 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1857 /* Linked file, with another name already extracted. Create a
1860 /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
1861 * but it's only available on Windows 7 and later. So no use
1862 * even checking it, really. Instead, CreateHardLinkW() will
1863 * apparently return ERROR_INVALID_FUNCTION if the volume does
1864 * not support hard links. */
1865 DEBUG("Creating hard link \"%ls => %ls\"",
1866 output_path, inode->i_extracted_file);
1867 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
1870 err = GetLastError();
1871 if (err != ERROR_INVALID_FUNCTION) {
1872 ERROR("Can't create hard link \"%ls => %ls\"",
1873 output_path, inode->i_extracted_file);
1875 return WIMLIB_ERR_LINK;
1877 args->num_hard_links_failed++;
1878 if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
1879 WARNING("Can't create hard link \"%ls => %ls\":\n"
1880 " Volume does not support hard links!\n"
1881 " Falling back to extracting a copy of the file.",
1882 output_path, inode->i_extracted_file);
1883 } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
1884 WARNING("Suppressing further hard linking warnings...");
1889 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1890 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1892 WARNING("Skipping extraction of reparse point \"%ls\":\n"
1893 " Not supported by destination filesystem",
1895 struct wim_lookup_table_entry *lte;
1896 lte = inode_unnamed_lte_resolved(inode);
1898 args->progress.extract.completed_bytes += wim_resource_size(lte);
1902 /* Create the file, directory, or reparse point, and extract the
1904 ret = win32_extract_streams(inode, output_path,
1905 &args->progress.extract.completed_bytes,
1910 if (inode->i_security_id >= 0 &&
1911 !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
1912 && (args->vol_flags & FILE_PERSISTENT_ACLS))
1914 ret = win32_set_security_data(inode, output_path, args);
1918 if (inode->i_nlink > 1) {
1919 /* Save extracted path for a later call to
1920 * CreateHardLinkW() if this inode has multiple links.
1922 inode->i_extracted_file = WSTRDUP(output_path);
1923 if (!inode->i_extracted_file)
1924 ret = WIMLIB_ERR_NOMEM;
1929 /* Set timestamps on an extracted file using the Win32 API */
1931 win32_do_apply_dentry_timestamps(const wchar_t *path,
1932 size_t path_num_chars,
1933 const struct wim_dentry *dentry,
1934 const struct apply_args *args)
1938 const struct wim_inode *inode = dentry->d_inode;
1940 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1941 !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1943 /* Skip reparse points not extracted */
1947 /* Windows doesn't let you change the timestamps of the root directory
1948 * (at least on FAT, which is dumb but expected since FAT doesn't store
1949 * any metadata about the root directory...) */
1950 if (path_is_root_of_drive(path))
1953 DEBUG("Opening \"%ls\" to set timestamps", path);
1954 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1955 if (h == INVALID_HANDLE_VALUE) {
1956 err = GetLastError();
1960 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1961 .dwHighDateTime = inode->i_creation_time >> 32};
1962 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1963 .dwHighDateTime = inode->i_last_access_time >> 32};
1964 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1965 .dwHighDateTime = inode->i_last_write_time >> 32};
1967 DEBUG("Calling SetFileTime() on \"%ls\"", path);
1968 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1969 err = GetLastError();
1973 DEBUG("Closing \"%ls\"", path);
1974 if (!CloseHandle(h)) {
1975 err = GetLastError();
1980 /* Only warn if setting timestamps failed; still return 0. */
1981 WARNING("Can't set timestamps on \"%ls\"", path);
1987 /* Replacement for POSIX fsync() */
1994 h = (HANDLE)_get_osfhandle(fd);
1995 if (h == INVALID_HANDLE_VALUE) {
1996 err = GetLastError();
1997 ERROR("Could not get Windows handle for file descriptor");
2002 if (!FlushFileBuffers(h)) {
2003 err = GetLastError();
2004 ERROR("Could not flush file buffers to disk");
2012 /* Use the Win32 API to get the number of processors */
2014 win32_get_number_of_processors()
2016 SYSTEM_INFO sysinfo;
2017 GetSystemInfo(&sysinfo);
2018 return sysinfo.dwNumberOfProcessors;
2021 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
2022 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
2023 * really does the right thing under all circumstances. */
2025 realpath(const wchar_t *path, wchar_t *resolved_path)
2028 wimlib_assert(resolved_path == NULL);
2031 ret = GetFullPathNameW(path, 0, NULL, NULL);
2033 err = GetLastError();
2037 resolved_path = TMALLOC(ret);
2040 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2042 err = GetLastError();
2043 free(resolved_path);
2044 resolved_path = NULL;
2052 return resolved_path;
2055 /* rename() on Windows fails if the destination file exists. And we need to
2056 * make it work on wide characters. Fix it. */
2058 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2060 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2063 /* As usual, the possible error values are not documented */
2064 DWORD err = GetLastError();
2065 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2073 /* Replacement for POSIX fnmatch() (partial functionality only) */
2075 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2077 if (PathMatchSpecW(string, pattern))
2083 /* truncate() replacement */
2085 win32_truncate_replacement(const wchar_t *path, off_t size)
2087 DWORD err = NO_ERROR;
2088 LARGE_INTEGER liOffset;
2090 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2091 if (h == INVALID_HANDLE_VALUE)
2094 liOffset.QuadPart = size;
2095 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2096 goto fail_close_handle;
2098 if (!SetEndOfFile(h))
2099 goto fail_close_handle;
2104 err = GetLastError();
2107 if (err == NO_ERROR)
2108 err = GetLastError();
2109 ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2116 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2117 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2118 * linked in by Visual Studio...?). */
2120 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2122 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2124 pthread_mutex_lock(&strerror_lock);
2125 mbstowcs(buf, strerror(errnum), buflen);
2126 buf[buflen - 1] = '\0';
2127 pthread_mutex_unlock(&strerror_lock);
2131 #endif /* __WIN32__ */